OXYGENHUB
◆ agents-in-readme oxygen / crates / oxy-core / src / repo / revset.rs
28.8 KiB · Rust · last changed Revsets: independent() and conflicts() 1 month ago source blame history raw
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)>>,
36
    /// Who authenticated each change, once asked (signature checks cost).
37
    auth: HashMap<ChangeHash, SignatureStatus>,
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();
271
        let heads = match self.working_copy() {
272
            Some(wc) => self
273
                .graph
274
                .get(&wc)
275
                .map(|m| m.deps.clone())
276
                .or_else(|| self.repo.working_copy().ok().map(|(_, c)| c.deps))
277
                .unwrap_or_default(),
278
            None => self.repo.bookmark_heads()?,
279
        };
280
        let state = self.repo.load_state(&heads)?;
281
        let nodes: HashSet<NodeId> = state
282
            .tree()
283
            .view()
284
            .entries
285
            .iter()
286
            .filter(|(path, _)| matcher.is_match(path))
287
            .map(|(_, e)| e.node)
288
            .collect();
289
        if nodes.is_empty() {
290
            return Ok(Set::new());
291
        }
292
        let candidates = self.universe(within)?;
293
        let mut out = Set::new();
294
        for (i, h) in candidates.iter().enumerate() {
295
            let Ok(c) = self.repo.store().get_change(h) else {
296
                continue;
297
            };
298
            if c.tree_ops.iter().any(|o| nodes.contains(&o.node()))
299
                || c.edits.iter().any(|e| nodes.contains(&e.node()))
300
            {
301
                out.insert(*h);
302
            }
303
            if i % 256 == 255 {
304
                self.tick()?;
305
            }
306
        }
307
        Ok(out)
308
    }
309
310
    fn text_arg<'e>(&self, name: &str, args: &'e [Expr], i: usize) -> Result<&'e str> {
311
        match args.get(i) {
312
            Some(Expr::Symbol(s)) => Ok(s),
313
            _ => Err(err(format!("{name}() takes text, quoted if it has spaces"))),
314
        }
315
    }
316
317
    fn arity(&self, name: &str, args: &[Expr], n: usize) -> Result<()> {
318
        if args.len() != n {
319
            return Err(err(format!(
320
                "{name}() takes {n} argument{}, not {}",
321
                if n == 1 { "" } else { "s" },
322
                args.len()
323
            )));
324
        }
325
        Ok(())
326
    }
