OXYGENHUB
# 614f55e14eee oxygen / crates / oxy-core / src / repo / revset.rs
26.4 KiB · Rust · last changed Revsets: trust predicates, and -r on show, verify and abandon 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
            "latest" => {
372
                self.arity(name, args, 2)?;
373
                let x = self.eval(&args[0], None)?;
374
                let n: usize = self
375
                    .text_arg(name, args, 1)?
376
                    .parse()
377
                    .map_err(|_| err("latest(X, n) takes a count"))?;
378
                let mut members: Vec<ChangeHash> = x.into_iter().collect();
379
                self.sort_newest_first(&mut members);
380
                Ok(members.into_iter().take(n).collect())
381
            }
382
            "author" => {
383
                self.arity(name, args, 1)?;
384
                let who = self.text_arg(name, args, 0)?.to_string();
385
                let mut matches: HashMap<KeyId, bool> = HashMap::new();
386
                self.filter_metas_with(within, |ev, _, m| {
387
                    if let Some(hit) = matches.get(&m.author) {
388
                        return *hit;
389
                    }
390
                    let hit = ev.names_key(&who, &m.author);
391
                    matches.insert(m.author, hit);
392
                    hit
393
                })
394
            }
395
            "description" => {
396
                self.arity(name, args, 1)?;
397
                let text = self.text_arg(name, args, 0)?.to_string();
398
                if text.starts_with("re:") {
399
                    return Err(err(
400
                        "description(re:…) is not supported yet; give a substring",
401
                    ));
402
                }
403
                let needle = text.to_lowercase();
404
                self.filter_metas(within, |_, m| m.message.to_lowercase().contains(&needle))
405
            }
406
            "date" => {
407
                self.arity(name, args, 1)?;
408
                let range = revset::parse_date_range(self.text_arg(name, args, 0)?, self.now_ms)
409
                    .map_err(err)?;
410
                self.filter_metas(within, |_, m| range.contains(m.hlc.wall_ms))
411
            }
412
            "kind" => {
413
                self.arity(name, args, 1)?;
414
                let kind = match self.text_arg(name, args, 0)? {
415
                    "normal" => ChangeKind::Normal,
416
                    "resolution" => ChangeKind::Resolution,
417
                    "working-copy" | "working_copy" => ChangeKind::WorkingCopy,
418
                    other => {
419
                        return Err(err(format!(
420
                            "kind({other:?}): use normal, resolution or working-copy"
421
                        )))
422
                    }
423
                };
424
                self.filter_metas(within, |_, m| m.kind == kind)
425
            }
426
            "touches" => {
427
                self.arity(name, args, 1)?;
428
                let glob = self.text_arg(name, args, 0)?.to_string();
429
                self.touches(within, &glob)
430
            }
431
            // Trust (§2.4): what authenticated a change, and what vouched
432
            // for the states it is in.
433
            "signed_by" => {
434
                self.arity(name, args, 1)?;
435
                let who = self.text_arg(name, args, 0)?.to_string();
436
                self.filter_metas_with(within, |ev, h, m| match ev.auth(h, m) {
437
                    SignatureStatus::Valid { key, .. } => ev.names_key(&who, &key),
438
                    _ => false,
439
                })
440
            }
441
            "delegated" => {
442
                self.arity(name, args, 0)?;
443
                self.filter_metas_with(within, |ev, h, m| {
444
                    !m.author.is_zero()
445
                        && matches!(ev.auth(h, m), SignatureStatus::Valid { key, .. } if key != m.author)
446
                })
447
            }
448
            "unsigned" => {
449
                self.arity(name, args, 0)?;
450
                self.filter_metas_with(within, |ev, h, m| {
451
                    m.kind != ChangeKind::WorkingCopy
452
                        && !matches!(ev.auth(h, m), SignatureStatus::Valid { .. })
453
                })
454
            }
455
            "revoked" => {
456
                self.arity(name, args, 0)?;
457
                self.filter_metas_with(within, |ev, h, m| {
458
                    matches!(ev.auth(h, m), SignatureStatus::Valid { revoked: true, .. })
459
                })
460
            }
461
            "attested" => {
462
                self.arity(name, args, 1)?;
463
                let kind = self.text_arg(name, args, 0)?.to_string();
464
                self.attested(within, &kind)
465
            }
466
            "built" => {
467
                self.arity(name, args, 1)?;
468
                let job = self.text_arg(name, args, 0)?.to_string();
469
                self.built(within, &job)
470
            }
471
            other => {
472
                // A saved revset: `oxy config revset.NAME 'EXPR'` makes NAME().
473
                if let Some(saved) = self.repo.config.revsets.get(other).cloned() {
474
                    self.arity(name, args, 0)?;
475
                    if self.depth >= 16 {
476
                        return Err(err(format!("revset.{other} refers to itself")));
477
                    }
478
                    let e = revset::parse(&saved)
479
                        .map_err(|e| err(format!("revset.{other} = {saved:?}: {e}")))?;
480
                    self.depth += 1;
481
                    let r = self.eval(&e, within);
482
                    self.depth -= 1;
483
                    return r;
484
                }
485
                Err(err(format!(
486
                    "unknown function {other}(); see docs/revset_query_language.md"
487
                )))
488
            }
