OXYGENHUB
◆ bare-hashes oxygen / crates / oxy-core / src / repo / revset.rs
29.8 KiB · Rust · last changed log --path and touches() without decoding all of history 26 days ago source blame history raw
47ce8b8e Andy McCall ↶ 1
//! Evaluating revsets (docs/revset_query_language.md §4) over a repository.
2
//!
3
//! The graph is the change metadata the state index already holds: a
4
//! symbol loads the closure of the heads it names, and `all()`, `X::`,
5
//! `dependents()` and `roots()` load every bookmark, remote bookmark, tag
6
//! and the working copy. Evaluation is read-only and has a time budget;
7
//! a query past it fails and says what to narrow.
8
9
use super::*;
10
use crate::ids::NodeId;
11
use crate::revset::{self, Expr};
12
use crate::state::ChangeMeta;
13
use std::time::{Duration, Instant};
14
15
type Set = BTreeSet<ChangeHash>;
16
17
/// The default budget for a command-line evaluation.
18
pub const REVSET_BUDGET: Duration = Duration::from_secs(10);
19
20
/// A revset's result with the metadata of every change it names.
21
#[derive(Clone, Debug)]
22
pub struct Revset {
23
    /// Newest first, as a log is ordered.
24
    pub hashes: Vec<ChangeHash>,
25
    pub metas: HashMap<ChangeHash, ChangeMeta>,
26
}
27
28
struct Eval<'a> {
29
    repo: &'a Repo,
30
    graph: HashMap<ChangeHash, ChangeMeta>,
31
    /// Which heads have had their closure loaded.
32
    loaded: HashSet<ChangeHash>,
33
    all_loaded: bool,
34
    dependents: Option<HashMap<ChangeHash, Vec<ChangeHash>>>,
35
    names: HashMap<KeyId, Option<(String, String)>>,
2c9ddac3 Andy McCall ↶ 36
    /// Who authenticated each change, once asked (signature checks cost).
37
    auth: HashMap<ChangeHash, SignatureStatus>,
47ce8b8e Andy McCall ↶ 38
    deadline: Instant,
39
    budget: Duration,
40
    now_ms: u64,
41
    depth: usize,
