OXYGENHUB
# b493d993a9df oxygen / crates / oxy-core / src / repo / inspect.rs
16.3 KiB · Rust · last changed Log, blame and fsck at the scale of the Linux tree 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 (_, wc) = self.working_copy()?;
63
        self.blame_heads(path, &wc.deps, "the working copy's base state")
64
    }
65
66
    /// Blame `path` in the state with these heads (hosted repositories).
67
    pub fn blame_in(&self, path: &str, heads: &[ChangeHash]) -> Result<Vec<BlameLine>> {
68
        self.blame_heads(path, heads, "that state")
69
    }
70
71
    /// Blame `path` in the state with these heads, building only its graph.
72
    fn blame_heads(&self, path: &str, heads: &[ChangeHash], what: &str) -> Result<Vec<BlameLine>> {
73
        let mut state = self.load_state_history(heads)?;
74
        let tree = state.tree().view();
75
        if let Some(e) = tree.entries.get(path) {
76
            self.load_graphs_of(&mut state, &[e.node])?;
77
        }
78
        self.blame_state(path, &state, &tree, what)
79
    }
80
81
    /// Blame `path` in a loaded state whose tree view the caller holds; no
82
    /// file other than `path` is rendered.
83
    pub fn blame_of(
84
        &self,
85
        state: &crate::state::State,
86
        tree: &crate::tree::TreeView,
87
        path: &str,
88
    ) -> Result<Vec<BlameLine>> {
89
        self.blame_state(path, state, tree, "that state")
90
    }
91
92
    fn blame_state(
93
        &self,
94
        path: &str,
95
        state: &crate::state::State,
96
        tree: &crate::tree::TreeView,
97
        what: &str,
98
    ) -> Result<Vec<BlameLine>> {
99
        let Some(f) = tree.entries.get(path) else {
100
            return fail(format!("{path} is not in {what}"));
101
        };
102
        if f.kind != crate::objects::NodeKind::File || f.mode.opaque {
103
            return fail(format!("{path} is not a text file"));
104
        }
105
        let mut out = Vec::new();
106
        for (i, ((hash, index), text)) in state.live_lines(&f.node).into_iter().enumerate() {
107
            let meta = state.get(&hash);
108
            let author = match meta {
109
                Some(m) if !m.author.is_zero() => self
110
                    .store
111
                    .get_identity(&m.author)
112
                    .map(|id| id.name)
113
                    .unwrap_or_else(|_| m.author.short(12)),
114
                Some(m) => m
115
                    .message
116
                    .lines()
117
                    .rev()
118
                    .find_map(|l| l.strip_prefix("Git-Author: "))
119
                    .map(|a| a.split('<').next().unwrap_or(a).trim().to_string())
120
                    .unwrap_or_else(|| "unknown".into()),
121
                None => "unknown".into(),
122
            };
123
            out.push(BlameLine {
124
                line: i + 1,
125
                hash,
126
                index,
127
                change_id: meta.map(|m| m.change_id).unwrap_or(ChangeId([0; 16])),
128
                author,
129
                when_ms: meta.map(|m| m.hlc.wall_ms).unwrap_or(0),
130
                text,
131
            });
132
        }
133
        Ok(out)
134
    }
135
136
    // ------------------------------------------------------------ bisect
137
138
    fn bisect_dir(&self) -> PathBuf {
139
        self.oxy.join("bisect")
140
    }
141
142
    fn bisect_load(&self) -> Result<Option<BisectState>> {
143
        let dir = self.bisect_dir();
144
        if !dir.join("start").exists() {
145
            return Ok(None);
146
        }
147
        let read = |name: &str| fs::read_to_string(dir.join(name)).unwrap_or_default();
148
        let nums: Vec<usize> = read("range")
149
            .split_whitespace()
150
            .filter_map(|n| n.parse().ok())
151
            .collect();
152
        Ok(Some(BisectState {
153
            start: hashes_from(&read("start")),
154
            good: hashes_from(&read("good")),
155
            bad: hashes_from(&read("bad")),
156
            candidates: hashes_from(&read("candidates")),
157
            lo: nums.first().copied().unwrap_or(0),
158
            hi: nums.get(1).copied().unwrap_or(0),
159
            testing: nums.get(2).copied().filter(|_| nums.len() > 2),
160
            skipped: read("skipped")
161
                .split_whitespace()
162
                .filter_map(|n| n.parse().ok())
163
                .collect(),
164
        }))
165
    }
