feat: adopt marqdo 3.0.0-rc.4 public analysis boundary

This commit is contained in:
cflmy committed 2026-11-25 21:18:35 +08:00
1 parent 769550b14b
commit fe18df6c4b
74 files changed
+7618 -5368

No files matched your search

+189 -59
View File
@@ -1,4 +1,5 @@
use std::{
cmp::Ordering,
fs,
path::{Path, PathBuf},
process::{Command, Output},
@@ -6,6 +7,7 @@ use std::{
use serde::Deserialize;
use serde_json::Value;
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;
use crate::error::{io, LintError, Result};
@@ -13,12 +15,15 @@ use crate::error::{io, LintError, Result};
#[derive(Debug, Clone)]
pub struct MarqdoRunner {
binary: PathBuf,
version: SemVer,
}
#[derive(Debug)]
pub struct CheckOutcome {
pub success: bool,
pub analysis: Option<Value>,
pub analysis_bytes: Vec<u8>,
pub artifact_digest: Option<String>,
pub output: String,
pub diagnostics: Vec<CheckDiagnostic>,
}
@@ -66,71 +71,56 @@ impl MarqdoRunner {
.map(Path::to_path_buf)
.or_else(|| std::env::var_os("MARQDO_BIN").map(PathBuf::from))
.unwrap_or_else(|| PathBuf::from("marqdo"));
let runner = Self { binary };
runner.ensure_compatible()?;
Ok(runner)
let output = Command::new(&binary)
.arg("--version")
.output()
.map_err(|error| io(&binary, error))?;
if !output.status.success() {
return Err(LintError::Core(format!(
"无法运行 {} --version:{}",
binary.display(),
format_output(&output)
)));
}
let text = String::from_utf8_lossy(&output.stdout);
let text = text.trim();
let raw = text.strip_prefix("marqdo ").unwrap_or(text);
let version = SemVer::parse(raw).map_err(|error| {
LintError::Protocol(format!(
"无法解析 Marqdo 版本 {raw:?}:{error};需要 Marqdo >=3.0.0-rc.4,<4.0.0"
))
})?;
let minimum = SemVer::parse("3.0.0-rc.4").expect("static version");
let maximum = SemVer::parse("4.0.0").expect("static version");
if version < minimum || version >= maximum {
return Err(LintError::Protocol(format!(
"需要 Marqdo >=3.0.0-rc.4,<4.0.0,实际为 {raw};请升级核心并用当前 CLI 重新生成 Analysis,重装 marqdo-lint Tool"
)));
}
Ok(Self { binary, version })
}
pub fn binary(&self) -> &Path {
&self.binary
}
pub fn ensure_compatible(&self) -> Result<()> {
let output = self.run(&[std::ffi::OsStr::new("--version")])?;
if !output.status.success() {
return Err(LintError::Core(format_output(&output)));
}
let version = String::from_utf8_lossy(&output.stdout);
let version = version
.trim()
.strip_prefix("marqdo ")
.unwrap_or(version.trim());
let major = version
.split('.')
.next()
.and_then(|part| part.parse::<u64>().ok());
if major != Some(3) {
return Err(LintError::Protocol(format!(
"需要 Marqdo >=3.0.0-beta.1,<4.0.0,实际为 {version}"
)));
}
Ok(())
pub fn version(&self) -> &SemVer {
&self.version
}
pub fn inspect(&self, file: &Path) -> Result<Value> {
let output = Command::new(&self.binary)
.arg("inspect")
.arg(file)
.arg("--ast")
.arg("--json")
.output()
.map_err(|error| io(&self.binary, error))?;
if !output.status.success() {
return Err(LintError::Core(format_output(&output)));
}
let value: Value = serde_json::from_slice(&output.stdout)
.map_err(|error| LintError::Protocol(format!("inspect AST JSON 无效:{error}")))?;
if value.get("command").and_then(Value::as_str) != Some("inspect") {
return Err(LintError::Protocol(
"inspect 输出缺少 command=inspect".into(),
));
}
value
.get("ast")
.cloned()
.ok_or_else(|| LintError::Protocol("inspect 输出缺少 ast 字段".into()))
}
pub fn check(&self, file: &Path) -> Result<CheckOutcome> {
pub fn check(&self, file: &Path, refs: bool) -> Result<CheckOutcome> {
let temporary = NamedTempFile::new().map_err(|error| io("Analysis 临时文件", error))?;
let output = Command::new(&self.binary)
let mut command = Command::new(&self.binary);
command
.arg("check")
.arg(file)
.arg("--json")
.arg("--emit")
.arg(temporary.path())
.output()
.map_err(|error| io(&self.binary, error))?;
.arg(temporary.path());
if refs {
command.arg("--refs");
}
let output = command.output().map_err(|error| io(&self.binary, error))?;
if !output.status.success() {
let diagnostics = check_diagnostics(&output.stdout);
let text = if diagnostics.is_empty() {
@@ -145,27 +135,30 @@ impl MarqdoRunner {
return Ok(CheckOutcome {
success: false,
analysis: None,
analysis_bytes: Vec::new(),
artifact_digest: None,
output: text,
diagnostics,
});
}
let bytes = fs::read(temporary.path()).map_err(|error| io(temporary.path(), error))?;
if bytes.is_empty() {
return Err(LintError::Protocol(
"核心 check 成功但没有写出 Analysis 工件".into(),
));
}
let artifact_digest = format!("sha256:{:x}", Sha256::digest(&bytes));
let analysis = serde_json::from_slice(&bytes)
.map_err(|error| LintError::Protocol(format!("Analysis JSON 无效:{error}")))?;
Ok(CheckOutcome {
success: true,
analysis: Some(analysis),
analysis_bytes: bytes,
artifact_digest: Some(artifact_digest),
output: String::new(),
diagnostics: Vec::new(),
})
}
fn run(&self, args: &[&std::ffi::OsStr]) -> Result<Output> {
Command::new(&self.binary)
.args(args)
.output()
.map_err(|error| io(&self.binary, error))
}
}
fn format_output(output: &Output) -> String {
@@ -191,3 +184,140 @@ fn check_diagnostics(stdout: &[u8]) -> Vec<CheckDiagnostic> {
.filter(|report| report.command == "check")
.map_or_else(Vec::new, |report| report.diagnostics)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemVer {
major: u64,
minor: u64,
patch: u64,
prerelease: Vec<Identifier>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Identifier {
Numeric(u64),
Text(String),
}
impl SemVer {
pub fn parse(input: &str) -> std::result::Result<Self, String> {
let input = input.trim();
let (core, build) = match input.split_once('+') {
Some((core, build)) => {
if build.is_empty()
|| !build
.split('.')
.all(|part| !part.is_empty() && is_identifier(part))
{
return Err("build metadata 无效".into());
}
(core, Some(build))
}
None => (input, None),
};
let _ = build;
let (core, prerelease) = match core.split_once('-') {
Some((core, prerelease)) => (core, Some(prerelease)),
None => (core, None),
};
let mut parts = core.split('.');
let major = parse_number(parts.next(), "major")?;
let minor = parse_number(parts.next(), "minor")?;
let patch = parse_number(parts.next(), "patch")?;
if parts.next().is_some() {
return Err("版本号段过多".into());
}
let mut identifiers = Vec::new();
if let Some(prerelease) = prerelease {
if prerelease.is_empty() {
return Err("prerelease 为空".into());
}
for part in prerelease.split('.') {
if part.is_empty() || !is_identifier(part) {
return Err(format!("prerelease 标识 {part:?} 无效"));
}
if part.bytes().all(|byte| byte.is_ascii_digit()) {
let value = part
.parse::<u64>()
.map_err(|_| format!("prerelease 数字 {part:?} 溢出"))?;
identifiers.push(Identifier::Numeric(value));
} else {
identifiers.push(Identifier::Text(part.to_string()));
}
}
}
Ok(Self {
major,
minor,
patch,
prerelease: identifiers,
})
}
}
fn parse_number(part: Option<&str>, name: &str) -> std::result::Result<u64, String> {
let part = part.ok_or_else(|| format!("缺少 {name} 版本段"))?;
if part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(format!("{name} 必须是数字"));
}
part.parse::<u64>()
.map_err(|_| format!("{name} 版本段溢出"))
}
fn is_identifier(value: &str) -> bool {
value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
}
impl Ord for SemVer {
fn cmp(&self, other: &Self) -> Ordering {
(self.major, self.minor, self.patch)
.cmp(&(other.major, other.minor, other.patch))
.then_with(|| compare_prerelease(&self.prerelease, &other.prerelease))
}
}
impl PartialOrd for SemVer {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn compare_prerelease(left: &[Identifier], right: &[Identifier]) -> Ordering {
match (left.is_empty(), right.is_empty()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => {
for (left, right) in left.iter().zip(right) {
let ordering = match (left, right) {
(Identifier::Numeric(left), Identifier::Numeric(right)) => left.cmp(right),
(Identifier::Numeric(_), Identifier::Text(_)) => Ordering::Less,
(Identifier::Text(_), Identifier::Numeric(_)) => Ordering::Greater,
(Identifier::Text(left), Identifier::Text(right)) => left.cmp(right),
};
if ordering != Ordering::Equal {
return ordering;
}
}
left.len().cmp(&right.len())
}
}
}
#[cfg(test)]
mod tests {
use super::SemVer;
#[test]
fn enforces_the_current_prerelease_floor() {
assert!(SemVer::parse("3.0.0-rc.4").unwrap() < SemVer::parse("3.0.0").unwrap());
assert!(SemVer::parse("3.0.0-rc.3").unwrap() < SemVer::parse("3.0.0-rc.4").unwrap());
assert!(SemVer::parse("3.0.0-rc.10").unwrap() > SemVer::parse("3.0.0-rc.4").unwrap());
assert!(SemVer::parse("3.1.0-alpha.1").unwrap() > SemVer::parse("3.0.0-rc.4").unwrap());
assert!(SemVer::parse("4.0.0").unwrap() > SemVer::parse("3.0.0").unwrap());
assert!(SemVer::parse("3.0").is_err());
assert!(SemVer::parse("3.0.0-").is_err());
}
}