42
}
43
44
fn err(msg: impl Into<String>) -> RepoError {
45
    RepoError::Msg(msg.into())
46
}
47
48
impl<'a> Eval<'a> {
49
    fn tick(&self) -> Result<()> {
50
        if Instant::now() > self.deadline {
51
            return Err(err(format!(
52
                "the revset went past its budget of {:.0} s; narrow it with a range such as main.. or a date()",
53
                self.budget.as_secs_f64()
54
            )));
55
        }
56
        Ok(())
57
    }
58
59
    /// Load the closure of `heads` into the graph.
60
    fn ensure(&mut self, heads: &[ChangeHash]) -> Result<()> {
61
        let fresh: Vec<ChangeHash> = heads
62
            .iter()
63
            .copied()
64
            .filter(|h| !self.loaded.contains(h))
65
            .collect();
66
        if fresh.is_empty() {
67
            return Ok(());
68
        }
69
        for (h, m) in self.repo.metas_of(&fresh)? {
70
            self.graph.insert(h, m);
71
        }
72
        self.loaded.extend(fresh);
73
        self.dependents = None;
74
        self.tick()
75
    }
76
77
    /// Load every change the repository names: bookmarks, remote
78
    /// bookmarks, tags, and the working copy.
79
    fn load_all(&mut self) -> Result<()> {
80
        if self.all_loaded {
81
            return Ok(());
82
        }
83
        let view = self.repo.view()?;
84
        let mut heads: Vec<ChangeHash> = Vec::new();
85
        for st in view.bookmarks.values() {
86
            heads.extend(self.repo.store().get_state(st)?.heads);
87
        }
88
        for bookmarks in view.remotes.values() {
89
            for st in bookmarks.values() {
90
                heads.extend(self.repo.store().get_state(st)?.heads);
91
            }
92
        }
93
        for st in view.tags.values() {
94
            heads.extend(self.repo.store().get_state(st)?.heads);
95
        }
96
        if let Some(wc) = self.working_copy() {
97
            heads.push(wc);
98
        }
99
        heads.sort();
100
        heads.dedup();
101
        self.ensure(&heads)?;
102
        self.all_loaded = true;
103
        Ok(())
104
    }
105
106
    fn working_copy(&self) -> Option<ChangeHash> {
107
        if self.repo.is_bare() {
108
            None
109
        } else {
110
            self.repo.working_copy().ok().map(|(h, _)| h)
111
        }
112
    }
113
114
    fn all(&mut self) -> Result<Set> {
115
        self.load_all()?;
116
        Ok(self.graph.keys().copied().collect())
117
    }
118
119
    fn dependents_map(&mut self) -> Result<&HashMap<ChangeHash, Vec<ChangeHash>>> {
120
        self.load_all()?;
121
        if self.dependents.is_none() {
122
            let mut map: HashMap<ChangeHash, Vec<ChangeHash>> = HashMap::new();
123
            for (h, m) in &self.graph {
124
                for d in &m.deps {
125
                    map.entry(*d).or_default().push(*h);
126
                }
127
            }
128
            self.dependents = Some(map);
129
        }
130
        Ok(self.dependents.as_ref().unwrap())
131
    }
132
133
    /// `::X`: the members and their dependency closures.
134
    fn ancestors(&mut self, set: &Set) -> Result<Set> {
135
        let mut out = set.clone();
136
        let mut stack: Vec<ChangeHash> = set.iter().copied().collect();
137
        let mut n = 0usize;
138
        while let Some(h) = stack.pop() {
139
            if let Some(m) = self.graph.get(&h) {
140
                for d in &m.deps {
141
                    if out.insert(*d) {
142
                        stack.push(*d);
143
                    }
144
                }
145
            }
146
            n += 1;
147
            if n.is_multiple_of(4096) {
148
                self.tick()?;
149
            }
150
        }
151
        Ok(out)
152
    }
153
154
    /// `X::`: the members and everything that transitively depends on them.
155
    fn descendants(&mut self, set: &Set) -> Result<Set> {
156
        let mut out = set.clone();
157
        let mut stack: Vec<ChangeHash> = set.iter().copied().collect();
158
        let deps = self.dependents_map()?;
159
        while let Some(h) = stack.pop() {
160
            if let Some(ds) = deps.get(&h) {
161
                for d in ds {
162
                    if out.insert(*d) {
163
                        stack.push(*d);
164
                    }
165
                }
166
            }
167
        }
168
        Ok(out)
169
    }
170
171
    /// Members no other member depends on, directly or through others.
172
    fn heads(&mut self, set: &Set) -> Result<Set> {
173
        let mut below: HashSet<ChangeHash> = HashSet::new();
174
        let mut stack: Vec<ChangeHash> = set
175
            .iter()
176
            .filter_map(|h| self.graph.get(h))
177
            .flat_map(|m| m.deps.iter().copied())
178
            .collect();
179
        while let Some(h) = stack.pop() {
180
            if below.insert(h) {
181
                if let Some(m) = self.graph.get(&h) {
182
                    stack.extend(m.deps.iter().copied());
183
                }
184
            }
185
        }
186
        Ok(set.iter().copied().filter(|h| !below.contains(h)).collect())
187
    }
188
189
    /// Members that depend on no other member, directly or through others.
190
    fn roots(&mut self, set: &Set) -> Result<Set> {
191
        let deps = self.dependents_map()?;
192
        let mut above: HashSet<ChangeHash> = HashSet::new();
193
        let mut stack: Vec<ChangeHash> = set
194
            .iter()
195
            .filter_map(|h| deps.get(h))
196
            .flat_map(|ds| ds.iter().copied())
197
            .collect();
198
        while let Some(h) = stack.pop() {
199
            if above.insert(h) {
200
                if let Some(ds) = deps.get(&h) {
201
                    stack.extend(ds.iter().copied());
202
                }
203
            }
204
        }
205
        Ok(set.iter().copied().filter(|h| !above.contains(h)).collect())
206
    }
207
208
    fn symbol(&mut self, name: &str) -> Result<Set> {
209
        if name == "@" {
210
            let Some(wc) = self.working_copy() else {
211
                return Err(err(
212
                    "@ names the working copy, and a bare repository has none",
213
                ));
214
            };
215
            self.ensure(&[wc])?;
216
            return Ok([wc].into_iter().collect());
217
        }
218
        let heads = self.repo.resolve_heads(name)?;
219
        self.ensure(&heads)?;
220
        Ok(heads.into_iter().collect())
221
    }
222
223
    /// The identity's name and email, if its object is known.
224
    fn who(&mut self, key: &KeyId) -> Option<(String, String)> {
225
        if let Some(w) = self.names.get(key) {
226
            return w.clone();
227
        }
228
        let w = self.repo.identity(key).ok().map(|id| (id.name, id.email));
229
        self.names.insert(*key, w.clone());
230
        w
231
    }
232
233
    /// The set a predicate ranges over: what it is intersected with when
234
    /// that is known, else everything.
235
    fn universe(&mut self, within: Option<&Set>) -> Result<Set> {
236
        match within {
237
            Some(s) => Ok(s.clone()),
238
            None => self.all(),
239
        }
240
    }
241
242
    fn filter_metas(
243
        &mut self,
244
        within: Option<&Set>,
245
        mut keep: impl FnMut(&ChangeHash, &ChangeMeta) -> bool,
246
    ) -> Result<Set> {
247
        let candidates = self.universe(within)?;
248
        let mut out = Set::new();
249
        for (i, h) in candidates.iter().enumerate() {
250
            if let Some(m) = self.graph.get(h) {
251
                if keep(h, m) {
252
                    out.insert(*h);
253
                }
254
            }
255
            if i % 8192 == 8191 {
256
                self.tick()?;
257
            }
258
        }
259
        Ok(out)
260
    }
261
262
    /// Changes touching any node whose path matches `glob` in the
263
    /// evaluation state: the working copy's base, or the bookmark's state
264
    /// in a bare repository. Nodes keep their identity through renames.
265
    fn touches(&mut self, within: Option<&Set>, glob: &str) -> Result<Set> {
266
        let matcher = globset::GlobBuilder::new(glob)
267
            .literal_separator(false)
268
            .build()
269
            .map_err(|e| err(format!("touches({glob:?}): {e}")))?
270
            .compile_matcher();
170bb436 Andy McCall ↶ 271
        // The tree alone names the nodes: no file graph is built. The
272
        // working copy's base comes from the workspace's state index.
273
        let state = match self.working_copy() {
274
            Some(wc) => {
275
                let deps = self
276
                    .graph
277
                    .get(&wc)
278
                    .map(|m| m.deps.clone())
279
                    .or_else(|| self.repo.working_copy().ok().map(|(_, c)| c.deps))
280
                    .unwrap_or_default();
281
                self.repo.load_state_indexed(&deps)?
282
            }
283
            None => self.repo.load_state_history(&self.repo.bookmark_heads()?)?,
47ce8b8e Andy McCall ↶ 284
        };
285
        let nodes: HashSet<NodeId> = state
286
            .tree()
287
            .view()
288
            .entries
289
            .iter()
290
            .filter(|(path, _)| matcher.is_match(path))
291
            .map(|(_, e)| e.node)
292
            .collect();
293
        if nodes.is_empty() {
294
            return Ok(Set::new());
295
        }
296
        let candidates = self.universe(within)?;
170bb436 Andy McCall ↶ 297
        let mut touched = self.repo.touched();
298
        touched.fill(self.repo, &candidates.iter().copied().collect::<Vec<_>>());
47ce8b8e Andy McCall ↶ 299
        let mut out = Set::new();
300
        for (i, h) in candidates.iter().enumerate() {
170bb436 Andy McCall ↶ 301
            if touched.touches(self.repo, h, &nodes) {
47ce8b8e Andy McCall ↶ 302
                out.insert(*h);
303
            }
304
            if i % 256 == 255 {
305
                self.tick()?;
306
            }
307
        }
170bb436 Andy McCall ↶ 308
        touched.save();
47ce8b8e Andy McCall ↶ 309
        Ok(out)
310
    }
311
312
    fn text_arg<'e>(&self, name: &str, args: &'e [Expr], i: usize) -> Result<&'e str> {
