vkit 0.1.4

Fast Rust dev CLI: manage git worktrees, Node ports, run scripts, install & sync VS Code / Cursor extensions.
//! 每个仓库记住「上一个 worktree」,供 `vkit wt switch -` 使用。

use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

use super::git;

fn state_dir(main_path: &Path) -> Result<PathBuf> {
    let common = git::git_common_dir(main_path)?;
    let dir = if common.file_name().and_then(|s| s.to_str()) == Some(".git") {
        common.join("vkit")
    } else {
        // bare:common 本身是 git dir
        common.join("vkit")
    };
    Ok(dir)
}

pub fn load_previous(main_path: &Path) -> Option<PathBuf> {
    let path = state_dir(main_path).ok()?.join("previous");
    let raw = fs::read_to_string(path).ok()?;
    let p = PathBuf::from(raw.trim());
    p.exists().then_some(p)
}

pub fn save_previous(main_path: &Path, previous: &Path) -> Result<()> {
    let dir = state_dir(main_path)?;
    fs::create_dir_all(&dir).with_context(|| format!("创建状态目录失败:{}", dir.display()))?;
    let file = dir.join("previous");
    fs::write(&file, previous.to_string_lossy().as_bytes())
        .with_context(|| format!("写入 previous 失败:{}", file.display()))?;
    Ok(())
}