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