313
        match args.get(i) {
314
            Some(Expr::Symbol(s)) => Ok(s),
315
            _ => Err(err(format!("{name}() takes text, quoted if it has spaces"))),
316
        }
317
    }
318
319
    fn arity(&self, name: &str, args: &[Expr], n: usize) -> Result<()> {
320
        if args.len() != n {
321
            return Err(err(format!(
322
                "{name}() takes {n} argument{}, not {}",
323
                if n == 1 { "" } else { "s" },
324
                args.len()
325
            )));
326
        }
327
        Ok(())
328
    }
329
330
    fn call(&mut self, name: &str, args: &[Expr], within: Option<&Set>) -> Result<Set> {
331
        match name {
332
            "all" => {
333
                self.arity(name, args, 0)?;
334
                self.universe(within)
335
            }
336
            "none" => {
337
                self.arity(name, args, 0)?;
338
                Ok(Set::new())
339
            }
340
            "deps" => {
341
                self.arity(name, args, 1)?;
342
                let x = self.eval(&args[0], None)?;
343
                let mut out = Set::new();
344
                for h in &x {
345
                    if let Some(m) = self.graph.get(h) {
346
                        out.extend(m.deps.iter().copied());
347
                    }
348
                }
349
                Ok(out)
350
            }
351
            "dependents" => {
352
                self.arity(name, args, 1)?;
353
                let x = self.eval(&args[0], None)?;
354
                let deps = self.dependents_map()?;
355
                let mut out = Set::new();
356
                for h in &x {
357
                    if let Some(ds) = deps.get(h) {
358
                        out.extend(ds.iter().copied());
359
                    }
360
                }
361
                Ok(out)
362
            }
363
            "heads" => {
364
                self.arity(name, args, 1)?;
365
                let x = self.eval(&args[0], None)?;
366
                self.heads(&x)
367
            }
368
            "roots" => {
369
                self.arity(name, args, 1)?;
370
                let x = self.eval(&args[0], None)?;
371
                self.roots(&x)
372
            }
543bbf64 Andy McCall ↶ 373
            "independent" => {
374
                self.arity(name, args, 2)?;
375
                let x = self.eval(&args[0], None)?;
376
                let inn = self.eval(&args[1], None)?;
377
                let below = self.ancestors(&x)?;
378
                let above = self.descendants(&x)?;
379
                Ok(inn
380
                    .into_iter()
381
                    .filter(|h| !below.contains(h) && !above.contains(h))
382
                    .collect())
383
            }
384
            "conflicts" => {
385
                if args.len() > 1 {
386
                    return Err(err(
387
                        "conflicts() takes a state, or nothing for the working copy's",
388
                    ));
389
                }
390
                let heads: Vec<ChangeHash> = match args.first() {
391
                    Some(e) => self.eval(e, None)?.into_iter().collect(),
392
                    None => match self.working_copy() {
393
                        Some(wc) => {
394
                            self.ensure(&[wc])?;
395
                            self.graph
396
                                .get(&wc)
397
                                .map(|m| m.deps.clone())
398
                                .unwrap_or_default()
399
                        }
400
                        None => self.repo.bookmark_heads()?,
401
                    },
402
                };
403
                self.conflicts(within, &heads)
404
            }
47ce8b8e Andy McCall ↶ 405
            "latest" => {
406
                self.arity(name, args, 2)?;
407
                let x = self.eval(&args[0], None)?;
408
                let n: usize = self
409
                    .text_arg(name, args, 1)?
410
                    .parse()
411
                    .map_err(|_| err("latest(X, n) takes a count"))?;
412
                let mut members: Vec<ChangeHash> = x.into_iter().collect();
413
                self.sort_newest_first(&mut members);
414
                Ok(members.into_iter().take(n).collect())
415
            }
416
            "author" => {
417
                self.arity(name, args, 1)?;
418
                let who = self.text_arg(name, args, 0)?.to_string();
419
                let mut matches: HashMap<KeyId, bool> = HashMap::new();
420
                self.filter_metas_with(within, |ev, _, m| {
421
                    if let Some(hit) = matches.get(&m.author) {
422
                        return *hit;
423
                    }
2c9ddac3 Andy McCall ↶ 424
                    let hit = ev.names_key(&who, &m.author);
47ce8b8e Andy McCall ↶ 425
                    matches.insert(m.author, hit);
426
                    hit
427
                })
428
            }
429
            "description" => {
430
                self.arity(name, args, 1)?;
431
                let text = self.text_arg(name, args, 0)?.to_string();
432
                if text.starts_with("re:") {
433
                    return Err(err(
434
                        "description(re:…) is not supported yet; give a substring",
435
                    ));
436
                }
437
                let needle = text.to_lowercase();
438
                self.filter_metas(within, |_, m| m.message.to_lowercase().contains(&needle))
439
            }
440
            "date" => {
441
                self.arity(name, args, 1)?;
442
                let range = revset::parse_date_range(self.text_arg(name, args, 0)?, self.now_ms)
443
                    .map_err(err)?;
444
                self.filter_metas(within, |_, m| range.contains(m.hlc.wall_ms))
445
            }
446
            "kind" => {
447
                self.arity(name, args, 1)?;
448
                let kind = match self.text_arg(name, args, 0)? {
449
                    "normal" => ChangeKind::Normal,
450
                    "resolution" => ChangeKind::Resolution,
451
                    "working-copy" | "working_copy" => ChangeKind::WorkingCopy,
452
                    other => {
453
                        return Err(err(format!(
454
                            "kind({other:?}): use normal, resolution or working-copy"
455
                        )))
456
                    }
457
                };
458
                self.filter_metas(within, |_, m| m.kind == kind)
459
            }
460
            "touches" => {
461
                self.arity(name, args, 1)?;
462
                let glob = self.text_arg(name, args, 0)?.to_string();
463
                self.touches(within, &glob)
464
            }
2c9ddac3 Andy McCall ↶ 465
            // Trust (§2.4): what authenticated a change, and what vouched
466
            // for the states it is in.
467
            "signed_by" => {
468
                self.arity(name, args, 1)?;
469
                let who = self.text_arg(name, args, 0)?.to_string();
470
                self.filter_metas_with(within, |ev, h, m| match ev.auth(h, m) {
471
                    SignatureStatus::Valid { key, .. } => ev.names_key(&who, &key),
472
                    _ => false,
473
                })
474
            }
475
            "delegated" => {
476
                self.arity(name, args, 0)?;
477
                self.filter_metas_with(within, |ev, h, m| {
478
                    !m.author.is_zero()
479
                        && matches!(ev.auth(h, m), SignatureStatus::Valid { key, .. } if key != m.author)
480
                })
481
            }
482
            "unsigned" => {
483
                self.arity(name, args, 0)?;
484
                self.filter_metas_with(within, |ev, h, m| {
485
                    m.kind != ChangeKind::WorkingCopy
486
                        && !matches!(ev.auth(h, m), SignatureStatus::Valid { .. })
487
                })
488
            }
489
            "revoked" => {
490
                self.arity(name, args, 0)?;
491
                self.filter_metas_with(within, |ev, h, m| {
492
                    matches!(ev.auth(h, m), SignatureStatus::Valid { revoked: true, .. })
493
                })
494
            }
495
            "attested" => {
496
                self.arity(name, args, 1)?;
497
                let kind = self.text_arg(name, args, 0)?.to_string();
498
                self.attested(within, &kind)
499
            }
bf3a6781 Andy McCall ↶ 500
            // A bookmark's heads by name: what a bare bookmark symbol means,
501
            // without falling through to tags and change prefixes.
502
            "bookmark" => {
503
                self.arity(name, args, 1)?;
504
                let b = self.text_arg(name, args, 0)?;
505
                let view = self.repo.view()?;
506
                let st = match view.bookmarks.get(b) {
507
                    Some(st) => *st,
508
                    None => match remote_bookmark(&view, b) {
509
                        Some((_, _, st)) => st,
510
                        None => return Err(err(format!("bookmark({b}): no such bookmark"))),
511
                    },
512
                };
513
                let heads = self.repo.store().get_state(&st)?.heads;
514
                self.ensure(&heads)?;
515
                Ok(heads.into_iter().collect())
516
            }
2c9ddac3 Andy McCall ↶ 517
            "built" => {
518
                self.arity(name, args, 1)?;
519
                let job = self.text_arg(name, args, 0)?.to_string();
520
                self.built(within, &job)
521
            }
47ce8b8e Andy McCall ↶ 522
            other => {
523
                // A saved revset: `oxy config revset.NAME 'EXPR'` makes NAME().
524
                if let Some(saved) = self.repo.config.revsets.get(other).cloned() {
525
                    self.arity(name, args, 0)?;
526
                    if self.depth >= 16 {
527
                        return Err(err(format!("revset.{other} refers to itself")));
528
                    }
529
                    let e = revset::parse(&saved)
530
                        .map_err(|e| err(format!("revset.{other} = {saved:?}: {e}")))?;
531
                    self.depth += 1;
532
                    let r = self.eval(&e, within);
533
                    self.depth -= 1;
534
                    return r;
535
                }
536
                Err(err(format!(
537
                    "unknown function {other}(); see docs/revset_query_language.md"
538
                )))
2c9ddac3 Andy McCall ↶ 539
            }
540
        }
541
    }
