refactor(xatu): split lint rule framework
This commit is contained in:
@@ -3,7 +3,16 @@ load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library", "rust_test")
|
||||
rust_library(
|
||||
name = "xatu_lib",
|
||||
crate_name = "xatu",
|
||||
srcs = ["lib.rs"],
|
||||
srcs = [
|
||||
"analysis.rs",
|
||||
"diagnostic.rs",
|
||||
"edit.rs",
|
||||
"empty_inherit.rs",
|
||||
"file_set.rs",
|
||||
"lib.rs",
|
||||
"rules.rs",
|
||||
"runner.rs",
|
||||
],
|
||||
deps = [
|
||||
"//third_party/crates:rnix",
|
||||
"//third_party/crates:rowan",
|
||||
|
||||
52
src/xatu/analysis.rs
Normal file
52
src/xatu/analysis.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use std::path::Path;
|
||||
|
||||
use crate::diagnostic::{parse_error_diagnostics, Diagnostic};
|
||||
use crate::edit::Edit;
|
||||
use crate::rules::{self, RuleContext};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct AnalysisOutcome {
|
||||
pub(crate) diagnostics: Vec<Diagnostic>,
|
||||
pub(crate) edits: Vec<Edit>,
|
||||
}
|
||||
|
||||
pub(crate) fn analyze_source(path: &Path, source: &str) -> AnalysisOutcome {
|
||||
let parse = rnix::Root::parse(source);
|
||||
|
||||
if !parse.errors().is_empty() {
|
||||
return AnalysisOutcome {
|
||||
diagnostics: parse_error_diagnostics(path, source, parse.errors()),
|
||||
edits: Vec::new(),
|
||||
};
|
||||
}
|
||||
|
||||
let root = parse.tree();
|
||||
let context = RuleContext {
|
||||
source,
|
||||
root: &root,
|
||||
};
|
||||
let mut findings = Vec::new();
|
||||
|
||||
for rule in rules::all() {
|
||||
rule.check(&context, &mut findings);
|
||||
}
|
||||
|
||||
let mut diagnostics = Vec::with_capacity(findings.len());
|
||||
let mut edits = Vec::new();
|
||||
|
||||
for finding in findings {
|
||||
diagnostics.push(Diagnostic::at_offset(
|
||||
path,
|
||||
source,
|
||||
finding.rule,
|
||||
finding.message,
|
||||
finding.offset,
|
||||
));
|
||||
|
||||
if let Some(fix) = finding.fix {
|
||||
edits.push(fix);
|
||||
}
|
||||
}
|
||||
|
||||
AnalysisOutcome { diagnostics, edits }
|
||||
}
|
||||
91
src/xatu/diagnostic.rs
Normal file
91
src/xatu/diagnostic.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
use std::fmt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const PARSE_ERROR_RULE: &str = "parse_error";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Diagnostic {
|
||||
pub path: PathBuf,
|
||||
pub rule: &'static str,
|
||||
pub message: String,
|
||||
pub line: usize,
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub(crate) fn at_offset(
|
||||
path: &Path,
|
||||
source: &str,
|
||||
rule: &'static str,
|
||||
message: String,
|
||||
offset: usize,
|
||||
) -> Self {
|
||||
let (line, column) = line_column(source, offset);
|
||||
|
||||
Self {
|
||||
path: path.to_path_buf(),
|
||||
rule,
|
||||
message,
|
||||
line,
|
||||
column,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Diagnostic {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
formatter,
|
||||
"{}:{}:{}: {}: {}",
|
||||
self.path.display(),
|
||||
self.line,
|
||||
self.column,
|
||||
self.rule,
|
||||
self.message
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_error_diagnostics(
|
||||
path: &Path,
|
||||
source: &str,
|
||||
errors: &[rnix::ParseError],
|
||||
) -> Vec<Diagnostic> {
|
||||
errors
|
||||
.iter()
|
||||
.map(|error| {
|
||||
Diagnostic::at_offset(
|
||||
path,
|
||||
source,
|
||||
PARSE_ERROR_RULE,
|
||||
error.to_string(),
|
||||
parse_error_offset(error, source.len()),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn parse_error_offset(error: &rnix::ParseError, end_offset: usize) -> usize {
|
||||
let range = match error {
|
||||
rnix::ParseError::Unexpected(range)
|
||||
| rnix::ParseError::UnexpectedExtra(range)
|
||||
| rnix::ParseError::UnexpectedWanted(_, range, _)
|
||||
| rnix::ParseError::UnexpectedDoubleBind(range)
|
||||
| rnix::ParseError::DuplicatedArgs(range, _) => Some(range),
|
||||
rnix::ParseError::UnexpectedEOF
|
||||
| rnix::ParseError::UnexpectedEOFWanted(_)
|
||||
| rnix::ParseError::RecursionLimitExceeded => None,
|
||||
_ => None,
|
||||
};
|
||||
|
||||
range.map_or(end_offset, |range| usize::from(range.start()))
|
||||
}
|
||||
|
||||
fn line_column(source: &str, offset: usize) -> (usize, usize) {
|
||||
let prefix = &source[..offset.min(source.len())];
|
||||
let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
|
||||
let line_start = prefix.rfind('\n').map_or(0, |index| index + 1);
|
||||
let column = prefix[line_start..].chars().count() + 1;
|
||||
|
||||
(line, column)
|
||||
}
|
||||
80
src/xatu/edit.rs
Normal file
80
src/xatu/edit.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Edit {
|
||||
start: usize,
|
||||
end: usize,
|
||||
replacement: String,
|
||||
}
|
||||
|
||||
impl Edit {
|
||||
pub(crate) fn delete_statement(source: &str, start: usize, end: usize) -> Self {
|
||||
Self {
|
||||
start: deletion_start(source, start, end),
|
||||
end: deletion_end(source, start, end),
|
||||
replacement: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply_edits(source: &str, edits: &[Edit]) -> String {
|
||||
let mut fixed = source.to_owned();
|
||||
let mut edits = non_overlapping_edits(edits);
|
||||
|
||||
for edit in edits.drain(..).rev() {
|
||||
fixed.replace_range(edit.start..edit.end, &edit.replacement);
|
||||
}
|
||||
|
||||
fixed
|
||||
}
|
||||
|
||||
fn non_overlapping_edits(edits: &[Edit]) -> Vec<Edit> {
|
||||
let mut sorted = edits.to_vec();
|
||||
sorted.sort_by_key(|edit| (edit.start, edit.end));
|
||||
|
||||
let mut filtered = Vec::new();
|
||||
let mut previous_end = 0;
|
||||
|
||||
for edit in sorted {
|
||||
if edit.start < previous_end {
|
||||
continue;
|
||||
}
|
||||
|
||||
previous_end = edit.end;
|
||||
filtered.push(edit);
|
||||
}
|
||||
|
||||
filtered
|
||||
}
|
||||
|
||||
fn deletion_start(source: &str, start: usize, end: usize) -> usize {
|
||||
let line_start = source[..start].rfind('\n').map_or(0, |index| index + 1);
|
||||
|
||||
if source[line_start..start].trim().is_empty()
|
||||
&& trailing_line_text(source, end).trim().is_empty()
|
||||
{
|
||||
line_start
|
||||
} else {
|
||||
start
|
||||
}
|
||||
}
|
||||
|
||||
fn deletion_end(source: &str, start: usize, end: usize) -> usize {
|
||||
let line_start = source[..start].rfind('\n').map_or(0, |index| index + 1);
|
||||
|
||||
if source[line_start..start].trim().is_empty()
|
||||
&& trailing_line_text(source, end).trim().is_empty()
|
||||
{
|
||||
source[end..]
|
||||
.find('\n')
|
||||
.map_or(end, |relative| end + relative + 1)
|
||||
} else {
|
||||
end
|
||||
}
|
||||
}
|
||||
|
||||
fn trailing_line_text(source: &str, end: usize) -> &str {
|
||||
let line_end = source[end..]
|
||||
.find('\n')
|
||||
.map_or(source.len(), |relative| end + relative);
|
||||
|
||||
&source[end..line_end]
|
||||
}
|
||||
37
src/xatu/empty_inherit.rs
Normal file
37
src/xatu/empty_inherit.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use rnix::ast;
|
||||
use rowan::ast::AstNode;
|
||||
|
||||
use crate::edit::Edit;
|
||||
use crate::rules::{Finding, Rule, RuleContext};
|
||||
|
||||
pub(crate) static RULE: EmptyInherit = EmptyInherit;
|
||||
|
||||
pub(crate) struct EmptyInherit;
|
||||
|
||||
impl Rule for EmptyInherit {
|
||||
fn name(&self) -> &'static str {
|
||||
"empty_inherit"
|
||||
}
|
||||
|
||||
fn check(&self, context: &RuleContext<'_>, findings: &mut Vec<Finding>) {
|
||||
for inherit in context
|
||||
.root
|
||||
.syntax()
|
||||
.descendants()
|
||||
.filter_map(ast::Inherit::cast)
|
||||
{
|
||||
if inherit.attrs().next().is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let range = inherit.syntax().text_range();
|
||||
let start = usize::from(range.start());
|
||||
let end = usize::from(range.end());
|
||||
let fix = Edit::delete_statement(context.source, start, end);
|
||||
|
||||
findings.push(
|
||||
Finding::new(self.name(), "remove empty inherit statement", start).with_fix(fix),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
45
src/xatu/file_set.rs
Normal file
45
src/xatu/file_set.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) fn collect_nix_files(path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let metadata = fs::metadata(path)?;
|
||||
|
||||
if metadata.is_file() {
|
||||
return Ok(if is_nix_file(path) {
|
||||
vec![path.to_path_buf()]
|
||||
} else {
|
||||
Vec::new()
|
||||
});
|
||||
}
|
||||
|
||||
if !metadata.is_dir() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut files = Vec::new();
|
||||
collect_nix_files_from_dir(path, &mut files)?;
|
||||
files.sort();
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn collect_nix_files_from_dir(path: &Path, files: &mut Vec<PathBuf>) -> io::Result<()> {
|
||||
for entry in fs::read_dir(path)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let metadata = entry.metadata()?;
|
||||
|
||||
if metadata.is_dir() {
|
||||
collect_nix_files_from_dir(&path, files)?;
|
||||
} else if metadata.is_file() && is_nix_file(&path) {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_nix_file(path: &Path) -> bool {
|
||||
path.extension() == Some(OsStr::new("nix"))
|
||||
}
|
||||
300
src/xatu/lib.rs
300
src/xatu/lib.rs
@@ -1,295 +1,21 @@
|
||||
use std::fmt;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
use rnix::ast;
|
||||
use rowan::ast::AstNode;
|
||||
mod analysis;
|
||||
mod diagnostic;
|
||||
mod edit;
|
||||
mod empty_inherit;
|
||||
mod file_set;
|
||||
mod rules;
|
||||
mod runner;
|
||||
|
||||
const EMPTY_INHERIT_RULE: &str = "empty_inherit";
|
||||
const PARSE_ERROR_RULE: &str = "parse_error";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunMode {
|
||||
Check,
|
||||
Fix,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunStatus {
|
||||
Clean,
|
||||
Findings,
|
||||
}
|
||||
|
||||
impl RunStatus {
|
||||
pub fn code(self) -> u8 {
|
||||
match self {
|
||||
RunStatus::Clean => 0,
|
||||
RunStatus::Findings => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Diagnostic {
|
||||
pub path: PathBuf,
|
||||
pub rule: &'static str,
|
||||
pub message: String,
|
||||
pub line: usize,
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
impl fmt::Display for Diagnostic {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
formatter,
|
||||
"{}:{}:{}: {}: {}",
|
||||
self.path.display(),
|
||||
self.line,
|
||||
self.column,
|
||||
self.rule,
|
||||
self.message
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
paths: &[PathBuf],
|
||||
mode: RunMode,
|
||||
stdout: &mut impl Write,
|
||||
stderr: &mut impl Write,
|
||||
) -> io::Result<RunStatus> {
|
||||
if paths.is_empty() {
|
||||
writeln!(stderr, "error: provide at least one file or directory")?;
|
||||
return Ok(RunStatus::Findings);
|
||||
}
|
||||
|
||||
let mut status = RunStatus::Clean;
|
||||
|
||||
for input in paths {
|
||||
let files = match collect_nix_files(input) {
|
||||
Ok(files) => files,
|
||||
Err(error) => {
|
||||
writeln!(stderr, "error: {error}")?;
|
||||
status = RunStatus::Findings;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
for file in files {
|
||||
let source = match fs::read_to_string(&file) {
|
||||
Ok(source) => source,
|
||||
Err(error) => {
|
||||
writeln!(stderr, "error: {}: {error}", file.display())?;
|
||||
status = RunStatus::Findings;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let outcome = analyze_source(&file, &source);
|
||||
|
||||
for diagnostic in &outcome.diagnostics {
|
||||
writeln!(stdout, "{diagnostic}")?;
|
||||
}
|
||||
|
||||
if !outcome.diagnostics.is_empty() {
|
||||
status = RunStatus::Findings;
|
||||
}
|
||||
|
||||
if mode == RunMode::Fix && !outcome.edits.is_empty() {
|
||||
let fixed = apply_edits(&source, &outcome.edits);
|
||||
fs::write(&file, fixed)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct AnalysisOutcome {
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
edits: Vec<Edit>,
|
||||
}
|
||||
pub use diagnostic::Diagnostic;
|
||||
pub use runner::{run, RunMode, RunStatus};
|
||||
|
||||
pub fn diagnostics_for_source(path: &Path, source: &str) -> Vec<Diagnostic> {
|
||||
analyze_source(path, source).diagnostics
|
||||
analysis::analyze_source(path, source).diagnostics
|
||||
}
|
||||
|
||||
pub fn fix_source(source: &str) -> String {
|
||||
let outcome = analyze_source(Path::new("<memory>"), source);
|
||||
apply_edits(source, &outcome.edits)
|
||||
}
|
||||
|
||||
fn analyze_source(path: &Path, source: &str) -> AnalysisOutcome {
|
||||
let parse = rnix::Root::parse(source);
|
||||
|
||||
if !parse.errors().is_empty() {
|
||||
return AnalysisOutcome {
|
||||
diagnostics: parse
|
||||
.errors()
|
||||
.iter()
|
||||
.map(|error| {
|
||||
let offset = parse_error_offset(error, source.len());
|
||||
let (line, column) = line_column(source, offset);
|
||||
Diagnostic {
|
||||
path: path.to_path_buf(),
|
||||
rule: PARSE_ERROR_RULE,
|
||||
message: error.to_string(),
|
||||
line,
|
||||
column,
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
edits: Vec::new(),
|
||||
};
|
||||
}
|
||||
|
||||
let root = parse.tree();
|
||||
let mut diagnostics = Vec::new();
|
||||
let mut edits = Vec::new();
|
||||
|
||||
for inherit in root.syntax().descendants().filter_map(ast::Inherit::cast) {
|
||||
if inherit.attrs().next().is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let range = inherit.syntax().text_range();
|
||||
let start = usize::from(range.start());
|
||||
let end = usize::from(range.end());
|
||||
let (line, column) = line_column(source, start);
|
||||
|
||||
diagnostics.push(Diagnostic {
|
||||
path: path.to_path_buf(),
|
||||
rule: EMPTY_INHERIT_RULE,
|
||||
message: "remove empty inherit statement".to_owned(),
|
||||
line,
|
||||
column,
|
||||
});
|
||||
|
||||
edits.push(Edit {
|
||||
start: deletion_start(source, start, end),
|
||||
end: deletion_end(source, start, end),
|
||||
replacement: String::new(),
|
||||
});
|
||||
}
|
||||
|
||||
AnalysisOutcome { diagnostics, edits }
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct Edit {
|
||||
start: usize,
|
||||
end: usize,
|
||||
replacement: String,
|
||||
}
|
||||
|
||||
fn apply_edits(source: &str, edits: &[Edit]) -> String {
|
||||
let mut fixed = source.to_owned();
|
||||
let mut sorted = edits.to_vec();
|
||||
sorted.sort_by_key(|edit| edit.start);
|
||||
|
||||
for edit in sorted.into_iter().rev() {
|
||||
fixed.replace_range(edit.start..edit.end, &edit.replacement);
|
||||
}
|
||||
|
||||
fixed
|
||||
}
|
||||
|
||||
fn deletion_start(source: &str, start: usize, end: usize) -> usize {
|
||||
let line_start = source[..start].rfind('\n').map_or(0, |index| index + 1);
|
||||
|
||||
if source[line_start..start].trim().is_empty() && trailing_line_text(source, end).trim().is_empty()
|
||||
{
|
||||
line_start
|
||||
} else {
|
||||
start
|
||||
}
|
||||
}
|
||||
|
||||
fn deletion_end(source: &str, start: usize, end: usize) -> usize {
|
||||
let line_start = source[..start].rfind('\n').map_or(0, |index| index + 1);
|
||||
|
||||
if source[line_start..start].trim().is_empty() && trailing_line_text(source, end).trim().is_empty()
|
||||
{
|
||||
source[end..]
|
||||
.find('\n')
|
||||
.map_or(end, |relative| end + relative + 1)
|
||||
} else {
|
||||
end
|
||||
}
|
||||
}
|
||||
|
||||
fn trailing_line_text(source: &str, end: usize) -> &str {
|
||||
let line_end = source[end..]
|
||||
.find('\n')
|
||||
.map_or(source.len(), |relative| end + relative);
|
||||
|
||||
&source[end..line_end]
|
||||
}
|
||||
|
||||
fn collect_nix_files(path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let metadata = fs::metadata(path)?;
|
||||
|
||||
if metadata.is_file() {
|
||||
return Ok(if is_nix_file(path) {
|
||||
vec![path.to_path_buf()]
|
||||
} else {
|
||||
Vec::new()
|
||||
});
|
||||
}
|
||||
|
||||
if !metadata.is_dir() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut files = Vec::new();
|
||||
collect_nix_files_from_dir(path, &mut files)?;
|
||||
files.sort();
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn collect_nix_files_from_dir(path: &Path, files: &mut Vec<PathBuf>) -> io::Result<()> {
|
||||
for entry in fs::read_dir(path)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let metadata = entry.metadata()?;
|
||||
|
||||
if metadata.is_dir() {
|
||||
collect_nix_files_from_dir(&path, files)?;
|
||||
} else if metadata.is_file() && is_nix_file(&path) {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_nix_file(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|extension| extension == "nix")
|
||||
}
|
||||
|
||||
fn parse_error_offset(error: &rnix::ParseError, end_offset: usize) -> usize {
|
||||
let range = match error {
|
||||
rnix::ParseError::Unexpected(range)
|
||||
| rnix::ParseError::UnexpectedExtra(range)
|
||||
| rnix::ParseError::UnexpectedWanted(_, range, _)
|
||||
| rnix::ParseError::UnexpectedDoubleBind(range)
|
||||
| rnix::ParseError::DuplicatedArgs(range, _) => Some(range),
|
||||
rnix::ParseError::UnexpectedEOF
|
||||
| rnix::ParseError::UnexpectedEOFWanted(_)
|
||||
| rnix::ParseError::RecursionLimitExceeded => None,
|
||||
_ => None,
|
||||
};
|
||||
|
||||
range.map_or(end_offset, |range| usize::from(range.start()))
|
||||
}
|
||||
|
||||
fn line_column(source: &str, offset: usize) -> (usize, usize) {
|
||||
let prefix = &source[..offset.min(source.len())];
|
||||
let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
|
||||
let line_start = prefix.rfind('\n').map_or(0, |index| index + 1);
|
||||
let column = prefix[line_start..].chars().count() + 1;
|
||||
|
||||
(line, column)
|
||||
let outcome = analysis::analyze_source(Path::new("<memory>"), source);
|
||||
edit::apply_edits(source, &outcome.edits)
|
||||
}
|
||||
|
||||
43
src/xatu/rules.rs
Normal file
43
src/xatu/rules.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
use rnix::Root;
|
||||
|
||||
use crate::edit::Edit;
|
||||
|
||||
pub(crate) struct RuleContext<'a> {
|
||||
pub(crate) source: &'a str,
|
||||
pub(crate) root: &'a Root,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Finding {
|
||||
pub(crate) rule: &'static str,
|
||||
pub(crate) message: String,
|
||||
pub(crate) offset: usize,
|
||||
pub(crate) fix: Option<Edit>,
|
||||
}
|
||||
|
||||
impl Finding {
|
||||
pub(crate) fn new(rule: &'static str, message: impl Into<String>, offset: usize) -> Self {
|
||||
Self {
|
||||
rule,
|
||||
message: message.into(),
|
||||
offset,
|
||||
fix: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_fix(mut self, fix: Edit) -> Self {
|
||||
self.fix = Some(fix);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait Rule: Sync {
|
||||
fn name(&self) -> &'static str;
|
||||
fn check(&self, context: &RuleContext<'_>, findings: &mut Vec<Finding>);
|
||||
}
|
||||
|
||||
static RULES: [&'static dyn Rule; 1] = [&crate::empty_inherit::RULE];
|
||||
|
||||
pub(crate) fn all() -> &'static [&'static dyn Rule] {
|
||||
&RULES
|
||||
}
|
||||
81
src/xatu/runner.rs
Normal file
81
src/xatu/runner.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::analysis::analyze_source;
|
||||
use crate::edit::apply_edits;
|
||||
use crate::file_set::collect_nix_files;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunMode {
|
||||
Check,
|
||||
Fix,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunStatus {
|
||||
Clean,
|
||||
Findings,
|
||||
}
|
||||
|
||||
impl RunStatus {
|
||||
pub fn code(self) -> u8 {
|
||||
match self {
|
||||
RunStatus::Clean => 0,
|
||||
RunStatus::Findings => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
paths: &[PathBuf],
|
||||
mode: RunMode,
|
||||
stdout: &mut impl Write,
|
||||
stderr: &mut impl Write,
|
||||
) -> io::Result<RunStatus> {
|
||||
if paths.is_empty() {
|
||||
writeln!(stderr, "error: provide at least one file or directory")?;
|
||||
return Ok(RunStatus::Findings);
|
||||
}
|
||||
|
||||
let mut status = RunStatus::Clean;
|
||||
|
||||
for input in paths {
|
||||
let files = match collect_nix_files(input) {
|
||||
Ok(files) => files,
|
||||
Err(error) => {
|
||||
writeln!(stderr, "error: {error}")?;
|
||||
status = RunStatus::Findings;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
for file in files {
|
||||
let source = match fs::read_to_string(&file) {
|
||||
Ok(source) => source,
|
||||
Err(error) => {
|
||||
writeln!(stderr, "error: {}: {error}", file.display())?;
|
||||
status = RunStatus::Findings;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let outcome = analyze_source(&file, &source);
|
||||
|
||||
for diagnostic in &outcome.diagnostics {
|
||||
writeln!(stdout, "{diagnostic}")?;
|
||||
}
|
||||
|
||||
if !outcome.diagnostics.is_empty() {
|
||||
status = RunStatus::Findings;
|
||||
}
|
||||
|
||||
if mode == RunMode::Fix && !outcome.edits.is_empty() {
|
||||
let fixed = apply_edits(&source, &outcome.edits);
|
||||
fs::write(&file, fixed)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(status)
|
||||
}
|
||||
Reference in New Issue
Block a user