489
        }
490
    }
491
492
    /// The authentication of a change: its signature or seal, checked once.
493
    fn auth(&mut self, h: &ChangeHash, m: &ChangeMeta) -> SignatureStatus {
494
        if let Some(s) = self.auth.get(h) {
495
            return s.clone();
496
        }
497
        let s = self
498
            .repo
499
            .authenticate_change_known(h, Some(m))
500
            .unwrap_or_else(|e| SignatureStatus::Invalid(e.to_string()));
501
        self.auth.insert(*h, s.clone());
502
        s
503
    }
504
505
    /// Whether `who` names key `key`: by hex prefix, `me`, or the name or
506
    /// email of its identity.
507
    fn names_key(&mut self, who: &str, key: &KeyId) -> bool {
508
        (who == "me" && Some(*key) == self.repo.config.author_key)
509
            || key.starts_with_hex(who)
510
            || self.who(key).is_some_and(|(n, e)| {
511
                let needle = who.to_lowercase();
512
                n.to_lowercase().contains(&needle) || e.to_lowercase().contains(&needle)
513
            })
514
    }
515
516
    /// The closure of the states whose heads these are, within `within`.
517
    fn closure_of(&mut self, mut heads: Vec<ChangeHash>, within: Option<&Set>) -> Result<Set> {
518
        heads.sort();
519
        heads.dedup();
520
        self.ensure(&heads)?;
521
        let set: Set = heads.into_iter().collect();
522
        let closure = self.ancestors(&set)?;
523
        Ok(match within {
524
            Some(w) => closure.intersection(w).copied().collect(),
525
            None => closure,
526
        })
527
    }
528
529
    /// The closure of every state that carries an attestation of `kind`:
530
    /// `tag` (tagged states), `receipt` (states a runner reported on) or
531
    /// `ref` (states a remote attested, as its tracking bookmarks hold).
532
    fn attested(&mut self, within: Option<&Set>, kind: &str) -> Result<Set> {
533
        let mut heads: Vec<ChangeHash> = Vec::new();
534
        match kind {
535
            "tag" => {
536
                for t in self.repo.tags()? {
537
                    heads.extend(t.heads);
538
                }
539
            }
540
            "receipt" => {
541
                for st in self.repo.store().receipt_states()? {
542
                    if let Ok(s) = self.repo.store().get_state(&st) {
543
                        heads.extend(s.heads);
544
                    }
545
                }
546
            }
547
            "ref" => {
548
                let view = self.repo.view()?;
549
                for bookmarks in view.remotes.values() {
550
                    for st in bookmarks.values() {
551
                        heads.extend(self.repo.store().get_state(st)?.heads);
552
                    }
553
                }
554
            }
555
            other => return Err(err(format!("attested({other:?}): use tag, receipt or ref"))),
556
        }
557
        self.closure_of(heads, within)
558
    }
559
560
    /// The closure of every state with a valid receipt for Flow job `job`
561
    /// from a runner whose key is not revoked.
562
    fn built(&mut self, within: Option<&Set>, job: &str) -> Result<Set> {
563
        let mut heads: Vec<ChangeHash> = Vec::new();
564
        for st in self.repo.store().receipt_states()? {
565
            let Ok(state) = self.repo.store().get_state(&st) else {
566
                continue;
567
            };
568
            let good = self
569
                .repo
570
                .receipts(&state.heads)?
571
                .into_iter()
572
                .any(|r| r.signed.receipt.job_name == job && r.problem.is_none() && !r.revoked);
573
            if good {
574
                heads.extend(state.heads);
575
            }
576
            self.tick()?;
577
        }
578
        self.closure_of(heads, within)
579
    }
580
581
    /// `filter_metas` for a test that needs the evaluator (identity lookups).