542
543
    /// The authentication of a change: its signature or seal, checked once.
544
    fn auth(&mut self, h: &ChangeHash, m: &ChangeMeta) -> SignatureStatus {
545
        if let Some(s) = self.auth.get(h) {
546
            return s.clone();
547
        }
548
        let s = self
549
            .repo
550
            .authenticate_change_known(h, Some(m))
551
            .unwrap_or_else(|e| SignatureStatus::Invalid(e.to_string()));
552
        self.auth.insert(*h, s.clone());
553
        s
554
    }
555
556
    /// Whether `who` names key `key`: by hex prefix, `me`, or the name or
557
    /// email of its identity.
558
    fn names_key(&mut self, who: &str, key: &KeyId) -> bool {
559
        (who == "me" && Some(*key) == self.repo.config.author_key)
560
            || key.starts_with_hex(who)
561
            || self.who(key).is_some_and(|(n, e)| {
562
                let needle = who.to_lowercase();
563
                n.to_lowercase().contains(&needle) || e.to_lowercase().contains(&needle)
564
            })
565
    }
566
567
    /// The closure of the states whose heads these are, within `within`.
568
    fn closure_of(&mut self, mut heads: Vec<ChangeHash>, within: Option<&Set>) -> Result<Set> {
569
        heads.sort();
570
        heads.dedup();
571
        self.ensure(&heads)?;
572
        let set: Set = heads.into_iter().collect();
573
        let closure = self.ancestors(&set)?;
574
        Ok(match within {
575
            Some(w) => closure.intersection(w).copied().collect(),
576
            None => closure,
577
        })
578
    }
