use std::{ fs, path::{Path, PathBuf}, }; use serde::Serialize; use crate::{ error::{io, LintError, Result}, model::{AnalysisModule, ExecutionProjection, MarkdownTree, SourceSnapshot}, }; use super::{fallback_ast, CheckDiagnostic, MarqdoRunner}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum AnalysisStatus { Complete, AnalysisIncomplete, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum MarkdownOrigin { MarqdoInspect, ComrakFallback, } #[derive(Debug, Clone)] pub struct SourceDocument { pub source: SourceSnapshot, pub markdown: MarkdownTree, pub markdown_origin: MarkdownOrigin, pub module: Option, } #[derive(Debug)] pub struct ProjectInput { pub entry: PathBuf, pub documents: Vec, pub analysis: Option, pub analysis_status: AnalysisStatus, pub core_output: String, pub core_diagnostics: Vec, pub notices: Vec, } impl ProjectInput { pub fn load(entry: impl AsRef, runner: &MarqdoRunner) -> Result { let entry = fs::canonicalize(entry.as_ref()).map_err(|error| io(entry.as_ref(), error))?; let mut notices = Vec::new(); let entry_document = read_document(&entry, runner, &mut notices)?; let check = runner.check(&entry)?; if !check.success { return Ok(Self { entry, documents: vec![entry_document], analysis: None, analysis_status: AnalysisStatus::AnalysisIncomplete, core_output: check.output, core_diagnostics: check.diagnostics, notices, }); } let raw = check .analysis .ok_or_else(|| LintError::Protocol("核心 check 成功但没有生成 Analysis".into()))?; let analysis = ExecutionProjection::from_json(raw).map_err(LintError::Protocol)?; let root = project_root(&entry); let mut documents = Vec::new(); for module in analysis .modules .iter() .filter(|module| module.package_instance_id.starts_with("root:")) { let path = root.join(&module.relative_path); let mut document = read_document(&path, runner, &mut notices)?; if document.source.digest_hex() != module.source_digest { return Err(LintError::Protocol(format!( "模块 {} 的源码摘要与 Analysis 不一致", module.id ))); } for function in &module.functions { function.validate_source_spans(&document.source)?; } document.module = Some(module.clone()); documents.push(document); } if documents.is_empty() { documents.push(entry_document); } documents.sort_by(|left, right| left.source.path.cmp(&right.source.path)); Ok(Self { entry, documents, analysis: Some(analysis), analysis_status: AnalysisStatus::Complete, core_output: String::new(), core_diagnostics: Vec::new(), notices, }) } pub fn document_only(entry: impl AsRef, runner: &MarqdoRunner) -> Result { let entry = fs::canonicalize(entry.as_ref()).map_err(|error| io(entry.as_ref(), error))?; let mut notices = Vec::new(); let document = read_document(&entry, runner, &mut notices)?; Ok(Self { entry, documents: vec![document], analysis: None, analysis_status: AnalysisStatus::AnalysisIncomplete, core_output: String::new(), core_diagnostics: Vec::new(), notices, }) } } fn read_document( path: &Path, runner: &MarqdoRunner, notices: &mut Vec, ) -> Result { let source = SourceSnapshot::load(path)?; match runner.inspect(path) { Ok(ast) => { let markdown = MarkdownTree::from_json(ast, &source)?; Ok(SourceDocument { source, markdown, markdown_origin: MarkdownOrigin::MarqdoInspect, module: None, }) } Err(LintError::Core(message)) => { let markdown = MarkdownTree::from_json(fallback_ast(&source)?, &source)?; notices.push(format!( "{}:inspect 不可用,已使用严格 comrak 降级;{message}", path.display() )); Ok(SourceDocument { source, markdown, markdown_origin: MarkdownOrigin::ComrakFallback, module: None, }) } Err(error) => Err(error), } } 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() { return current.to_path_buf(); } let Some(parent) = current.parent() else { return entry.parent().unwrap_or(Path::new(".")).to_path_buf(); }; current = parent; } }