OXYGENHUB
# f97d3556db5f oxygen / crates / oxy-core / src / repo / inspect.rs
12.5 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 1 month ago source blame history raw
1
//! Inspection (spec §27): blame from atom keys, and bisect over
2
//! dependency-closed prefixes of the candidates between a good and a bad
3
//! state.
4
5
use super::*;
6
7
/// One line of `oxy blame`.
8
#[derive(Clone, Debug)]
9
pub struct BlameLine {
10
    pub line: usize,
11
    pub hash: ChangeHash,
12
    pub index: u32,
13
    pub change_id: ChangeId,
14
    pub author: String,
15
    pub when_ms: u64,
16
    pub text: Vec<u8>,
17
}
18
19
/// Where a bisect stands.
20
#[derive(Clone, Debug, PartialEq, Eq)]
21
pub enum BisectStep {
22
    /// More `good`/`bad` marks are needed before the search can start.
23
    NeedMarks { good: usize, bad: usize },
24
    /// A state is checked out for testing.
25
    Testing {
26
        heads: Vec<ChangeHash>,
27
        remaining: usize,
28
        steps_left: u32,
29
    },
30
    /// The first change whose inclusion makes the state bad.
31
    Found { culprit: ChangeHash },
32
    /// Every remaining candidate was skipped.
33
    Inconclusive { candidates: Vec<ChangeHash> },
34
}
35
36
#[derive(Clone, Debug, Default)]
37
struct BisectState {
38
    start: Vec<ChangeHash>,
39
    good: Vec<ChangeHash>,
40
    bad: Vec<ChangeHash>,
41
    candidates: Vec<ChangeHash>,
42
    lo: usize,
43
    hi: usize,
44
    /// The prefix length currently checked out for testing.
45
    testing: Option<usize>,
46
    skipped: Vec<usize>,
47
}
48
49
fn hashes_line(v: &[ChangeHash]) -> String {
50
    v.iter().map(|h| h.to_hex()).collect::<Vec<_>>().join(" ")
51
}
52
fn hashes_from(s: &str) -> Vec<ChangeHash> {
53
    s.split_whitespace()
54
        .filter_map(ObjectRef::from_hex)
55
        .collect()
56
}
57
58
impl Repo {
59
    /// The introducing change, author, and date of every line of `path` in
60
    /// the working copy's base state (spec §27).
61
    pub fn blame(&self, path: &str) -> Result<Vec<BlameLine>> {
62
        let snap = self.snapshot("oxy blame")?;
63
        self.blame_state(
64
            path,
65
            &snap.base,
66
            &snap.base_snapshot,
67
            "the working copy's base state",
68
        )
69
    }
70
71
    /// Blame `path` in the state with these heads (hosted repositories).
72
    pub fn blame_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<BlameLine>> {
73
        let state = self.load_state(heads)?;
74
        let snapshot = state.materialize();
75
        self.blame_state(path, &state, &snapshot, "that state")
76
    }
77
78
    fn blame_state(
79
        &self,
80
        path: &str,
81
        state: &crate::state::State,
82
        snapshot: &crate::state::Snapshot,
83
        what: &str,
84
    ) -> Result<Vec<BlameLine>> {
85
        let Some(f) = snapshot.files.get(path) else {
86
            return fail(format!("{path} is not in {what}"));
87
        };
88
        if !matches!(f.content, FileContent::Text { .. }) {
89
            return fail(format!("{path} is not a text file"));
90
        }
91
        let mut out = Vec::new();
92
        for (i, ((hash, index), text)) in state.live_lines(&f.node).into_iter().enumerate() {
93
            let meta = state.get(&hash);
94
            let author = match meta {
95
                Some(m) if !m.author.is_zero() => self
96
                    .store
97
                    .get_identity(&m.author)
98
                    .map(|id| id.name)
99
                    .unwrap_or_else(|_| m.author.short(12)),
100
                Some(m) => m
101
                    .message
102
                    .lines()
103
                    .rev()
104
                    .find_map(|l| l.strip_prefix("Git-Author: "))
105
                    .map(|a| a.split('<').next().unwrap_or(a).trim().to_string())
106
                    .unwrap_or_else(|| "unknown".into()),
107
                None => "unknown".into(),
108
            };
109
            out.push(BlameLine {
110
                line: i + 1,
111
                hash,
112
                index,
113
                change_id: meta.map(|m| m.change_id).unwrap_or(ChangeId([0; 16])),
114
                author,
115
                when_ms: meta.map(|m| m.hlc.wall_ms).unwrap_or(0),
116
                text,
117
            });
118
        }
119
        Ok(out)
120
    }
121
122
    // ------------------------------------------------------------ bisect
123
124
    fn bisect_dir(&self) -> PathBuf {
125
        self.oxy.join("bisect")
126
    }
127
128
    fn bisect_load(&self) -> Result<Option<BisectState>> {
129
        let dir = self.bisect_dir();
130
        if !dir.join("start").exists() {
131
            return Ok(None);
132
        }
133
        let read = |name: &str| fs::read_to_string(dir.join(name)).unwrap_or_default();
134
        let nums: Vec<usize> = read("range")
135
            .split_whitespace()
136
            .filter_map(|n| n.parse().ok())
137
            .collect();
138
        Ok(Some(BisectState {
139
            start: hashes_from(&read("start")),
140
            good: hashes_from(&read("good")),
141
            bad: hashes_from(&read("bad")),
142
            candidates: hashes_from(&read("candidates")),
143
            lo: nums.first().copied().unwrap_or(0),
144
            hi: nums.get(1).copied().unwrap_or(0),
145
            testing: nums.get(2).copied().filter(|_| nums.len() > 2),
146
            skipped: read("skipped")
147
                .split_whitespace()
148
                .filter_map(|n| n.parse().ok())
149
                .collect(),
150
        }))
151
    }
152
153
    fn bisect_save(&self, st: &BisectState) -> Result<()> {
154
        let dir = self.bisect_dir();
155
        fs::create_dir_all(&dir)?;
156
        write_atomic(&dir.join("start"), hashes_line(&st.start).as_bytes())?;
157
        write_atomic(&dir.join("good"), hashes_line(&st.good).as_bytes())?;
158
        write_atomic(&dir.join("bad"), hashes_line(&st.bad).as_bytes())?;
159
        write_atomic(
160
            &dir.join("candidates"),
161
            hashes_line(&st.candidates).as_bytes(),
162
        )?;
163
        let mut range = format!("{} {}", st.lo, st.hi);
164
        if let Some(t) = st.testing {
165
            range.push_str(&format!(" {t}"));
166
        }
167
        write_atomic(&dir.join("range"), range.as_bytes())?;
168
        write_atomic(
169
            &dir.join("skipped"),
170
            st.skipped
171
                .iter()
172
                .map(|n| n.to_string())
173
                .collect::<Vec<_>>()
174
                .join(" ")
175
                .as_bytes(),
176
        )?;
177
        Ok(())
178
    }
179
180
    /// Begin a bisect: remembers the working copy's base to restore later.
181
    pub fn bisect_start(&self) -> Result<()> {
182
        if self.bisect_load()?.is_some() {
183
            return fail("a bisect is in progress; finish it or run `oxy bisect reset`");
184
        }
185
        let (_, wc) = self.working_copy()?;
186
        let start = self.load_state(&wc.deps)?.maximal(&wc.deps);
187
        self.bisect_save(&BisectState {
188
            start,
189
            ..Default::default()
190
        })
191
    }
192
193
    pub fn bisect_reset(&self) -> Result<()> {
194
        let Some(st) = self.bisect_load()? else {
195
            return fail("no bisect in progress");
196
        };
197
        self.checkout(&st.start, false, "oxy bisect reset")?;
198
        fs::remove_dir_all(self.bisect_dir())?;
199
        Ok(())
200
    }
201
202
    pub fn bisect_status(&self) -> Result<Option<BisectStep>> {
203
        let Some(st) = self.bisect_load()? else {
204
            return Ok(None);
205
        };
206
        Ok(Some(self.bisect_step(&st)))
207
    }
208
209
    fn bisect_step(&self, st: &BisectState) -> BisectStep {
210
        if st.candidates.is_empty() {
211
            return BisectStep::NeedMarks {
212
                good: st.good.len(),
213
                bad: st.bad.len(),
214
            };
215
        }
216
        if st.hi <= st.lo + 1 {
217
            return BisectStep::Found {
218
                culprit: st.candidates[st.lo],
219
            };
220
        }
221
        match st.testing {
222
            Some(_) => {
223
                let remaining = st.hi - st.lo;
224
                BisectStep::Testing {
225
                    heads: self.bisect_heads(st, st.testing.unwrap()),
226
                    remaining,
227
                    steps_left: (remaining as f64).log2().ceil() as u32,
228
                }
229
            }
230
            None => BisectStep::Inconclusive {
231
                candidates: st.candidates[st.lo..st.hi].to_vec(),
232
            },
233
        }
234
    }
235
236
    /// `good ∪ candidates[..k]`, as heads.
237
    fn bisect_heads(&self, st: &BisectState, k: usize) -> Vec<ChangeHash> {
238
        let mut all = st.good.clone();
239
        all.extend(st.candidates[..k].iter().copied());
240
        self.load_state(&all)
241
            .map(|s| s.maximal(&all))
242
            .unwrap_or(all)
243
    }
244
245
    /// Check out the midpoint of the open range, skipping indices marked
246
    /// untestable, and record it as the state under test.
247
    fn bisect_advance(&self, st: &mut BisectState) -> Result<BisectStep> {
248
        if st.hi <= st.lo + 1 {
249
            st.testing = None;
250
            self.bisect_save(st)?;
251
            return Ok(BisectStep::Found {
252
                culprit: st.candidates[st.lo],
253
            });
254
        }
255
        let mid = st.lo + (st.hi - st.lo) / 2;
256
        // Try mid, then the nearest untried indices on either side.
257
        let mut order = vec![mid];
258
        for d in 1..(st.hi - st.lo) {
259
            if mid + d < st.hi {
260
                order.push(mid + d);
261
            }
262
            if mid > st.lo + d {
263
                order.push(mid - d);
264
            }
265
        }
266
        let Some(k) = order.into_iter().find(|k| !st.skipped.contains(k)) else {
267
            st.testing = None;
268
            self.bisect_save(st)?;
269
            return Ok(BisectStep::Inconclusive {
270
                candidates: st.candidates[st.lo..st.hi].to_vec(),
271
            });
272
        };
273
        let heads = self.bisect_heads(st, k);
274
        self.checkout(
275
            &heads,
276
            false,
277
            &format!("oxy bisect (testing {k} of {})", st.candidates.len()),
278
        )?;
279
        st.testing = Some(k);
280
        self.bisect_save(st)?;
281
        let remaining = st.hi - st.lo;
282
        Ok(BisectStep::Testing {
283
            heads,
284
            remaining,
285
            steps_left: (remaining as f64).log2().ceil() as u32,
286
        })
287
    }
288
289
    /// Mark states good or bad. With `changes`, before the search starts,
290
    /// they name known-good or known-bad states; without, the state under
291
    /// test gets the verdict. `None` for `good` means skip (untestable).
292
    pub fn bisect_mark(&self, good: Option<bool>, changes: &[ChangeHash]) -> Result<BisectStep> {
293
        let Some(mut st) = self.bisect_load()? else {
294
            return fail("no bisect in progress; run `oxy bisect start`");
295
        };
296
        if !changes.is_empty() {
297
            if !st.candidates.is_empty() {
298
                return fail("the search has started; mark the state under test with plain `oxy bisect good|bad`");
299
            }
300
            match good {
301
                Some(true) => st.good.extend(changes.iter().copied()),
302
                Some(false) => st.bad.extend(changes.iter().copied()),
303
                None => return fail("skip applies to the state under test"),
304
            }
305
            if st.good.is_empty() || st.bad.is_empty() {
306
                self.bisect_save(&st)?;
307
                return Ok(BisectStep::NeedMarks {
308
                    good: st.good.len(),
309
                    bad: st.bad.len(),
310
                });
311
            }
312
            let good_heads = self.load_state(&st.good)?.maximal(&st.good);
313
            let bad_heads = self.load_state(&st.bad)?.maximal(&st.bad);
314
            st.good = good_heads.clone();
315
            st.bad = bad_heads.clone();
316
            st.candidates = self.negotiate(&good_heads, &bad_heads)?;
317
            if st.candidates.is_empty() {
318
                return fail("the bad state adds nothing to the good state; nothing to bisect");
319
            }
320
            st.lo = 0;
321
            st.hi = st.candidates.len();
322
            return self.bisect_advance(&mut st);
323
        }
324
        let Some(k) = st.testing else {
325
            return fail("no state is under test; give `oxy bisect good|bad` a change or bookmark to start with");
326
        };
327
        match good {
328
            Some(true) => st.lo = k,
329
            Some(false) => st.hi = k,
330
            None => st.skipped.push(k),
331
        }
332
        self.bisect_advance(&mut st)
333
    }
334
335
    /// Automate with a command run in the working copy: exit 0 is good, 125
336
    /// skips, anything else is bad.
337
    pub fn bisect_run(&self, command: &[String]) -> Result<BisectStep> {
338
        let Some(st) = self.bisect_load()? else {
339
            return fail("no bisect in progress; run `oxy bisect start`");
340
        };
341
        if st.testing.is_none() {
342
            return Ok(self.bisect_step(&st));
343
        }
344
        loop {
345
            let status = std::process::Command::new(&command[0])
346
                .args(&command[1..])
347
                .current_dir(&self.root)
348
                .status()
349
                .map_err(|e| RepoError::Msg(format!("running {}: {e}", command[0])))?;
350
            let verdict = match status.code() {
351
                Some(0) => Some(true),
352
                Some(125) => None,
353
                _ => Some(false),
354
            };
355
            match self.bisect_mark(verdict, &[])? {
356
                BisectStep::Testing { .. } => continue,
357
                done => return Ok(done),
358
            }
359
        }
360
    }
361
}