579
580
    /// The closure of every state that carries an attestation of `kind`:
581
    /// `tag` (tagged states), `receipt` (states a runner reported on) or
582
    /// `ref` (states a remote attested, as its tracking bookmarks hold).
583
    fn attested(&mut self, within: Option<&Set>, kind: &str) -> Result<Set> {
584
        let mut heads: Vec<ChangeHash> = Vec::new();
585
        match kind {
586
            "tag" => {
587
                for t in self.repo.tags()? {
588
                    heads.extend(t.heads);
589
                }
590
            }
591
            "receipt" => {
592
                for st in self.repo.store().receipt_states()? {
593
                    if let Ok(s) = self.repo.store().get_state(&st) {
594
                        heads.extend(s.heads);
595
                    }
596
                }
597
            }
598
            "ref" => {
599
                let view = self.repo.view()?;
600
                for bookmarks in view.remotes.values() {
601
                    for st in bookmarks.values() {
602
                        heads.extend(self.repo.store().get_state(st)?.heads);
603
                    }
604
                }
605
            }
606
            other => return Err(err(format!("attested({other:?}): use tag, receipt or ref"))),
607
        }
608
        self.closure_of(heads, within)
609
    }
610
611
    /// The closure of every state with a valid receipt for Flow job `job`
612
    /// from a runner whose key is not revoked.