327
328
    fn call(&mut self, name: &str, args: &[Expr], within: Option<&Set>) -> Result<Set> {
329
        match name {
330
            "all" => {
331
                self.arity(name, args, 0)?;
332
                self.universe(within)
333
            }
334
            "none" => {
335
                self.arity(name, args, 0)?;
336
                Ok(Set::new())
337
            }
338
            "deps" => {
339
                self.arity(name, args, 1)?;
340
                let x = self.eval(&args[0], None)?;
341
                let mut out = Set::new();
342
                for h in &x {
343
                    if let Some(m) = self.graph.get(h) {
344
                        out.extend(m.deps.iter().copied());
345
                    }
346
                }
347
                Ok(out)
348
            }
349
            "dependents" => {
350
                self.arity(name, args, 1)?;
351
                let x = self.eval(&args[0], None)?;
352
                let deps = self.dependents_map()?;
353
                let mut out = Set::new();
354
                for h in &x {
355
                    if let Some(ds) = deps.get(h) {
356
                        out.extend(ds.iter().copied());
357
                    }
358
                }
359
                Ok(out)
360
            }
361
            "heads" => {
362
                self.arity(name, args, 1)?;
363
                let x = self.eval(&args[0], None)?;
364
                self.heads(&x)
365
            }
366
            "roots" => {
367
                self.arity(name, args, 1)?;
368
                let x = self.eval(&args[0], None)?;
369
                self.roots(&x)
370
            }
371
            "independent" => {
372
                self.arity(name, args, 2)?;
373
                let x = self.eval(&args[0], None)?;
374
                let inn = self.eval(&args[1], None)?;
375
                let below = self.ancestors(&x)?;
376
                let above = self.descendants(&x)?;
377
                Ok(inn
378
                    .into_iter()
379
                    .filter(|h| !below.contains(h) && !above.contains(h))
380
                    .collect())
381
            }
382
            "conflicts" => {
383
                if args.len() > 1 {
384
                    return Err(err(
385
                        "conflicts() takes a state, or nothing for the working copy's",
386
                    ));
387
                }
388
                let heads: Vec<ChangeHash> = match args.first() {
389
                    Some(e) => self.eval(e, None)?.into_iter().collect(),
390
                    None => match self.working_copy() {
391
                        Some(wc) => {
392
                            self.ensure(&[wc])?;
393
                            self.graph
394
                                .get(&wc)
395
                                .map(|m| m.deps.clone())
396
                                .unwrap_or_default()
397
                        }
398
                        None => self.repo.bookmark_heads()?,
399
                    },
400
                };
401
                self.conflicts(within, &heads)
402
            }
403
            "latest" => {
404
                self.arity(name, args, 2)?;
405
                let x = self.eval(&args[0], None)?;
406
                let n: usize = self
407
                    .text_arg(name, args, 1)?
408
                    .parse()
409
                    .map_err(|_| err("latest(X, n) takes a count"))?;
410
                let mut members: Vec<ChangeHash> = x.into_iter().collect();
411
                self.sort_newest_first(&mut members);
412
                Ok(members.into_iter().take(n).collect())
413
            }
414
            "author" => {
415
                self.arity(name, args, 1)?;
416
                let who = self.text_arg(name, args, 0)?.to_string();
417
                let mut matches: HashMap<KeyId, bool> = HashMap::new();
418
                self.filter_metas_with(within, |ev, _, m| {
419
                    if let Some(hit) = matches.get(&m.author) {
420
                        return *hit;
421
                    }
422
                    let hit = ev.names_key(&who, &m.author);
423
                    matches.insert(m.author, hit);
424
                    hit
425
                })
426
            }
427
            "description" => {
428
                self.arity(name, args, 1)?;
429
                let text = self.text_arg(name, args, 0)?.to_string();
430
                if text.starts_with("re:") {
431
                    return Err(err(
432
                        "description(re:…) is not supported yet; give a substring",
433
                    ));
434
                }
435
                let needle = text.to_lowercase();
436
                self.filter_metas(within, |_, m| m.message.to_lowercase().contains(&needle))
437
            }
438
            "date" => {
439
                self.arity(name, args, 1)?;
440
                let range = revset::parse_date_range(self.text_arg(name, args, 0)?, self.now_ms)
441
                    .map_err(err)?;
442
                self.filter_metas(within, |_, m| range.contains(m.hlc.wall_ms))
443
            }
444
            "kind" => {
445
                self.arity(name, args, 1)?;
446
                let kind = match self.text_arg(name, args, 0)? {
447
                    "normal" => ChangeKind::Normal,
448
                    "resolution" => ChangeKind::Resolution,
449
                    "working-copy" | "working_copy" => ChangeKind::WorkingCopy,
450
                    other => {
451
                        return Err(err(format!(
452
                            "kind({other:?}): use normal, resolution or working-copy"
453
                        )))
454
                    }
455
                };
456
                self.filter_metas(within, |_, m| m.kind == kind)
457
            }
458
            "touches" => {
459
                self.arity(name, args, 1)?;
460
                let glob = self.text_arg(name, args, 0)?.to_string();
461
                self.touches(within, &glob)
462
            }
463
            // Trust (§2.4): what authenticated a change, and what vouched
464
            // for the states it is in.
465
            "signed_by" => {
466
                self.arity(name, args, 1)?;
467
                let who = self.text_arg(name, args, 0)?.to_string();
468
                self.filter_metas_with(within, |ev, h, m| match ev.auth(h, m) {
469
                    SignatureStatus::Valid { key, .. } => ev.names_key(&who, &key),
470
                    _ => false,
471
                })
472
            }
473
            "delegated" => {
474
                self.arity(name, args, 0)?;
475
                self.filter_metas_with(within, |ev, h, m| {
476
                    !m.author.is_zero()
477
                        && matches!(ev.auth(h, m), SignatureStatus::Valid { key, .. } if key != m.author)
478
                })
479
            }
480
            "unsigned" => {
481
                self.arity(name, args, 0)?;
482
                self.filter_metas_with(within, |ev, h, m| {
483
                    m.kind != ChangeKind::WorkingCopy
484
                        && !matches!(ev.auth(h, m), SignatureStatus::Valid { .. })
485
                })
486
            }
487
            "revoked" => {
488
                self.arity(name, args, 0)?;
489
                self.filter_metas_with(within, |ev, h, m| {
490
                    matches!(ev.auth(h, m), SignatureStatus::Valid { revoked: true, .. })
491
                })
492
            }
493
            "attested" => {
494
                self.arity(name, args, 1)?;
495
                let kind = self.text_arg(name, args, 0)?.to_string();
496
                self.attested(within, &kind)
497
            }
498
            "built" => {
499
                self.arity(name, args, 1)?;
500
                let job = self.text_arg(name, args, 0)?.to_string();
501
                self.built(within, &job)
502
            }
503
            other => {
504
                // A saved revset: `oxy config revset.NAME 'EXPR'` makes NAME().
505
                if let Some(saved) = self.repo.config.revsets.get(other).cloned() {
506
                    self.arity(name, args, 0)?;
507
                    if self.depth >= 16 {
508
                        return Err(err(format!("revset.{other} refers to itself")));
509
                    }
510
                    let e = revset::parse(&saved)
511
                        .map_err(|e| err(format!("revset.{other} = {saved:?}: {e}")))?;
512
                    self.depth += 1;
513
                    let r = self.eval(&e, within);
514
                    self.depth -= 1;
515
                    return r;
516
                }
517
                Err(err(format!(
518
                    "unknown function {other}(); see docs/revset_query_language.md"
519
                )))
520
            }
521
        }
522
    }
