1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use crate::error::Result;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// Persistent bisect state stored in `.codetree/bisect.json`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BisectState {
/// The commit known to be bad (HEAD at bisect start, or marked bad).
pub bad: Option<String>,
/// The commit known to be good (oldest known-good ancestor).
pub good: Vec<String>,
/// The current commit being tested.
pub current: Option<String>,
/// The original HEAD to restore after bisect completes.
pub original_head: Option<String>,
/// The original branch name to restore after bisect completes.
pub original_branch: Option<String>,
}
impl BisectState {
fn path(repo_path: &Path) -> PathBuf {
repo_path.join(".codetree").join("bisect.json")
}
/// Load bisect state from disk, or return default if none exists.
pub fn load(repo_path: &Path) -> Result<Self> {
let path = Self::path(repo_path);
if !path.exists() {
return Ok(Self::default());
}
let content = std::fs::read_to_string(&path)?;
let state: BisectState = serde_json::from_str(&content)
.unwrap_or_default();
Ok(state)
}
/// Save bisect state to disk.
pub fn save(&self, repo_path: &Path) -> Result<()> {
let path = Self::path(repo_path);
let content = serde_json::to_string_pretty(self)?;
crate::atomic::write_atomic(&path, content.as_bytes())?;
Ok(())
}
/// Clear bisect state (remove the file).
pub fn clear(repo_path: &Path) -> Result<()> {
let path = Self::path(repo_path);
if path.exists() {
std::fs::remove_file(&path)?;
}
Ok(())
}
/// Check if a bisect session is in progress.
pub fn is_active(&self) -> bool {
self.bad.is_some()
}
/// Find the midpoint commit between the bad commit and the nearest good
/// ancestor. Returns None if the range is exhausted (bad's parent is good).
pub fn midpoint(&self, repo: &crate::vcs::Repository) -> Result<Option<String>> {
let Some(bad) = &self.bad else {
return Ok(None);
};
// Collect all ancestors of bad until we hit a good commit.
let mut ancestors: Vec<String> = Vec::new();
let mut current = bad.clone();
loop {
if self.good.contains(¤t) {
break;
}
ancestors.push(current.clone());
let commit = repo.read_commit(¤t)?;
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
// If only 1 ancestor (just bad itself) or bad is directly after good, done.
if ancestors.len() <= 1 {
return Ok(None);
}
// Pick the midpoint (skip index 0 which is bad itself).
let mid = ancestors.len() / 2;
Ok(Some(ancestors[mid].clone()))
}
}