166
167
    fn bisect_save(&self, st: &BisectState) -> Result<()> {
168
        let dir = self.bisect_dir();
169
        fs::create_dir_all(&dir)?;
170
        write_atomic(&dir.join("start"), hashes_line(&st.start).as_bytes())?;
171
        write_atomic(&dir.join("good"), hashes_line(&st.good).as_bytes())?;
172
        write_atomic(&dir.join("bad"), hashes_line(&st.bad).as_bytes())?;
173
        write_atomic(
174
            &dir.join("candidates"),
175
            hashes_line(&st.candidates).as_bytes(),
176
        )?;
177
        let mut range = format!("{} {}", st.lo, st.hi);
178
        if let Some(t) = st.testing {
179
            range.push_str(&format!(" {t}"));
180
        }
181
        write_atomic(&dir.join("range"), range.as_bytes())?;
182
        write_atomic(
183
            &dir.join("skipped"),
184
            st.skipped
185
                .iter()
186
                .map(|n| n.to_string())
187
                .collect::<Vec<_>>()
188
                .join(" ")
189
                .as_bytes(),
190
        )?;
191
        Ok(())
192
    }
193
194
    /// Begin a bisect: remembers the working copy's base to restore later.
195
    pub fn bisect_start(&self) -> Result<()> {
196
        if self.bisect_load()?.is_some() {
197
            return fail("a bisect is in progress; finish it or run `oxy bisect reset`");
198
        }
199
        let (_, wc) = self.working_copy()?;
200
        let start = self.load_state(&wc.deps)?.maximal(&wc.deps);
201
        self.bisect_save(&BisectState {
202
            start,
203
            ..Default::default()
204
        })
205
    }
206
207
    pub fn bisect_reset(&self) -> Result<()> {
208
        let Some(st) = self.bisect_load()? else {
209
            return fail("no bisect in progress");
210
        };
211
        self.checkout(&st.start, false, "oxy bisect reset")?;
212
        fs::remove_dir_all(self.bisect_dir())?;
213
        Ok(())
214
    }
215
216
    pub fn bisect_status(&self) -> Result<Option<BisectStep>> {
217
        let Some(st) = self.bisect_load()? else {
218
            return Ok(None);
219
        };
220
        Ok(Some(self.bisect_step(&st)))
221
    }
222
223
    fn bisect_step(&self, st: &BisectState) -> BisectStep {
224
        if st.candidates.is_empty() {
225
            return BisectStep::NeedMarks {
226
                good: st.good.len(),
227
                bad: st.bad.len(),
228
            };
229
        }
230
        if st.hi <= st.lo + 1 {
231
            return BisectStep::Found {
232
                culprit: st.candidates[st.lo],
233
            };
234
        }
235
        match st.testing {
236
            Some(_) => {
237
                let remaining = st.hi - st.lo;
238
                BisectStep::Testing {
239
                    heads: self.bisect_heads(st, st.testing.unwrap()),
240
                    remaining,
241
                    steps_left: (remaining as f64).log2().ceil() as u32,
242
                }
243
            }
244
            None => BisectStep::Inconclusive {
245
                candidates: st.candidates[st.lo..st.hi].to_vec(),
246
            },
247
        }
248
    }
249
250
    /// `good ∪ candidates[..k]`, as heads.
251
    fn bisect_heads(&self, st: &BisectState, k: usize) -> Vec<ChangeHash> {
252
        let mut all = st.good.clone();
253
        all.extend(st.candidates[..k].iter().copied());
254
        self.load_state(&all)
255
            .map(|s| s.maximal(&all))
256
            .unwrap_or(all)
257
    }
258
259
    /// Check out the midpoint of the open range, skipping indices marked