523
524
    /// The authentication of a change: its signature or seal, checked once.
525
    fn auth(&mut self, h: &ChangeHash, m: &ChangeMeta) -> SignatureStatus {
526
        if let Some(s) = self.auth.get(h) {
527
            return s.clone();
528
        }
529
        let s = self
530
            .repo
531
            .authenticate_change_known(h, Some(m))
532
            .unwrap_or_else(|e| SignatureStatus::Invalid(e.to_string()));
533
        self.auth.insert(*h, s.clone());
534
        s
535
    }
536
537
    /// Whether `who` names key `key`: by hex prefix, `me`, or the name or
538
    /// email of its identity.
539
    fn names_key(&mut self, who: &str, key: &KeyId) -> bool {
540
        (who == "me" && Some(*key) == self.repo.config.author_key)
541
            || key.starts_with_hex(who)
542
            || self.who(key).is_some_and(|(n, e)| {
543
                let needle = who.to_lowercase();
544
                n.to_lowercase().contains(&needle) || e.to_lowercase().contains(&needle)
545
            })
546
    }
547
548
    /// The closure of the states whose heads these are, within `within`.
549
    fn closure_of(&mut self, mut heads: Vec<ChangeHash>, within: Option<&Set>) -> Result<Set> {
550
        heads.sort();
551
        heads.dedup();
552
        self.ensure(&heads)?;
553
        let set: Set = heads.into_iter().collect();
554
        let closure = self.ancestors(&set)?;
555
        Ok(match within {
556
            Some(w) => closure.intersection(w).copied().collect(),
557
            None => closure,
558
        })
559
    }
560
561
    /// The closure of every state that carries an attestation of `kind`:
562
    /// `tag` (tagged states), `receipt` (states a runner reported on) or
563
    /// `ref` (states a remote attested, as its tracking bookmarks hold).
564
    fn attested(&mut self, within: Option<&Set>, kind: &str) -> Result<Set> {
565
        let mut heads: Vec<ChangeHash> = Vec::new();
566
        match kind {
567
            "tag" => {
568
                for t in self.repo.tags()? {
569
                    heads.extend(t.heads);
570
                }
571
            }
572
            "receipt" => {
573
                for st in self.repo.store().receipt_states()? {
574
                    if let Ok(s) = self.repo.store().get_state(&st) {
575
                        heads.extend(s.heads);
576
                    }
577
                }
578
            }
579
            "ref" => {
580
                let view = self.repo.view()?;
581
                for bookmarks in view.remotes.values() {
582
                    for st in bookmarks.values() {
583
                        heads.extend(self.repo.store().get_state(st)?.heads);
584
                    }
585
                }
586
            }
587
            other => return Err(err(format!("attested({other:?}): use tag, receipt or ref"))),
588
        }
589
        self.closure_of(heads, within)
590
    }