613
    fn built(&mut self, within: Option<&Set>, job: &str) -> Result<Set> {
614
        let mut heads: Vec<ChangeHash> = Vec::new();
615
        for st in self.repo.store().receipt_states()? {
616
            let Ok(state) = self.repo.store().get_state(&st) else {
617
                continue;
618
            };
619
            let good = self
620
                .repo
621
                .receipts(&state.heads)?
622
                .into_iter()
623
                .any(|r| r.signed.receipt.job_name == job && r.problem.is_none() && !r.revoked);
624
            if good {
625
                heads.extend(state.heads);
47ce8b8e Andy McCall ↶ 626
            }
2c9ddac3 Andy McCall ↶ 627
            self.tick()?;
47ce8b8e Andy McCall ↶ 628
        }
2c9ddac3 Andy McCall ↶ 629
        self.closure_of(heads, within)
543bbf64 Andy McCall ↶ 630
    }
631
632
    /// `conflicts(S)`: the changes that contributed atoms to a conflict in
633
    /// the state `heads` name (conflicts belong to states, not changes).
634
    fn conflicts(&mut self, within: Option<&Set>, heads: &[ChangeHash]) -> Result<Set> {
635
        let state = self.repo.load_state(heads)?;
636
        let snapshot = state.materialize();
637
        let mut out = Set::new();
638
        for f in snapshot.files.values() {
639
            if !f.is_conflicted() {
640
                continue;
641
            }
642
            match &f.content {
643
                crate::state::FileContent::Text { .. } => {
644
                    out.extend(state.conflict_regions(&f.node).contributors);
645
                }
646
                crate::state::FileContent::Opaque { blobs } => {
647
                    out.extend(state.blob_contributors(&f.node, blobs));
648
                }
649
                crate::state::FileContent::Dir => {}
650
            }
651
            self.tick()?;
652
        }
653
        self.ensure(heads)?;
654
        Ok(match within {
655
            Some(w) => out.intersection(w).copied().collect(),
656
            None => out,
657
        })
47ce8b8e Andy McCall ↶ 658
    }