260
    /// untestable, and record it as the state under test.
261
    fn bisect_advance(&self, st: &mut BisectState) -> Result<BisectStep> {
262
        if st.hi <= st.lo + 1 {
263
            st.testing = None;
264
            self.bisect_save(st)?;
265
            return Ok(BisectStep::Found {
266
                culprit: st.candidates[st.lo],
267
            });
268
        }
269
        let mid = st.lo + (st.hi - st.lo) / 2;
270
        // Try mid, then the nearest untried indices on either side.
271
        let mut order = vec![mid];
272
        for d in 1..(st.hi - st.lo) {
273
            if mid + d < st.hi {
274
                order.push(mid + d);
275
            }
276
            if mid > st.lo + d {
277
                order.push(mid - d);
278
            }
279
        }
280
        let Some(k) = order.into_iter().find(|k| !st.skipped.contains(k)) else {
281
            st.testing = None;
282
            self.bisect_save(st)?;
283
            return Ok(BisectStep::Inconclusive {
284
                candidates: st.candidates[st.lo..st.hi].to_vec(),
285
            });
286
        };
287
        let heads = self.bisect_heads(st, k);
288
        self.checkout(
289
            &heads,
290
            false,
291
            &format!("oxy bisect (testing {k} of {})", st.candidates.len()),
292
        )?;
293
        st.testing = Some(k);
294
        self.bisect_save(st)?;
295
        let remaining = st.hi - st.lo;
296
        Ok(BisectStep::Testing {
297
            heads,
298
            remaining,
299
            steps_left: (remaining as f64).log2().ceil() as u32,
300
        })
301
    }
302
303
    /// Mark states good or bad. With `changes`, before the search starts,
304
    /// they name known-good or known-bad states; without, the state under
305
    /// test gets the verdict. `None` for `good` means skip (untestable).
306
    pub fn bisect_mark(&self, good: Option<bool>, changes: &[ChangeHash]) -> Result<BisectStep> {
307
        let Some(mut st) = self.bisect_load()? else {
308
            return fail("no bisect in progress; run `oxy bisect start`");
309
        };
310
        if !changes.is_empty() {
311
            if !st.candidates.is_empty() {
312
                return fail("the search has started; mark the state under test with plain `oxy bisect good|bad`");
313
            }
314
            match good {
315
                Some(true) => st.good.extend(changes.iter().copied()),
316
                Some(false) => st.bad.extend(changes.iter().copied()),
317
                None => return fail("skip applies to the state under test"),
318
            }
319
            if st.good.is_empty() || st.bad.is_empty() {
320
                self.bisect_save(&st)?;
321
                return Ok(BisectStep::NeedMarks {
322
                    good: st.good.len(),
323
                    bad: st.bad.len(),
324
                });
325
            }
326
            let good_heads = self.load_state(&st.good)?.maximal(&st.good);
327
            let bad_heads = self.load_state(&st.bad)?.maximal(&st.bad);
328
            st.good = good_heads.clone();
329
            st.bad = bad_heads.clone();
330
            st.candidates = self.negotiate(&good_heads, &bad_heads)?;
331
            if st.candidates.is_empty() {
332
                return fail("the bad state adds nothing to the good state; nothing to bisect");
333
            }
334
            st.lo = 0;
335
            st.hi = st.candidates.len();
336
            return self.bisect_advance(&mut st);
337
        }
338
        let Some(k) = st.testing else {
339
            return fail("no state is under test; give `oxy bisect good|bad` a change or bookmark to start with");
340
        };
341
        match good {
342
            Some(true) => st.lo = k,
343
            Some(false) => st.hi = k,
344
            None => st.skipped.push(k),
345
        }
346
        self.bisect_advance(&mut st)
347
    }
348
349
    /// Automate with a command run in the working copy: exit 0 is good, 125
350
    /// skips, anything else is bad.