591
592
    /// The closure of every state with a valid receipt for Flow job `job`
593
    /// from a runner whose key is not revoked.
594
    fn built(&mut self, within: Option<&Set>, job: &str) -> Result<Set> {
595
        let mut heads: Vec<ChangeHash> = Vec::new();
596
        for st in self.repo.store().receipt_states()? {
597
            let Ok(state) = self.repo.store().get_state(&st) else {
598
                continue;
599
            };
600
            let good = self
601
                .repo
602
                .receipts(&state.heads)?
603
                .into_iter()
604
                .any(|r| r.signed.receipt.job_name == job && r.problem.is_none() && !r.revoked);
605
            if good {
606
                heads.extend(state.heads);
607
            }
608
            self.tick()?;
609
        }
610
        self.closure_of(heads, within)
611
    }
612
613
    /// `conflicts(S)`: the changes that contributed atoms to a conflict in
614
    /// the state `heads` name (conflicts belong to states, not changes).
615
    fn conflicts(&mut self, within: Option<&Set>, heads: &[ChangeHash]) -> Result<Set> {
616
        let state = self.repo.load_state(heads)?;
617
        let snapshot = state.materialize();
618
        let mut out = Set::new();
619
        for f in snapshot.files.values() {
620
            if !f.is_conflicted() {
621
                continue;
622
            }
623
            match &f.content {
624
                crate::state::FileContent::Text { .. } => {
625
                    out.extend(state.conflict_regions(&f.node).contributors);
626
                }
627
                crate::state::FileContent::Opaque { blobs } => {
628
                    out.extend(state.blob_contributors(&f.node, blobs));
629
                }
630
                crate::state::FileContent::Dir => {}
631
            }
632
            self.tick()?;
633
        }
634
        self.ensure(heads)?;
635
        Ok(match within {
636
            Some(w) => out.intersection(w).copied().collect(),
637
            None => out,
638
        })
639
    }
640
641
    /// `filter_metas` for a test that needs the evaluator (identity lookups).
