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