659
660
    /// `filter_metas` for a test that needs the evaluator (identity lookups).
661
    fn filter_metas_with(
662
        &mut self,
663
        within: Option<&Set>,
664
        mut keep: impl FnMut(&mut Eval<'a>, &ChangeHash, &ChangeMeta) -> bool,
665
    ) -> Result<Set> {
666
        let candidates = self.universe(within)?;
667
        let mut out = Set::new();
668
        for (i, h) in candidates.iter().enumerate() {
669
            if let Some(m) = self.graph.get(h).cloned() {
670
                if keep(self, h, &m) {
671
                    out.insert(*h);
672
                }
673
            }
674
            if i % 8192 == 8191 {
675
                self.tick()?;
676
            }
677
        }
678
        Ok(out)
679
    }
680
681
    /// Whether an expression selects by a property, so that evaluating it
682
    /// within the other side of an intersection saves scanning everything.
683
    fn is_predicate(e: &Expr) -> bool {
684
        match e {
685
            Expr::Call(name, _) => matches!(
686
                name.as_str(),
2c9ddac3 Andy McCall ↶ 687
                "author"
688
                    | "description"
689
                    | "date"
690
                    | "kind"
691
                    | "touches"
692
                    | "all"
693
                    | "signed_by"
694
                    | "delegated"
695
                    | "unsigned"
696
                    | "revoked"
697
                    | "attested"
698
                    | "built"
543bbf64 Andy McCall ↶ 699
                    | "conflicts"
47ce8b8e Andy McCall ↶ 700
            ),
701
            Expr::Intersection(a, b) => Self::is_predicate(a) || Self::is_predicate(b),
702
            Expr::Union(a, b) => Self::is_predicate(a) && Self::is_predicate(b),
703
            Expr::Difference(a, _) => Self::is_predicate(a),
704
            _ => false,
705
        }
706
    }
707
708
    fn eval(&mut self, e: &Expr, within: Option<&Set>) -> Result<Set> {
709
        self.tick()?;
710
        match e {
711
            Expr::Symbol(s) => self.symbol(s),
712
            Expr::Ancestors(x) => {
713
                let x = self.eval(x, None)?;
714
                self.ancestors(&x)
715
            }
716
            Expr::Descendants(x) => {
717
                let x = self.eval(x, None)?;
718
                self.descendants(&x)
719
            }
720
            Expr::Between(x, y) => {
721
                let x = self.eval(x, None)?;
722
                let y = self.eval(y, None)?;
723
                let down = self.descendants(&x)?;
724
                let up = self.ancestors(&y)?;
725
                Ok(down.intersection(&up).copied().collect())
726
            }
727
            Expr::Range(x, y) => {
728
                let x = self.eval(x, None)?;
729
                let y = self.eval(y, None)?;
730
                let from = self.ancestors(&x)?;
731
                let to = self.ancestors(&y)?;
732
                Ok(to.difference(&from).copied().collect())
733
            }
734
            Expr::Union(a, b) => {
735
                let mut a = self.eval(a, within)?;
736
                a.extend(self.eval(b, within)?);
737
                Ok(a)
738
            }
739
            Expr::Intersection(a, b) => {
740
                let (first, second) = if Self::is_predicate(a) && !Self::is_predicate(b) {
741
                    (b, a)
742
                } else {
743
                    (a, b)
744
                };
745
                let left = self.eval(first, within)?;
746
                let right = self.eval(second, Some(&left))?;
747
                Ok(left.intersection(&right).copied().collect())
748
            }
749
            Expr::Difference(a, b) => {
750
                let left = self.eval(a, within)?;
751
                let right = self.eval(b, Some(&left))?;
752
                Ok(left.difference(&right).copied().collect())
753
            }
754
            Expr::Call(name, args) => self.call(name, args, within),
755
        }
756
    }
757
758
    fn sort_newest_first(&self, hashes: &mut [ChangeHash]) {
759
        hashes.sort_by(|a, b| {
760
            let (ma, mb) = (self.graph.get(a), self.graph.get(b));
761
            mb.map(|m| m.hlc).cmp(&ma.map(|m| m.hlc)).then(b.cmp(a))
762
        });
763
    }
764
}
765
766
impl Repo {
767
    /// Evaluate a revset within [`REVSET_BUDGET`].
768
    pub fn revset(&self, src: &str) -> Result<Revset> {
769
        self.revset_with_budget(src, REVSET_BUDGET)
770
    }
771
772
    /// Evaluate a revset: the changes it selects, newest first, with
773
    /// their metadata. Read-only. Fails past `budget`.
774
    pub fn revset_with_budget(&self, src: &str, budget: Duration) -> Result<Revset> {
775
        let expr = revset::parse(src).map_err(|e| err(format!("revset {src:?}: {e}")))?;
776
        let mut ev = Eval {
777
            repo: self,
778
            graph: HashMap::new(),
779
            loaded: HashSet::new(),
780
            all_loaded: false,
781
            dependents: None,
782
            names: HashMap::new(),
2c9ddac3 Andy McCall ↶ 783
            auth: HashMap::new(),
47ce8b8e Andy McCall ↶ 784
            deadline: Instant::now() + budget,
785
            budget,
786
            now_ms: Hlc::now().wall_ms,
787
            depth: 0,
788
        };
789
        let set = ev.eval(&expr, None)?;
790
        let mut hashes: Vec<ChangeHash> = set.into_iter().collect();
791
        ev.sort_newest_first(&mut hashes);
792
        let metas = hashes
793
            .iter()
794
            .filter_map(|h| ev.graph.get(h).map(|m| (*h, m.clone())))
795
            .collect();
796
        Ok(Revset { hashes, metas })
797
    }
798
799
    /// The log entries a revset selects, newest first. A head of the
800
    /// current bookmark is marked as in `log`.
801
    pub fn log_revset(&self, src: &str) -> Result<Vec<LogEntry>> {
802
        let r = self.revset(src)?;
803
        let heads: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
804
        let wc = if self.is_bare() {
805
            None
806
        } else {
807
            self.working_copy().ok().map(|(h, _)| h)
808
        };
809
        let mut entries: Vec<LogEntry> = r
810
            .hashes
811
            .iter()
812
            .filter_map(|h| {
813
                r.metas.get(h).map(|m| LogEntry {
814
                    hash: *h,
815
                    change: m.clone(),
816
                    is_working_copy: Some(*h) == wc,
817
                    is_head: heads.contains(h),
818
                })
819
            })
820
            .collect();
821
        // The working copy first, as `log` shows it.
822
        entries.sort_by_key(|e| !e.is_working_copy);
823
        Ok(entries)
824
    }
825
}