Skip to main content

code_repo_wiki/
project.rs

1//! 项目根目录(消除进程级 current_dir 依赖的注入载体)
2//!
3//! 背景:全仓库多处通过 `std::env::current_dir()` 推导项目根(扫描根、
4//! wiki_plan.yaml 定位、git 仓库定位、指纹键前缀),导致三方面问题:
5//! - 不可测试:测试进程的 cwd 是测试运行目录,与被测代码假设的
6//!   "项目根"不一致,根路径相关断言只能在真实仓库里跑;
7//! - 不可常驻:watch 长驻进程 / 服务化场景中 cwd 可被外部改变,
8//!   依赖 cwd 的路径推导会静默漂移(扫描范围、git 仓库定位全错);
9//! - 不可并行:多实例(并行子代理、多输出目录)共享同一 cwd 时
10//!   相互干扰。
11//!
12//! 方案:CLI 显式 --root 参数(main.rs)→ 本类型全链路注入。各模块
13//! 的 *_at 变体以 root 为首参(scan_and_parse_at / resolve_plan_at /
14//! get_head_commit_hash_at / run_incremental_update_at / classify_
15//! entity_changes_at / generate_schema_documents_at),生产代码不再
16//! 直接调用 `std::env::current_dir()`。[`ProjectRoot::from_cwd`] 仅保留
17//! 为 CLI 未传 --root 时的默认值(main.rs resolve_root)。
18
19use std::path::{Path, PathBuf};
20
21use anyhow::{Context, Result};
22
23/// 项目根目录(仅承载路径,不校验存在性)
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ProjectRoot {
26    path: PathBuf,
27}
28
29impl ProjectRoot {
30    /// 默认根:当前工作目录(仅 main.rs 在 --root 缺省时调用)
31    pub fn from_cwd() -> Result<Self> {
32        let path = std::env::current_dir().context("获取当前工作目录失败")?;
33        Ok(Self::new(path))
34    }
35
36    /// 显式指定项目根(CLI --root 注入入口)
37    pub fn new(path: PathBuf) -> Self {
38        Self { path }
39    }
40
41    /// 项目根路径
42    pub fn path(&self) -> &Path {
43        &self.path
44    }
45
46    /// 项目根下的相对路径
47    pub fn join(&self, rel: &Path) -> PathBuf {
48        self.path.join(rel)
49    }
50}
51// F 组增量闭环