351
    pub fn bisect_run(&self, command: &[String]) -> Result<BisectStep> {
352
        let Some(st) = self.bisect_load()? else {
353
            return fail("no bisect in progress; run `oxy bisect start`");
354
        };
355
        if st.testing.is_none() {
356
            return Ok(self.bisect_step(&st));
357
        }
358
        loop {
359
            let status = std::process::Command::new(&command[0])
360
                .args(&command[1..])
361
                .current_dir(&self.root)
362
                .status()
363
                .map_err(|e| RepoError::Msg(format!("running {}: {e}", command[0])))?;
364
            let verdict = match status.code() {
365
                Some(0) => Some(true),
366
                Some(125) => None,
367
                _ => Some(false),
368
            };
369
            match self.bisect_mark(verdict, &[])? {
370
                BisectStep::Testing { .. } => continue,
371
                done => return Ok(done),
372
            }
373
        }
374
    }
375
}
376
377
/// What `oxy describe` reports about the working copy (spec §10.1).
378
#[derive(Clone, Debug, PartialEq, Eq)]
379
pub struct Description {
380
    /// The tag of the base state, or the nearest tag below it.
381
    pub tag: Option<String>,
382
    /// Changes in the base state that the tag's state lacks (0: exact).
383
    pub distance: usize,
384
    pub bookmark: String,
385
    /// The base's newest head.
386
    pub change: ChangeId,
387
    pub hash: ChangeHash,
388
    /// Whether the working copy has uncommitted changes.
389
    pub dirty: bool,
390
}
391
392
impl Description {
393
    /// `v1.2`, `v1.2-3-8c5ea12a`, or `develop-8c5ea12a`, and `-dirty`.
394
    pub fn line(&self) -> String {
395
        let short = self.change.short(8);
396
        let base = match (&self.tag, self.distance) {
397
            (Some(t), 0) => t.clone(),
398
            (Some(t), n) => format!("{t}-{n}-{short}"),
399
            (None, _) => format!("{}-{short}", self.bookmark),
400
        };
401
        if self.dirty {
402
            format!("{base}-dirty")
403
        } else {
404
            base
405
        }
406
    }
407
}
408
409
impl Repo {
410
    /// Name the working copy for builds (`oxy describe`, like `git
411
    /// describe`): the tag of its base state; else the nearest tag whose
412
    /// state the base contains, with how many changes it adds and its
413
    /// newest head; else the bookmark and that head. `dirty` when the
414
    /// working copy has uncommitted changes.
415
    pub fn describe_working_copy(&self) -> Result<Description> {
416
        let snap = self.snapshot_status("oxy describe")?;
417
        let dirty = !snap.statuses.is_empty();
418
        let base = snap.base.maximal(&snap.wc.deps);
419
        let Some(&newest) = base
420
            .iter()
421
            .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
422
        else {
423
            return fail("the working copy sits on no change yet");
424
        };
425
        let Some(change) = snap.base.get(&newest).map(|m| m.change_id) else {
426
            return fail("the working copy's base is not loaded");
427
        };
428
        let mut sorted = base.clone();
429
        sorted.sort();
430
        let mut best: Option<(usize, String)> = None;
431
        for t in self.tags()? {
432
            if !t.heads.iter().all(|h| snap.base.contains(h)) {
433
                continue;
434
            }
435
            let mut tagged: std::collections::HashSet<ChangeHash> =
436
                t.heads.iter().copied().collect();
437
            for h in &t.heads {
438
                tagged.extend(snap.base.closure(h).iter().copied());
439
            }
440
            let mut heads = t.heads.clone();
441
            heads.sort();
442
            let distance = if heads == sorted {
443
                0
444
            } else {
445
                snap.base.len().saturating_sub(tagged.len()).max(1)
446
            };
447
            if best
448
                .as_ref()
449
                .is_none_or(|(d, n)| distance < *d || (distance == *d && t.name < *n))
450
            {
451
                best = Some((distance, t.name));
452
            }
453
        }
454
        let (distance, tag) = match best {
455
            Some((d, t)) => (d, Some(t)),
456
            None => (0, None),
457
        };
458
        Ok(Description {
459
            tag,
460
            distance,
461
            bookmark: self.config.bookmark.clone(),
462
            change,
463
            hash: newest,
464
            dirty,
465
        })
466
    }
467
}