642
    fn filter_metas_with(
643
        &mut self,
644
        within: Option<&Set>,
645
        mut keep: impl FnMut(&mut Eval<'a>, &ChangeHash, &ChangeMeta) -> bool,
646
    ) -> Result<Set> {
647
        let candidates = self.universe(within)?;
648
        let mut out = Set::new();
649
        for (i, h) in candidates.iter().enumerate() {
650
            if let Some(m) = self.graph.get(h).cloned() {
651
                if keep(self, h, &m) {
652
                    out.insert(*h);
653
                }
654
            }
655
            if i % 8192 == 8191 {
656
                self.tick()?;
657
            }
658
        }
659
        Ok(out)
660
    }
661
662
    /// Whether an expression selects by a property, so that evaluating it
663
    /// within the other side of an intersection saves scanning everything.
664
    fn is_predicate(e: &Expr) -> bool {
665
        match e {
666
            Expr::Call(name, _) => matches!(
667
                name.as_str(),
668
                "author"
669
                    | "description"
670
                    | "date"
671
                    | "kind"
672
                    | "touches"
673
                    | "all"
674
                    | "signed_by"
675
                    | "delegated"
676
                    | "unsigned"
677
                    | "revoked"
678
                    | "attested"
679
                    | "built"
680
                    | "conflicts"
681
            ),
682
            Expr::Intersection(a, b) => Self::is_predicate(a) || Self::is_predicate(b),
683
            Expr::Union(a, b) => Self::is_predicate(a) && Self::is_predicate(b),
684
            Expr::Difference(a, _) => Self::is_predicate(a),
685
            _ => false,
686
        }
687
    }
688
689
    fn eval(&mut self, e: &Expr, within: Option<&Set>) -> Result<Set> {
690
        self.tick()?;
691
        match e {
692
            Expr::Symbol(s) => self.symbol(s),
693
            Expr::Ancestors(x) => {
694
                let x = self.eval(x, None)?;
695
                self.ancestors(&x)
696
            }
697
            Expr::Descendants(x) => {
698
                let x = self.eval(x, None)?;
699
                self.descendants(&x)
700
            }
701
            Expr::Between(x, y) => {
702
                let x = self.eval(x, None)?;
703
                let y = self.eval(y, None)?;
704
                let down = self.descendants(&x)?;
705
                let up = self.ancestors(&y)?;
706
                Ok(down.intersection(&up).copied().collect())
707
            }
708
            Expr::Range(x, y) => {
709
                let x = self.eval(x, None)?;
710
                let y = self.eval(y, None)?;
711
                let from = self.ancestors(&x)?;
712
                let to = self.ancestors(&y)?;
713
                Ok(to.difference(&from).copied().collect())
714
            }
715
            Expr::Union(a, b) => {
716
                let mut a = self.eval(a, within)?;
717
                a.extend(self.eval(b, within)?);
718
                Ok(a)
719
            }
720
            Expr::Intersection(a, b) => {
721
                let (first, second) = if Self::is_predicate(a) && !Self::is_predicate(b) {
722
                    (b, a)
723
                } else {
724
                    (a, b)
725
                };
726
                let left = self.eval(first, within)?;
727
                let right = self.eval(second, Some(&left))?;
728
                Ok(left.intersection(&right).copied().collect())
729
            }
730
            Expr::Difference(a, b) => {
731
                let left = self.eval(a, within)?;
732
                let right = self.eval(b, Some(&left))?;
733
                Ok(left.difference(&right).copied().collect())
734
            }
735
            Expr::Call(name, args) => self.call(name, args, within),
736
        }
737
    }
738
739
    fn sort_newest_first(&self, hashes: &mut [ChangeHash]) {
740
        hashes.sort_by(|a, b| {
741
            let (ma, mb) = (self.graph.get(a), self.graph.get(b));
742
            mb.map(|m| m.hlc).cmp(&ma.map(|m| m.hlc)).then(b.cmp(a))
743
        });
744
    }
745
}
746
747
impl Repo {
748
    /// Evaluate a revset within [`REVSET_BUDGET`].
749
    pub fn revset(&self, src: &str) -> Result<Revset> {
750
        self.revset_with_budget(src, REVSET_BUDGET)
751
    }
752
753
    /// Evaluate a revset: the changes it selects, newest first, with
754
    /// their metadata. Read-only. Fails past `budget`.
755
    pub fn revset_with_budget(&self, src: &str, budget: Duration) -> Result<Revset> {
756
        let expr = revset::parse(src).map_err(|e| err(format!("revset {src:?}: {e}")))?;
757
        let mut ev = Eval {
758
            repo: self,
759
            graph: HashMap::new(),
760
            loaded: HashSet::new(),
761
            all_loaded: false,
762
            dependents: None,
763
            names: HashMap::new(),
764
            auth: HashMap::new(),
765
            deadline: Instant::now() + budget,
766
            budget,
767
            now_ms: Hlc::now().wall_ms,
768
            depth: 0,
769
        };
770
        let set = ev.eval(&expr, None)?;
771
        let mut hashes: Vec<ChangeHash> = set.into_iter().collect();
772
        ev.sort_newest_first(&mut hashes);
773
        let metas = hashes
774
            .iter()
775
            .filter_map(|h| ev.graph.get(h).map(|m| (*h, m.clone())))
776
            .collect();
777
        Ok(Revset { hashes, metas })
778
    }
779
780
    /// The log entries a revset selects, newest first. A head of the
781
    /// current bookmark is marked as in `log`.
782
    pub fn log_revset(&self, src: &str) -> Result<Vec<LogEntry>> {
783
        let r = self.revset(src)?;
784
        let heads: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
785
        let wc = if self.is_bare() {
786
            None
787
        } else {
788
            self.working_copy().ok().map(|(h, _)| h)
789
        };
790
        let mut entries: Vec<LogEntry> = r
791
            .hashes
792
            .iter()
793
            .filter_map(|h| {
794
                r.metas.get(h).map(|m| LogEntry {
795
                    hash: *h,
796
                    change: m.clone(),
797
                    is_working_copy: Some(*h) == wc,
798
                    is_head: heads.contains(h),
799
                })
800
            })
801
            .collect();
802
        // The working copy first, as `log` shows it.
803
        entries.sort_by_key(|e| !e.is_working_copy);
804
        Ok(entries)
805
    }
806
}