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,17 +17,26 @@ cargo build --locked
|
||||
|
||||
运行测试时需要兼容的冻结核心,并通过 `MARQDO_BIN` 指定其绝对路径。工具只调用公开的 `inspect --ast --json` 和 `check --emit`,不链接核心私有 crate。
|
||||
|
||||
## 目标命令
|
||||
## 使用
|
||||
|
||||
```bash
|
||||
marqdo-lint index.mq.md
|
||||
marqdo-lint . --profile recommended --format json
|
||||
marqdo-lint explain MQD-BRANCH-001
|
||||
marqdo-lint rules
|
||||
marqdo-lint index.mq.md --fix safe --dry-run
|
||||
marqdo-lint index.mq.md --fix safe
|
||||
```
|
||||
|
||||
打包后可通过 Tool v1 安装为 `marqdo lint`。完整设计、规则和安全边界见 `docs/`。
|
||||
```bash
|
||||
./scripts/package-tool.sh
|
||||
marqdo tool install .cache/tool-bundle/tool.json
|
||||
marqdo lint index.mq.md
|
||||
```
|
||||
|
||||
直接运行时,`MARQDO_BIN` 可以指定冻结核心的绝对路径。工具默认从当前目录读取 `marqdo-lint.toml`,也可使用 `--config FILE` 指定配置。目录内有 `index.mq.md` 时从该入口加载项目,否则递归查找 `.mq.md` 文件。
|
||||
|
||||
默认 `--fail-on warning`。退出码 `0` 表示检查完成且低于门槛,`1` 表示达到门槛或安全修复被拒绝,`2` 表示分析不可用、配置或工具错误。JSON 报告格式和配置示例见 [命令参考](docs/CLI.md)。
|
||||
|
||||
## 发布状态
|
||||
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
# 命令参考
|
||||
|
||||
`rules` 列出规则,`explain RULE_ID` 显示规则的依据、严重度、建议和修复级别。`--format json` 同样适用于这两个命令。
|
||||
|
||||
## 配置
|
||||
|
||||
```toml
|
||||
schema_version = 1
|
||||
profile = "recommended"
|
||||
min_narrative_ratio = 0.50
|
||||
short_function_max_statements = 4
|
||||
|
||||
[rules]
|
||||
"MQD-STYLE-001" = "off"
|
||||
|
||||
[[suppress]]
|
||||
path = "index.mq.md"
|
||||
rule = "MQD-PARAM-001"
|
||||
function = "计算折扣"
|
||||
reason = "参数约束在同目录的商品契约中集中维护"
|
||||
|
||||
[fix]
|
||||
mode = "safe-only"
|
||||
require_semantic_equivalence = true
|
||||
```
|
||||
|
||||
`strict-doc` 将解释覆盖类提示提高到 warning,`minimal` 保留核心布局检查,`migration` 淡化叙述比例并暂停部分排版提示。`--profile` 优先于配置的 profile,单条规则覆盖在 profile 之后应用。抑制项按报告路径、规则和可选的函数名及精确字节区间匹配。安全拒绝诊断不会被关闭。
|
||||
|
||||
## 报告
|
||||
|
||||
[JSON Schema](../schemas/marqdo-lint-v1.schema.json) 定义单文件报告和多文件报告。多文件报告将单文件报告按路径排序,并附汇总。源码路径优先相对于调用目录,目录之外的模块使用 Analysis 中的项目相对路径。诊断按起始偏移、结束偏移和 Rule ID 排序。所有 span 均为原始 UTF-8 字节中的半开区间,摘要是原始字节的 SHA-256,格式为小写十六进制加 `sha256:` 前缀。
|
||||
|
||||
只有报告恰有一个函数时,顶层 `metrics.narrative_ratio` 才使用该函数的比例。缺少分母、缺少分析或报告含多个函数时该值为 `null`,多函数各自的比例位于 `metrics.functions`。人类输出用从 1 开始的行和 Unicode 代码点列。
|
||||
|
||||
## 安全空白修复
|
||||
|
||||
`--fix safe --dry-run` 验证并将 unified diff 写到 stderr。去掉 `--dry-run` 后会保留权限并逐文件原子替换。JSON 仍写到 stdout。当前只尝试清理纯空格或制表符行和补文件末尾换行。如果这些字节属于代码围栏、前置元数据或其他保留原文的节点,验证会拒绝写回。
|
||||
|
||||
候选在临时目录中保留项目相对路径,使用相同核心重新检查。比较完整公开 AST、执行载荷顺序和规范化 Analysis。其中只略掉源码位置、被编辑模块的源码摘要和无 manifest 时派生的工作区摘要。调用目标、控制、资源和未编辑模块摘要必须一致。临时目录无法复现的依赖会触发拒绝。列表、标题、载体和模式的调整由作者按诊断手动完成。
|
||||
+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;
|
||||
@@ -120,3 +120,61 @@ fn t30_frozen_core_installs_and_dispatches_lint() {
|
||||
let report: Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(report["analysis_status"], "complete");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_fix_previews_then_persists_verified_whitespace_in_a_manifest_project() {
|
||||
if std::env::var_os("MARQDO_BIN").is_none() {
|
||||
return;
|
||||
}
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let source = temp.path().join("index.mq.md");
|
||||
let multi = fixtures().join("multi");
|
||||
fs::copy(multi.join("marqdo.yaml"), temp.path().join("marqdo.yaml")).unwrap();
|
||||
fs::copy(multi.join("geometry.mq.md"), temp.path().join("geometry.mq.md")).unwrap();
|
||||
let clean = fs::read_to_string(multi.join("index.mq.md")).unwrap();
|
||||
let original = clean.replace("## @exec main\n\n", "## @exec main\n \t\n");
|
||||
assert_ne!(original, clean);
|
||||
fs::write(&source, &original).unwrap();
|
||||
let fix = |args: &[&str]| {
|
||||
lint()
|
||||
.current_dir(temp.path())
|
||||
.args(["index.mq.md", "--fix", "safe", "--format", "json", "--fail-on", "never"])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let preview = fix(&["--dry-run"]);
|
||||
assert!(preview.status.success(), "{:?}", preview);
|
||||
assert!(String::from_utf8_lossy(&preview.stderr).contains("@@"));
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), original);
|
||||
let applied = fix(&[]);
|
||||
assert!(applied.status.success(), "{:?}", applied);
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), clean);
|
||||
let repeated = fix(&[]);
|
||||
assert!(repeated.status.success() && repeated.stderr.is_empty(), "{:?}", repeated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_fix_rejects_changes_to_inert_payload_and_unavailable_analysis() {
|
||||
if std::env::var_os("MARQDO_BIN").is_none() {
|
||||
return;
|
||||
}
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let source = temp.path().join("index.mq.md");
|
||||
for (original, code) in [
|
||||
("## @exec example\n\n```text\n \t\n```\n\n*return 1*\n", 1),
|
||||
("## @exec example\n\n`if true`\n\n*return 1*", 2),
|
||||
] {
|
||||
fs::write(&source, original).unwrap();
|
||||
let output = lint()
|
||||
.current_dir(temp.path())
|
||||
.args(["index.mq.md", "--fix", "safe", "--format", "json", "--fail-on", "never"])
|
||||
.output().unwrap();
|
||||
let report: Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(output.status.code(), Some(code), "{report}");
|
||||
assert!(report["diagnostics"].as_array().unwrap().iter().any(|diagnostic| {
|
||||
diagnostic["id"] == "MQD-SAFETY-001"
|
||||
}), "{report}");
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), original);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user