582
    fn filter_metas_with(
583
        &mut self,
584
        within: Option<&Set>,
585
        mut keep: impl FnMut(&mut Eval<'a>, &ChangeHash, &ChangeMeta) -> bool,
586
    ) -> Result<Set> {
587
        let candidates = self.universe(within)?;
588
        let mut out = Set::new();
589
        for (i, h) in candidates.iter().enumerate() {
590
            if let Some(m) = self.graph.get(h).cloned() {
591
                if keep(self, h, &m) {
592
                    out.insert(*h);
593
                }
594
            }
595
            if i % 8192 == 8191 {
596
                self.tick()?;
597
            }
598
        }
599
        Ok(out)
600
    }
601
602
    /// Whether an expression selects by a property, so that evaluating it
603
    /// within the other side of an intersection saves scanning everything.
604
    fn is_predicate(e: &Expr) -> bool {
605
        match e {
606
            Expr::Call(name, _) => matches!(
607
                name.as_str(),
608
                "author"
609
                    | "description"
610
                    | "date"
611
                    | "kind"
612
                    | "touches"
613
                    | "all"
614
                    | "signed_by"
615
                    | "delegated"
616
                    | "unsigned"
617
                    | "revoked"
618
                    | "attested"
619
                    | "built"
620
            ),
621
            Expr::Intersection(a, b) => Self::is_predicate(a) || Self::is_predicate(b),
622
            Expr::Union(a, b) => Self::is_predicate(a) && Self::is_predicate(b),
623
            Expr::Difference(a, _) => Self::is_predicate(a),
624
            _ => false,
625
        }
626
    }
627
628
    fn eval(&mut self, e: &Expr, within: Option<&Set>) -> Result<Set> {
629
        self.tick()?;
630
        match e {
631
            Expr::Symbol(s) => self.symbol(s),
632
            Expr::Ancestors(x) => {
633
                let x = self.eval(x, None)?;
634
                self.ancestors(&x)
635
            }
636
            Expr::Descendants(x) => {
637
                let x = self.eval(x, None)?;
638
                self.descendants(&x)
639
            }
640
            Expr::Between(x, y) => {
641
                let x = self.eval(x, None)?;
642
                let y = self.eval(y, None)?;
643
                let down = self.descendants(&x)?;
644
                let up = self.ancestors(&y)?;
645
                Ok(down.intersection(&up).copied().collect())
646
            }
647
            Expr::Range(x, y) => {
648
                let x = self.eval(x, None)?;
649
                let y = self.eval(y, None)?;
650
                let from = self.ancestors(&x)?;
651
                let to = self.ancestors(&y)?;
652
                Ok(to.difference(&from).copied().collect())
653
            }
654
            Expr::Union(a, b) => {
655
                let mut a = self.eval(a, within)?;
656
                a.extend(self.eval(b, within)?);
657
                Ok(a)
658
            }
659
            Expr::Intersection(a, b) => {
660
                let (first, second) = if Self::is_predicate(a) && !Self::is_predicate(b) {
661
                    (b, a)
662
                } else {
663
                    (a, b)
664
                };
665
                let left = self.eval(first, within)?;
666
                let right = self.eval(second, Some(&left))?;
667
                Ok(left.intersection(&right).copied().collect())
668
            }
669
            Expr::Difference(a, b) => {
670
                let left = self.eval(a, within)?;
671
                let right = self.eval(b, Some(&left))?;
672
                Ok(left.difference(&right).copied().collect())
673
            }
674
            Expr::Call(name, args) => self.call(name, args, within),
675
        }
676
    }
677
678
    fn sort_newest_first(&self, hashes: &mut [ChangeHash]) {
679
        hashes.sort_by(|a, b| {
680
            let (ma, mb) = (self.graph.get(a), self.graph.get(b));
681
            mb.map(|m| m.hlc).cmp(&ma.map(|m| m.hlc)).then(b.cmp(a))
682
        });
683
    }
684
}
685
686
impl Repo {
687
    /// Evaluate a revset within [`REVSET_BUDGET`].
688
    pub fn revset(&self, src: &str) -> Result<Revset> {
689
        self.revset_with_budget(src, REVSET_BUDGET)
690
    }
691
692
    /// Evaluate a revset: the changes it selects, newest first, with
693
    /// their metadata. Read-only. Fails past `budget`.
694
    pub fn revset_with_budget(&self, src: &str, budget: Duration) -> Result<Revset> {
695
        let expr = revset::parse(src).map_err(|e| err(format!("revset {src:?}: {e}")))?;
696
        let mut ev = Eval {
697
            repo: self,
698
            graph: HashMap::new(),
699
            loaded: HashSet::new(),
700
            all_loaded: false,
701
            dependents: None,
702
            names: HashMap::new(),
703
            auth: HashMap::new(),
704
            deadline: Instant::now() + budget,
705
            budget,
706
            now_ms: Hlc::now().wall_ms,
707
            depth: 0,
708
        };
709
        let set = ev.eval(&expr, None)?;
710
        let mut hashes: Vec<ChangeHash> = set.into_iter().collect();
711
        ev.sort_newest_first(&mut hashes);
712
        let metas = hashes
713
            .iter()
714
            .filter_map(|h| ev.graph.get(h).map(|m| (*h, m.clone())))
715
            .collect();
716
        Ok(Revset { hashes, metas })
717
    }
718
719
    /// The log entries a revset selects, newest first. A head of the
720
    /// current bookmark is marked as in `log`.
721
    pub fn log_revset(&self, src: &str) -> Result<Vec<LogEntry>> {
722
        let r = self.revset(src)?;
723
        let heads: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
724
        let wc = if self.is_bare() {
725
            None
726
        } else {
727
            self.working_copy().ok().map(|(h, _)| h)
728
        };
729
        let mut entries: Vec<LogEntry> = r
730
            .hashes
731
            .iter()
732
            .filter_map(|h| {
733
                r.metas.get(h).map(|m| LogEntry {
734
                    hash: *h,
735
                    change: m.clone(),
736
                    is_working_copy: Some(*h) == wc,
737
                    is_head: heads.contains(h),
738
                })
739
            })
740
            .collect();
741
        // The working copy first, as `log` shows it.
742
        entries.sort_by_key(|e| !e.is_working_copy);
743
        Ok(entries)
744
    }
745
}