feat: verify safe whitespace fixes before atomic writeback
This commit is contained in:
1 parent
94c36270fa
commit
1f4e120a53
11 files changed
+416
-11
No files matched your search
+17
-7
@@ -8,6 +8,7 @@ use crate::{
|
||||
diagnostics::{DocumentReport, FailOn, LintRun},
|
||||
engine::analyze_document,
|
||||
error::{io, LintError, Result},
|
||||
fix::fix_project,
|
||||
input::{MarqdoRunner, ProjectInput},
|
||||
rules,
|
||||
};
|
||||
@@ -29,6 +30,8 @@ pub struct Cli {
|
||||
fail_on: FailOnArg,
|
||||
#[arg(long, value_enum, value_name = "MODE")]
|
||||
fix: Option<FixMode>,
|
||||
#[arg(long, requires = "fix", help = "校验并显示修复差异")]
|
||||
dry_run: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
@@ -97,11 +100,6 @@ pub fn run() -> Result<i32> {
|
||||
Command::Rules => list_rules(cli.format),
|
||||
};
|
||||
}
|
||||
if cli.fix.is_some() {
|
||||
return Err(LintError::Config(
|
||||
"当前构建尚未启用写回;请使用人工建议".into(),
|
||||
));
|
||||
}
|
||||
let config = LintConfig::discover(cli.config.as_deref())?;
|
||||
let effective = config.resolve(cli.profile.map(Into::into))?;
|
||||
let entries = discover_entries(&cli.paths)?;
|
||||
@@ -112,13 +110,25 @@ pub fn run() -> Result<i32> {
|
||||
if inspected.contains(&entry) {
|
||||
continue;
|
||||
}
|
||||
let project = ProjectInput::load(&entry, &runner)?;
|
||||
let mut project = ProjectInput::load(&entry, &runner)?;
|
||||
let refusal = if cli.fix.is_some() {
|
||||
let outcome = fix_project(&project, &runner, cli.dry_run, &mut std::io::stderr().lock())?;
|
||||
if outcome.changed {
|
||||
project = ProjectInput::load(&entry, &runner)?;
|
||||
}
|
||||
outcome.diagnostic
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for (index, document) in project.documents.iter().enumerate() {
|
||||
if !inspected.insert(document.source.path.clone()) {
|
||||
continue;
|
||||
}
|
||||
let path = logical_path(&project, index);
|
||||
let analysis = analyze_document(document, &effective);
|
||||
let mut analysis = analyze_document(document, &effective);
|
||||
if document.source.path == project.entry {
|
||||
analysis.diagnostics.splice(0..0, refusal.clone());
|
||||
}
|
||||
run.reports.push(DocumentReport::new(
|
||||
document,
|
||||
project.analysis_status,
|
||||
|
||||
@@ -112,6 +112,9 @@ pub struct EffectiveConfig {
|
||||
impl EffectiveConfig {
|
||||
pub fn apply(&self, path: &str, diagnostics: &mut Vec<Diagnostic>) {
|
||||
diagnostics.retain_mut(|diagnostic| {
|
||||
if diagnostic.id == "MQD-SAFETY-001" {
|
||||
return true;
|
||||
}
|
||||
if let Some(level) = self.levels.get(&diagnostic.id).copied() {
|
||||
let Some(severity) = level.severity() else {
|
||||
return false;
|
||||
|
||||
@@ -213,7 +213,10 @@ impl LintRun {
|
||||
}
|
||||
let failed = self.reports.iter().any(|report| {
|
||||
report.diagnostics.iter().any(|diagnostic| {
|
||||
match (fail_on, diagnostic.severity) {
|
||||
if diagnostic.id == "MQD-SAFETY-001" {
|
||||
return true;
|
||||
}
|
||||
match (fail_on, diagnostic.severity) {
|
||||
(FailOn::Never, _) => false,
|
||||
(FailOn::Info, _) => true,
|
||||
(FailOn::Warning, Severity::Warning | Severity::Error) => true,
|
||||
|
||||
@@ -18,6 +18,8 @@ pub enum LintError {
|
||||
Protocol(String),
|
||||
#[error("Marqdo 核心调用失败:{0}")]
|
||||
Core(String),
|
||||
#[error("{0}")]
|
||||
UnsafeFix(String),
|
||||
#[error("配置错误:{0}")]
|
||||
Config(String),
|
||||
}
|
||||
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
//! Stage whitespace edits in a separate checkout layout before touching source files.
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fs,
|
||||
io::Write,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use serde_json::Value;
|
||||
use similar::TextDiff;
|
||||
use tempfile::{tempdir, NamedTempFile};
|
||||
|
||||
use crate::{
|
||||
alignment::align_function,
|
||||
diagnostics::Diagnostic,
|
||||
error::{io, LintError, Result},
|
||||
input::{project_root, AnalysisStatus, MarkdownOrigin, MarqdoRunner, ProjectInput},
|
||||
model::Span,
|
||||
};
|
||||
|
||||
type Candidates = BTreeMap<PathBuf, String>;
|
||||
|
||||
pub struct FixOutcome {
|
||||
pub changed: bool,
|
||||
pub diagnostic: Option<Diagnostic>,
|
||||
}
|
||||
|
||||
pub fn fix_project(
|
||||
project: &ProjectInput,
|
||||
runner: &MarqdoRunner,
|
||||
dry_run: bool,
|
||||
output: &mut impl Write,
|
||||
) -> Result<FixOutcome> {
|
||||
let candidates = project
|
||||
.documents
|
||||
.iter()
|
||||
.filter_map(|document| {
|
||||
let original = document.source.text();
|
||||
let candidate = whitespace_candidate(original);
|
||||
(candidate != original).then(|| (document.source.path.clone(), candidate))
|
||||
})
|
||||
.collect::<Candidates>();
|
||||
if candidates.is_empty() {
|
||||
return Ok(FixOutcome { changed: false, diagnostic: None });
|
||||
}
|
||||
|
||||
if let Err(error) = verify(project, runner, &candidates) {
|
||||
return Ok(FixOutcome {
|
||||
changed: false,
|
||||
diagnostic: Some(
|
||||
Diagnostic::new("MQD-SAFETY-001", Span::new(0, 0))
|
||||
.with_message(format!("自动修复已拒绝:{error}")),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
// Prepare every replacement before publishing any of them.
|
||||
let mut pending = Vec::new();
|
||||
for document in &project.documents {
|
||||
let path = &document.source.path;
|
||||
let Some(candidate) = candidates.get(path) else { continue };
|
||||
let diff = TextDiff::from_lines(document.source.text(), candidate);
|
||||
writeln!(output, "{}", diff.unified_diff().header(
|
||||
&format!("{} (原文)", path.display()),
|
||||
&format!("{} (候选)", path.display()),
|
||||
)).map_err(|error| io("diff 输出", error))?;
|
||||
if !dry_run {
|
||||
pending.push((path, prepare_replacement(path, candidate)?));
|
||||
}
|
||||
}
|
||||
ensure_sources_unchanged(project)?;
|
||||
for (path, file) in pending {
|
||||
file.persist(path).map_err(|error| io(path, error.error))?;
|
||||
}
|
||||
Ok(FixOutcome { changed: !dry_run, diagnostic: None })
|
||||
}
|
||||
|
||||
fn whitespace_candidate(original: &str) -> String {
|
||||
let mut candidate = String::with_capacity(original.len() + 1);
|
||||
for line in original.split_inclusive('\n') {
|
||||
let (content, ending) = if let Some(content) = line.strip_suffix("\r\n") {
|
||||
(content, "\r\n")
|
||||
} else if let Some(content) = line.strip_suffix('\n') {
|
||||
(content, "\n")
|
||||
} else {
|
||||
(line, "")
|
||||
};
|
||||
if !content.bytes().all(|byte| matches!(byte, b' ' | b'\t')) {
|
||||
candidate.push_str(content);
|
||||
}
|
||||
candidate.push_str(ending);
|
||||
}
|
||||
if !candidate.is_empty() && !candidate.ends_with('\n') {
|
||||
let ending = if original.lines().next().is_some_and(|line| {
|
||||
original[line.len()..].starts_with("\r\n")
|
||||
}) {
|
||||
"\r\n"
|
||||
} else {
|
||||
"\n"
|
||||
};
|
||||
candidate.push_str(ending);
|
||||
}
|
||||
candidate
|
||||
}
|
||||
|
||||
fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates) -> Result<()> {
|
||||
require_complete(project)?;
|
||||
ensure_sources_unchanged(project)?;
|
||||
let root = project_root(&project.entry);
|
||||
let staged = tempdir().map_err(|error| io("修复验证目录", error))?;
|
||||
for name in ["marqdo.yaml", "marqdo.lock"] {
|
||||
let file = root.join(name);
|
||||
match fs::read(&file) {
|
||||
Ok(bytes) => fs::write(staged.path().join(name), bytes).map_err(|error| io(&file, error))?,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(io(&file, error)),
|
||||
}
|
||||
}
|
||||
|
||||
for document in &project.documents {
|
||||
let path = &document.source.path;
|
||||
let shadow = staged.path().join(relative_to(path, &root)?);
|
||||
let parent = shadow.parent().expect("staging file has a parent");
|
||||
fs::create_dir_all(parent).map_err(|error| io(parent, error))?;
|
||||
let bytes = candidates.get(path)
|
||||
.map_or(document.source.bytes.as_slice(), |candidate| candidate.as_bytes());
|
||||
fs::write(&shadow, bytes).map_err(|error| io(&shadow, error))?;
|
||||
}
|
||||
|
||||
let entry = staged.path().join(relative_to(&project.entry, &root)?);
|
||||
let checked = ProjectInput::load(entry, runner)?;
|
||||
require_complete(&checked)?;
|
||||
let original = project.analysis.as_ref().expect("checked by require_complete");
|
||||
let revised = checked.analysis.as_ref().expect("checked by require_complete");
|
||||
let changed_modules: Vec<_> = project.documents.iter()
|
||||
.filter(|document| candidates.contains_key(&document.source.path))
|
||||
.filter_map(|document| document.module.as_ref().map(|module| module.id.as_str()))
|
||||
.collect();
|
||||
if analysis_fingerprint(&original.raw, &changed_modules)
|
||||
!= analysis_fingerprint(&revised.raw, &changed_modules)
|
||||
{
|
||||
return Err(refusal("Analysis 中的函数、绑定、资源或执行语义发生变化"));
|
||||
}
|
||||
|
||||
for document in &project.documents {
|
||||
let path = &document.source.path;
|
||||
if !candidates.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
let shadow = staged.path().join(relative_to(path, &root)?);
|
||||
let revised = checked.documents.iter().find(|candidate| candidate.source.path == shadow)
|
||||
.ok_or_else(|| refusal("候选文档缺少 Analysis 模块"))?;
|
||||
let payloads = |document: &crate::input::SourceDocument| {
|
||||
document.markdown.carriers.iter().map(|carrier| (carrier.kind, carrier.payload.clone()))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
let mut before_ast = runner.inspect(path)?;
|
||||
let mut after_ast = runner.inspect(&shadow)?;
|
||||
strip_spans(&mut before_ast);
|
||||
strip_spans(&mut after_ast);
|
||||
if before_ast != after_ast || payloads(document) != payloads(revised) {
|
||||
return Err(refusal("Markdown 结构、文字或执行载荷发生变化"));
|
||||
}
|
||||
}
|
||||
ensure_sources_unchanged(project)
|
||||
}
|
||||
|
||||
fn require_complete(project: &ProjectInput) -> Result<()> {
|
||||
if project.analysis_status != AnalysisStatus::Complete || project.analysis.is_none() {
|
||||
return Err(refusal("无法取得完整的 Analysis v2"));
|
||||
}
|
||||
for document in &project.documents {
|
||||
if document.markdown_origin != MarkdownOrigin::MarqdoInspect
|
||||
|| document.module.as_ref().is_none_or(|module| {
|
||||
module.functions.iter().any(|function| {
|
||||
!align_function(&document.markdown, function).complete
|
||||
})
|
||||
})
|
||||
{
|
||||
return Err(refusal("公开 AST 与 Analysis 无法完整对齐"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn analysis_fingerprint(analysis: &Value, changed_modules: &[&str]) -> Value {
|
||||
let mut normalized = analysis.clone();
|
||||
// A workspace snapshot root_id is itself a digest of the source digests.
|
||||
if let Some(project) = normalized["project"].as_object_mut() {
|
||||
if project.get("identity_kind").and_then(Value::as_str) == Some("workspace_snapshot") {
|
||||
project.remove("root_id");
|
||||
}
|
||||
}
|
||||
if let Some(modules) = normalized["modules"].as_array_mut() {
|
||||
for module in modules {
|
||||
if module["id"].as_str().is_some_and(|id| changed_modules.contains(&id)) {
|
||||
module.as_object_mut().expect("module id is a field").remove("source_digest");
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(diagnostics) = normalized["diagnostics"].as_array_mut() {
|
||||
for diagnostic in diagnostics.iter_mut().filter_map(Value::as_object_mut) {
|
||||
diagnostic.remove("line");
|
||||
diagnostic.remove("column");
|
||||
}
|
||||
}
|
||||
strip_spans(&mut normalized);
|
||||
normalized
|
||||
}
|
||||
|
||||
fn strip_spans(value: &mut Value) {
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
fields.retain(|key, field| {
|
||||
let position = matches!(key.as_str(), "span" | "heading_span" | "condition_span" | "key_span");
|
||||
let span = field.as_object().is_some_and(|object| {
|
||||
object.len() == 2 && object.get("start").and_then(Value::as_u64).is_some()
|
||||
&& object.get("end").and_then(Value::as_u64).is_some()
|
||||
});
|
||||
!(position && (span || field.is_null()))
|
||||
});
|
||||
fields.values_mut().for_each(strip_spans);
|
||||
}
|
||||
Value::Array(values) => values.iter_mut().for_each(strip_spans),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn relative_to<'a>(path: &'a Path, root: &Path) -> Result<&'a Path> {
|
||||
path.strip_prefix(root)
|
||||
.map_err(|_| refusal("源码不在可重建的项目根目录中"))
|
||||
}
|
||||
|
||||
fn ensure_sources_unchanged(project: &ProjectInput) -> Result<()> {
|
||||
for document in &project.documents {
|
||||
let path = &document.source.path;
|
||||
if fs::read(path).map_err(|error| io(path, error))? != document.source.bytes {
|
||||
return Err(refusal("验证期间源码已发生变化"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prepare_replacement(path: &Path, candidate: &str) -> Result<NamedTempFile> {
|
||||
let mut file = NamedTempFile::new_in(path.parent().expect("canonical path has parent"))
|
||||
.map_err(|error| io(path, error))?;
|
||||
let metadata = fs::metadata(path).map_err(|error| io(path, error))?;
|
||||
file.write_all(candidate.as_bytes()).map_err(|error| io(path, error))?;
|
||||
file.as_file().set_permissions(metadata.permissions()).map_err(|error| io(path, error))?;
|
||||
file.as_file().sync_all().map_err(|error| io(path, error))?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn refusal(message: &str) -> LintError {
|
||||
LintError::UnsafeFix(message.into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn t27_verifier_rejects_a_list_layout_change_even_with_unchanged_execution() {
|
||||
let Some(core) = std::env::var_os("MARQDO_BIN") else { return };
|
||||
let runner = MarqdoRunner::discover(Some(Path::new(&core))).unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("index.mq.md");
|
||||
let original = "## @exec choice\n\n**x = 0**\n\n1. `if true`\n\n **x = 1**\n\n`end`\n\n*return x*\n";
|
||||
let revised = original.replace("1. ", "").replace(" **", "**");
|
||||
fs::write(&file, original).unwrap();
|
||||
let project = ProjectInput::load(&file, &runner).unwrap();
|
||||
let candidates = BTreeMap::from([(project.entry.clone(), revised)]);
|
||||
let error = verify(&project, &runner, &candidates).unwrap_err();
|
||||
assert!(error.to_string().contains("Markdown"), "{error}");
|
||||
assert_eq!(fs::read_to_string(file).unwrap(), original);
|
||||
}
|
||||
}
|
||||
@@ -5,3 +5,4 @@ mod project;
|
||||
pub use fallback::{fallback_ast, profile_options};
|
||||
pub use marqdo::{CheckOutcome, MarqdoRunner};
|
||||
pub use project::{AnalysisStatus, MarkdownOrigin, ProjectInput, SourceDocument};
|
||||
pub(crate) use project::project_root;
|
||||
@@ -155,7 +155,7 @@ fn read_document(
|
||||
}
|
||||
}
|
||||
|
||||
fn project_root(entry: &Path) -> PathBuf {
|
||||
pub(crate) fn project_root(entry: &Path) -> PathBuf {
|
||||
let mut current = entry.parent().unwrap_or(Path::new("."));
|
||||
loop {
|
||||
if current.join("marqdo.yaml").is_file() {
|
||||
|
||||
@@ -10,3 +10,4 @@ pub mod model;
|
||||
pub mod rules;
|
||||
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
pub mod fix;
|
||||
Reference in new issue
Block a user