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