use std::{ cmp::Ordering, fs, path::{Path, PathBuf}, process::{Command, Output}, }; use serde::Deserialize; use serde_json::Value; use sha2::{Digest, Sha256}; use tempfile::NamedTempFile; 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, pub analysis_bytes: Vec, pub artifact_digest: Option, pub output: String, pub diagnostics: Vec, } #[derive(Debug, Deserialize)] pub struct CheckDiagnostic { pub code: String, pub severity: String, pub file: Option, pub line: Option, pub column: Option, pub message: String, #[serde(default)] pub hints: Vec, } impl CheckDiagnostic { fn render(&self) -> String { let location = self .file .as_ref() .map(|path| { format!( "{}:{}:{}: ", path.display(), self.line.unwrap_or(1), self.column.unwrap_or(1) ) }) .unwrap_or_default(); let mut text = format!( "{}[{}]: {location}{}", self.severity, self.code, self.message ); for hint in &self.hints { text.push_str(&format!("\n hint: {hint}")); } text } } impl MarqdoRunner { pub fn discover(explicit: Option<&Path>) -> Result { let binary = explicit .map(Path::to_path_buf) .or_else(|| std::env::var_os("MARQDO_BIN").map(PathBuf::from)) .unwrap_or_else(|| PathBuf::from("marqdo")); 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 version(&self) -> &SemVer { &self.version } pub fn check(&self, file: &Path, refs: bool) -> Result { let temporary = NamedTempFile::new().map_err(|error| io("Analysis 临时文件", error))?; let mut command = Command::new(&self.binary); command .arg("check") .arg(file) .arg("--json") .arg("--emit") .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() { format_output(&output) } else { diagnostics .iter() .map(CheckDiagnostic::render) .collect::>() .join("\n") }; 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 format_output(output: &Output) -> String { let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); match (stdout.trim().is_empty(), stderr.trim().is_empty()) { (false, false) => format!("{}\n{}", stdout.trim(), stderr.trim()), (false, true) => stdout.trim().to_string(), (true, false) => stderr.trim().to_string(), (true, true) => format!("核心退出状态 {}", output.status), } } fn check_diagnostics(stdout: &[u8]) -> Vec { #[derive(Deserialize)] struct CheckJson { command: String, diagnostics: Vec, } serde_json::from_slice::(stdout) .ok() .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, } #[derive(Debug, Clone, PartialEq, Eq)] enum Identifier { Numeric(u64), Text(String), } impl SemVer { pub fn parse(input: &str) -> std::result::Result { 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::() .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 { 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::() .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 { 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()); } }