OXYGENHUB

Coverage / crates/oxy-core/src/repo/revset.rs 89.6%

592 of 661 lines run, 66 of 146 functions · run #342 on proposal/125 · run missed

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
445×
fn err(msg: impl Into<String>) -> RepoError {
455×
    RepoError::Msg(msg.into())
465×
}
47
48
impl<'a> Eval<'a> {
49224×
    fn tick(&self) -> Result<()> {
50224×
        if Instant::now() > self.deadline {
511×
            return Err(err(format!(
521×
                "the revset went past its budget of {:.0} s; narrow it with a range such as main.. or a date()",
531×
                self.budget.as_secs_f64()
541×
            )));
55223×
        }
56223×
        Ok(())
57224×
    }
58
59
    /// Load the closure of `heads` into the graph.
6083×
    fn ensure(&mut self, heads: &[ChangeHash]) -> Result<()> {
6183×
        let fresh: Vec<ChangeHash> = heads
6283×
            .iter()
6383×
            .copied()
64211×
            .filter(|h| !self.loaded.contains(h))
6583×
            .collect();
6683×
        if fresh.is_empty() {
679×
            return Ok(());
6874×
        }
69284×
        for (h, m) in self.repo.metas_of(&fresh)? {
70284×
            self.graph.insert(h, m);
71284×
        }
7274×
        self.loaded.extend(fresh);
7374×
        self.dependents = None;
7474×
        self.tick()
7583×
    }
76
77
    /// Load every change the repository names: bookmarks, remote
78
    /// bookmarks, tags, and the working copy.
7925×
    fn load_all(&mut self) -> Result<()> {
8025×
        if self.all_loaded {
810×
            return Ok(());
8225×
        }
8325×
        let view = self.repo.view()?;
8425×
        let mut heads: Vec<ChangeHash> = Vec::new();
8525×
        for st in view.bookmarks.values() {
8625×
            heads.extend(self.repo.store().get_state(st)?.heads);
87
        }
8825×
        for bookmarks in view.remotes.values() {
891×
            for st in bookmarks.values() {
901×
                heads.extend(self.repo.store().get_state(st)?.heads);
91
            }
92
        }
9325×
        for st in view.tags.values() {
944×
            heads.extend(self.repo.store().get_state(st)?.heads);
95
        }
9625×
        if let Some(wc) = self.working_copy() {
9725×
            heads.push(wc);
9825×
        }
9925×
        heads.sort();
10025×
        heads.dedup();
10125×
        self.ensure(&heads)?;
10225×
        self.all_loaded = true;
10325×
        Ok(())
10425×
    }
105
10638×
    fn working_copy(&self) -> Option<ChangeHash> {
10738×
        if self.repo.is_bare() {
1080×
            None
109
        } else {
11038×
            self.repo.working_copy().ok().map(|(h, _)| h)
111
        }
11238×
    }
113
11419×
    fn all(&mut self) -> Result<Set> {
11519×
        self.load_all()?;
11619×
        Ok(self.graph.keys().copied().collect())
11719×
    }
118
1196×
    fn dependents_map(&mut self) -> Result<&HashMap<ChangeHash, Vec<ChangeHash>>> {
1206×
        self.load_all()?;
1216×
        if self.dependents.is_none() {
1226×
            let mut map: HashMap<ChangeHash, Vec<ChangeHash>> = HashMap::new();
12330×
            for (h, m) in &self.graph {
12430×
                for d in &m.deps {
12530×
                    map.entry(*d).or_default().push(*h);
12630×
                }
127
            }
1286×
            self.dependents = Some(map);
1290×
        }
1306×
        Ok(self.dependents.as_ref().unwrap())
1316×
    }
132
133
    /// `::X`: the members and their dependency closures.
13435×
    fn ancestors(&mut self, set: &Set) -> Result<Set> {
13535×
        let mut out = set.clone();
13635×
        let mut stack: Vec<ChangeHash> = set.iter().copied().collect();
13735×
        let mut n = 0usize;
138149×
        while let Some(h) = stack.pop() {
139114×
            if let Some(m) = self.graph.get(&h) {
140114×
                for d in &m.deps {
14166×
                    if out.insert(*d) {
14238×
                        stack.push(*d);
14338×
                    }
144
                }
1450×
            }
146114×
            n += 1;
147114×
            if n.is_multiple_of(4096) {
1480×
                self.tick()?;
149114×
            }
150
        }
15135×
        Ok(out)
15235×
    }
153
154
    /// `X::`: the members and everything that transitively depends on them.
1554×
    fn descendants(&mut self, set: &Set) -> Result<Set> {
1564×
        let mut out = set.clone();
1574×
        let mut stack: Vec<ChangeHash> = set.iter().copied().collect();
1584×
        let deps = self.dependents_map()?;
15918×
        while let Some(h) = stack.pop() {
16014×
            if let Some(ds) = deps.get(&h) {
16113×
                for d in ds {
16213×
                    if out.insert(*d) {
16310×
                        stack.push(*d);
16410×
                    }
165
                }
1664×
            }
167
        }
1684×
        Ok(out)
1694×
    }
170
171
    /// Members no other member depends on, directly or through others.
1722×
    fn heads(&mut self, set: &Set) -> Result<Set> {
1732×
        let mut below: HashSet<ChangeHash> = HashSet::new();
1742×
        let mut stack: Vec<ChangeHash> = set
1752×
            .iter()
1767×
            .filter_map(|h| self.graph.get(h))
1777×
            .flat_map(|m| m.deps.iter().copied())
1782×
            .collect();
1795×
        while let Some(h) = stack.pop() {
1803×
            if below.insert(h) {
1812×
                if let Some(m) = self.graph.get(&h) {
1822×
                    stack.extend(m.deps.iter().copied());
1832×
                }
1841×
            }
185
        }
1867×
        Ok(set.iter().copied().filter(|h| !below.contains(h)).collect())
1872×
    }
188
189
    /// Members that depend on no other member, directly or through others.
1901×
    fn roots(&mut self, set: &Set) -> Result<Set> {
1911×
        let deps = self.dependents_map()?;
1921×
        let mut above: HashSet<ChangeHash> = HashSet::new();
1931×
        let mut stack: Vec<ChangeHash> = set
1941×
            .iter()
1954×
            .filter_map(|h| deps.get(h))
1964×
            .flat_map(|ds| ds.iter().copied())
1971×
            .collect();
1988×
        while let Some(h) = stack.pop() {
1997×
            if above.insert(h) {
2003×
                if let Some(ds) = deps.get(&h) {
2012×
                    stack.extend(ds.iter().copied());
2022×
                }
2034×
            }
204
        }
2054×
        Ok(set.iter().copied().filter(|h| !above.contains(h)).collect())
2061×
    }
207
20846×
    fn symbol(&mut self, name: &str) -> Result<Set> {
20946×
        if name == "@" {
2105×
            let Some(wc) = self.working_copy() else {
2110×
                return Err(err(
2120×
                    "@ names the working copy, and a bare repository has none",
2130×
                ));
214
            };
2155×
            self.ensure(&[wc])?;
2165×
            return Ok([wc].into_iter().collect());
21741×
        }
21841×
        let heads = self.repo.resolve_heads(name)?;
21940×
        self.ensure(&heads)?;
22040×
        Ok(heads.into_iter().collect())
22146×
    }
222
223
    /// The identity's name and email, if its object is known.
2245×
    fn who(&mut self, key: &KeyId) -> Option<(String, String)> {
2255×
        if let Some(w) = self.names.get(key) {
2260×
            return w.clone();
2275×
        }
2285×
        let w = self.repo.identity(key).ok().map(|id| (id.name, id.email));
2295×
        self.names.insert(*key, w.clone());
2305×
        w
2315×
    }
232
233
    /// The set a predicate ranges over: what it is intersected with when
234
    /// that is known, else everything.
23531×
    fn universe(&mut self, within: Option<&Set>) -> Result<Set> {
23631×
        match within {
23712×
            Some(s) => Ok(s.clone()),
23819×
            None => self.all(),
239
        }
24031×
    }
241
2425×
    fn filter_metas(
2435×
        &mut self,
2445×
        within: Option<&Set>,
2455×
        mut keep: impl FnMut(&ChangeHash, &ChangeMeta) -> bool,
2465×
    ) -> Result<Set> {
2475×
        let candidates = self.universe(within)?;
2485×
        let mut out = Set::new();
24924×
        for (i, h) in candidates.iter().enumerate() {
25024×
            if let Some(m) = self.graph.get(h) {
25124×
                if keep(h, m) {
2527×
                    out.insert(*h);
25317×
                }
2540×
            }
25524×
            if i % 8192 == 8191 {
2560×
                self.tick()?;
25724×
            }
258
        }
2595×
        Ok(out)
2605×
    }
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.
2655×
    fn touches(&mut self, within: Option<&Set>, glob: &str) -> Result<Set> {
2665×
        let matcher = globset::GlobBuilder::new(glob)
2675×
            .literal_separator(false)
2685×
            .build()
2695×
            .map_err(|e| err(format!("touches({glob:?}): {e}")))?
2705×
            .compile_matcher();
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.
2745×
        let mut state = match self.working_copy() {
2755×
            Some(wc) => {
2765×
                let deps = self
2775×
                    .graph
2785×
                    .get(&wc)
2795×
                    .map(|m| m.deps.clone())
2805×
                    .or_else(|| self.repo.working_copy().ok().map(|(_, c)| c.deps))
2815×
                    .unwrap_or_default();
2825×
                self.repo.load_state_indexed(&deps)?
283
            }
2840×
            None => self.repo.load_state_history(&self.repo.bookmark_heads()?)?,
285
        };
2865×
        let view = self.repo.tree_view(&mut state)?;
2875×
        let mut nodes: HashSet<NodeId> = view
2885×
            .entries
2895×
            .iter()
29038×
            .filter(|(path, _)| matcher.is_match(path))
2915×
            .map(|(_, e)| e.node)
2925×
            .collect();
293
        // A file shown as one of identical additions is all of them.
2945×
        for (dup, shown) in &view.unified {
2950×
            if nodes.contains(shown) {
2960×
                nodes.insert(*dup);
2970×
            }
298
        }
2995×
        if nodes.is_empty() {
3001×
            return Ok(Set::new());
3014×
        }
3024×
        let candidates = self.universe(within)?;
3034×
        let mut touched = self.repo.touched();
3044×
        touched.fill(self.repo, &candidates.iter().copied().collect::<Vec<_>>());
3054×
        let mut out = Set::new();
30618×
        for (i, h) in candidates.iter().enumerate() {
30718×
            if touched.touches(self.repo, h, &nodes) {
30810×
                out.insert(*h);
30910×
            }
31018×
            if i % 256 == 255 {
3110×
                self.tick()?;
31218×
            }
313
        }
3144×
        touched.save();
3154×
        Ok(out)
3165×
    }
317
31831×
    fn text_arg<'e>(&self, name: &str, args: &'e [Expr], i: usize) -> Result<&'e str> {
31931×
        match args.get(i) {
32031×
            Some(Expr::Symbol(s)) => Ok(s),
3210×
            _ => Err(err(format!("{name}() takes text, quoted if it has spaces"))),
322
        }
32331×
    }
324
32550×
    fn arity(&self, name: &str, args: &[Expr], n: usize) -> Result<()> {
32650×
        if args.len() != n {
3270×
            return Err(err(format!(
328
                "{name}() takes {n} argument{}, not {}",
3290×
                if n == 1 { "" } else { "s" },
3300×
                args.len()
331
            )));
33250×
        }
33350×
        Ok(())
33450×
    }
335
33655×
    fn call(&mut self, name: &str, args: &[Expr], within: Option<&Set>) -> Result<Set> {
33755×
        match name {
33855×
            "all" => {
3392×
                self.arity(name, args, 0)?;
3402×
                self.universe(within)
341
            }
34253×
            "none" => {
3431×
                self.arity(name, args, 0)?;
3441×
                Ok(Set::new())
345
            }
34652×
            "deps" => {
3471×
                self.arity(name, args, 1)?;
3481×
                let x = self.eval(&args[0], None)?;
3491×
                let mut out = Set::new();
3503×
                for h in &x {
3513×
                    if let Some(m) = self.graph.get(h) {
3523×
                        out.extend(m.deps.iter().copied());
3533×
                    }
354
                }
3551×
                Ok(out)
356
            }
35751×
            "dependents" => {
3581×
                self.arity(name, args, 1)?;
3591×
                let x = self.eval(&args[0], None)?;
3601×
                let deps = self.dependents_map()?;
3611×
                let mut out = Set::new();
3621×
                for h in &x {
3631×
                    if let Some(ds) = deps.get(h) {
3641×
                        out.extend(ds.iter().copied());
3651×
                    }
366
                }
3671×
                Ok(out)
368
            }
36950×
            "heads" => {
3702×
                self.arity(name, args, 1)?;
3712×
                let x = self.eval(&args[0], None)?;
3722×
                self.heads(&x)
373
            }
37448×
            "roots" => {
3751×
                self.arity(name, args, 1)?;
3761×
                let x = self.eval(&args[0], None)?;
3771×
                self.roots(&x)
378
            }
37947×
            "independent" => {
3802×
                self.arity(name, args, 2)?;
3812×
                let x = self.eval(&args[0], None)?;
3822×
                let inn = self.eval(&args[1], None)?;
3832×
                let below = self.ancestors(&x)?;
3842×
                let above = self.descendants(&x)?;
3852×
                Ok(inn
3862×
                    .into_iter()
3879×
                    .filter(|h| !below.contains(h) && !above.contains(h))
3882×
                    .collect())
389
            }
39045×
            "conflicts" => {
3914×
                if args.len() > 1 {
3920×
                    return Err(err(
3930×
                        "conflicts() takes a state, or nothing for the working copy's",
3940×
                    ));
3954×
                }
3964×
                let heads: Vec<ChangeHash> = match args.first() {
3971×
                    Some(e) => self.eval(e, None)?.into_iter().collect(),
3983×
                    None => match self.working_copy() {
3993×
                        Some(wc) => {
4003×
                            self.ensure(&[wc])?;
4013×
                            self.graph
4023×
                                .get(&wc)
4033×
                                .map(|m| m.deps.clone())
4043×
                                .unwrap_or_default()
405
                        }
4060×
                        None => self.repo.bookmark_heads()?,
407
                    },
408
                };
4094×
                self.conflicts(within, &heads)
410
            }
41141×
            "latest" => {
4121×
                self.arity(name, args, 2)?;
4131×
                let x = self.eval(&args[0], None)?;
4141×
                let n: usize = self
4151×
                    .text_arg(name, args, 1)?
4161×
                    .parse()
4171×
                    .map_err(|_| err("latest(X, n) takes a count"))?;
4181×
                let mut members: Vec<ChangeHash> = x.into_iter().collect();
4191×
                self.sort_newest_first(&mut members);
4201×
                Ok(members.into_iter().take(n).collect())
421
            }
42240×
            "author" => {
4237×
                self.arity(name, args, 1)?;
4247×
                let who = self.text_arg(name, args, 0)?.to_string();
4257×
                let mut matches: HashMap<KeyId, bool> = HashMap::new();
42627×
                self.filter_metas_with(within, |ev, _, m| {
42727×
                    if let Some(hit) = matches.get(&m.author) {
42820×
                        return *hit;
4297×
                    }
4307×
                    let hit = ev.names_key(&who, &m.author);
4317×
                    matches.insert(m.author, hit);
4327×
                    hit
43327×
                })
434
            }
43533×
            "description" => {
4362×
                self.arity(name, args, 1)?;
4372×
                let text = self.text_arg(name, args, 0)?.to_string();
4382×
                if text.starts_with("re:") {
4390×
                    return Err(err(
4400×
                        "description(re:…) is not supported yet; give a substring",
4410×
                    ));
4422×
                }
4432×
                let needle = text.to_lowercase();
44410×
                self.filter_metas(within, |_, m| m.message.to_lowercase().contains(&needle))
445
            }
44631×
            "date" => {
4472×
                self.arity(name, args, 1)?;
4482×
                let range = revset::parse_date_range(self.text_arg(name, args, 0)?, self.now_ms)
4492×
                    .map_err(err)?;
4509×
                self.filter_metas(within, |_, m| range.contains(m.hlc.wall_ms))
451
            }
45229×
            "kind" => {
4531×
                self.arity(name, args, 1)?;
4541×
                let kind = match self.text_arg(name, args, 0)? {
4551×
                    "normal" => ChangeKind::Normal,
4561×
                    "resolution" => ChangeKind::Resolution,
4571×
                    "working-copy" | "working_copy" => ChangeKind::WorkingCopy,
4580×
                    other => {
4590×
                        return Err(err(format!(
4600×
                            "kind({other:?}): use normal, resolution or working-copy"
4610×
                        )))
462
                    }
463
                };
4645×
                self.filter_metas(within, |_, m| m.kind == kind)
465
            }
46628×
            "touches" => {
4675×
                self.arity(name, args, 1)?;
4685×
                let glob = self.text_arg(name, args, 0)?.to_string();
4695×
                self.touches(within, &glob)
470
            }
471
            // Trust (§2.4): what authenticated a change, and what vouched
472
            // for the states it is in.
47323×
            "signed_by" => {
4745×
                self.arity(name, args, 1)?;
4755×
                let who = self.text_arg(name, args, 0)?.to_string();
47625×
                self.filter_metas_with(within, |ev, h, m| match ev.auth(h, m) {
4774×
                    SignatureStatus::Valid { key, .. } => ev.names_key(&who, &key),
47821×
                    _ => false,
47925×
                })
480
            }
48118×
            "delegated" => {
4822×
                self.arity(name, args, 0)?;
4838×
                self.filter_metas_with(within, |ev, h, m| {
4848×
                    !m.author.is_zero()
4858×
                        && matches!(ev.auth(h, m), SignatureStatus::Valid { key, .. } if key != m.author)
4868×
                })
487
            }
48816×
            "unsigned" => {
4893×
                self.arity(name, args, 0)?;
49010×
                self.filter_metas_with(within, |ev, h, m| {
49110×
                    m.kind != ChangeKind::WorkingCopy
49210×
                        && !matches!(ev.auth(h, m), SignatureStatus::Valid { .. })
49310×
                })
494
            }
49513×
            "revoked" => {
4963×
                self.arity(name, args, 0)?;
49711×
                self.filter_metas_with(within, |ev, h, m| {
49811×
                    matches!(ev.auth(h, m), SignatureStatus::Valid { revoked: true, .. })
49911×
                })
500
            }
50110×
            "attested" => {
5025×
                self.arity(name, args, 1)?;
5035×
                let kind = self.text_arg(name, args, 0)?.to_string();
5045×
                self.attested(within, &kind)
505
            }
506
            // A bookmark's heads by name: what a bare bookmark symbol means,
507
            // without falling through to tags and change prefixes.
5085×
            "bookmark" => {
5092×
                self.arity(name, args, 1)?;
5102×
                let b = self.text_arg(name, args, 0)?;
5112×
                let view = self.repo.view()?;
5122×
                let st = match view.bookmarks.get(b) {
5131×
                    Some(st) => *st,
5141×
                    None => match remote_bookmark(&view, b) {
5150×
                        Some((_, _, st)) => st,
5161×
                        None => return Err(err(format!("bookmark({b}): no such bookmark"))),
517
                    },
518
                };
5191×
                let heads = self.repo.store().get_state(&st)?.heads;
5201×
                self.ensure(&heads)?;
5211×
                Ok(heads.into_iter().collect())
522
            }
5233×
            "built" => {
5241×
                self.arity(name, args, 1)?;
5251×
                let job = self.text_arg(name, args, 0)?.to_string();
5261×
                self.built(within, &job)
527
            }
5282×
            other => {
529
                // A saved revset: `oxy config revset.NAME 'EXPR'` makes NAME().
5302×
                if let Some(saved) = self.repo.config.revsets.get(other).cloned() {
5311×
                    self.arity(name, args, 0)?;
5321×
                    if self.depth >= 16 {
5330×
                        return Err(err(format!("revset.{other} refers to itself")));
5341×
                    }
5351×
                    let e = revset::parse(&saved)
5361×
                        .map_err(|e| err(format!("revset.{other} = {saved:?}: {e}")))?;
5371×
                    self.depth += 1;
5381×
                    let r = self.eval(&e, within);
5391×
                    self.depth -= 1;
5401×
                    return r;
5411×
                }
5421×
                Err(err(format!(
5431×
                    "unknown function {other}(); see docs/revset_query_language.md"
5441×
                )))
545
            }
546
        }
54755×
    }
548
549
    /// The authentication of a change: its signature or seal, checked once.
55054×
    fn auth(&mut self, h: &ChangeHash, m: &ChangeMeta) -> SignatureStatus {
55154×
        if let Some(s) = self.auth.get(h) {
5521×
            return s.clone();
55353×
        }
55453×
        let s = self
55553×
            .repo
55653×
            .authenticate_change_known(h, Some(m))
55753×
            .unwrap_or_else(|e| SignatureStatus::Invalid(e.to_string()));
55853×
        self.auth.insert(*h, s.clone());
55953×
        s
56054×
    }
561
562
    /// Whether `who` names key `key`: by hex prefix, `me`, or the name or
563
    /// email of its identity.
56411×
    fn names_key(&mut self, who: &str, key: &KeyId) -> bool {
56511×
        (who == "me" && Some(*key) == self.repo.config.author_key)
5667×
            || key.starts_with_hex(who)
5675×
            || self.who(key).is_some_and(|(n, e)| {
5685×
                let needle = who.to_lowercase();
5695×
                n.to_lowercase().contains(&needle) || e.to_lowercase().contains(&needle)
5705×
            })
57111×
    }
572
573
    /// The closure of the states whose heads these are, within `within`.
5745×
    fn closure_of(&mut self, mut heads: Vec<ChangeHash>, within: Option<&Set>) -> Result<Set> {
5755×
        heads.sort();
5765×
        heads.dedup();
5775×
        self.ensure(&heads)?;
5785×
        let set: Set = heads.into_iter().collect();
5795×
        let closure = self.ancestors(&set)?;
5805×
        Ok(match within {
5810×
            Some(w) => closure.intersection(w).copied().collect(),
5825×
            None => closure,
583
        })
5845×
    }
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).
5895×
    fn attested(&mut self, within: Option<&Set>, kind: &str) -> Result<Set> {
5905×
        let mut heads: Vec<ChangeHash> = Vec::new();
5915×
        match kind {
5925×
            "tag" => {
5933×
                for t in self.repo.tags()? {
5942×
                    heads.extend(t.heads);
5952×
                }
596
            }
5972×
            "receipt" => {
5981×
                for st in self.repo.store().receipt_states()? {
5990×
                    if let Ok(s) = self.repo.store().get_state(&st) {
6000×
                        heads.extend(s.heads);
6010×
                    }
602
                }
603
            }
6041×
            "ref" => {
6050×
                let view = self.repo.view()?;
6060×
                for bookmarks in view.remotes.values() {
6070×
                    for st in bookmarks.values() {
6080×
                        heads.extend(self.repo.store().get_state(st)?.heads);
609
                    }
610
                }
611
            }
6121×
            other => return Err(err(format!("attested({other:?}): use tag, receipt or ref"))),
613
        }
6144×
        self.closure_of(heads, within)
6155×
    }
616
617
    /// The closure of every state with a valid receipt for Flow job `job`
618
    /// from a runner whose key is not revoked.
6191×
    fn built(&mut self, within: Option<&Set>, job: &str) -> Result<Set> {
6201×
        let mut heads: Vec<ChangeHash> = Vec::new();
6211×
        for st in self.repo.store().receipt_states()? {
6220×
            let Ok(state) = self.repo.store().get_state(&st) else {
6230×
                continue;
624
            };
6250×
            let good = self
6260×
                .repo
6270×
                .receipts(&state.heads)?
6280×
                .into_iter()
6290×
                .any(|r| r.signed.receipt.job_name == job && r.problem.is_none() && !r.revoked);
6300×
            if good {
6310×
                heads.extend(state.heads);
6320×
            }
6330×
            self.tick()?;
634
        }
6351×
        self.closure_of(heads, within)
6361×
    }
637
638
    /// `conflicts(S)`: the changes that contributed atoms to a conflict in
639
    /// the state `heads` name (conflicts belong to states, not changes).
6404×
    fn conflicts(&mut self, within: Option<&Set>, heads: &[ChangeHash]) -> Result<Set> {
6414×
        let state = self.repo.load_state(heads)?;
6424×
        let snapshot = state.materialize();
6434×
        let mut out = Set::new();
64436×
        for f in snapshot.files.values() {
64536×
            if !f.is_conflicted() {
64634×
                continue;
6472×
            }
6482×
            match &f.content {
6492×
                crate::state::FileContent::Text { .. } => {
6502×
                    out.extend(state.conflict_regions(&f.node).contributors);
6512×
                }
6520×
                crate::state::FileContent::Opaque { blobs } => {
6530×
                    out.extend(state.blob_contributors(&f.node, blobs));
6540×
                }
6550×
                crate::state::FileContent::Dir => {}
656
            }
6572×
            self.tick()?;
658
        }
6594×
        self.ensure(heads)?;
6604×
        Ok(match within {
6610×
            Some(w) => out.intersection(w).copied().collect(),
6624×
            None => out,
663
        })
6644×
    }
665
666
    /// `filter_metas` for a test that needs the evaluator (identity lookups).
66720×
    fn filter_metas_with(
66820×
        &mut self,
66920×
        within: Option<&Set>,
67020×
        mut keep: impl FnMut(&mut Eval<'a>, &ChangeHash, &ChangeMeta) -> bool,
67120×
    ) -> Result<Set> {
67220×
        let candidates = self.universe(within)?;
67320×
        let mut out = Set::new();
67481×
        for (i, h) in candidates.iter().enumerate() {
67581×
            if let Some(m) = self.graph.get(h).cloned() {
67681×
                if keep(self, h, &m) {
67736×
                    out.insert(*h);
67845×
                }
6790×
            }
68081×
            if i % 8192 == 8191 {
6810×
                self.tick()?;
68281×
            }
683
        }
68420×
        Ok(out)
68520×
    }
686
687
    /// Whether an expression selects by a property, so that evaluating it
688
    /// within the other side of an intersection saves scanning everything.
68923×
    fn is_predicate(e: &Expr) -> bool {
69023×
        match e {
69113×
            Expr::Call(name, _) => matches!(
69213×
                name.as_str(),
69313×
                "author"
6947×
                    | "description"
6957×
                    | "date"
6966×
                    | "kind"
6976×
                    | "touches"
6985×
                    | "all"
6995×
                    | "signed_by"
7005×
                    | "delegated"
7015×
                    | "unsigned"
7022×
                    | "revoked"
7032×
                    | "attested"
7041×
                    | "built"
7051×
                    | "conflicts"
706
            ),
7070×
            Expr::Intersection(a, b) => Self::is_predicate(a) || Self::is_predicate(b),
7080×
            Expr::Union(a, b) => Self::is_predicate(a) && Self::is_predicate(b),
7090×
            Expr::Difference(a, _) => Self::is_predicate(a),
71010×
            _ => false,
711
        }
71223×
    }
713
714148×
    fn eval(&mut self, e: &Expr, within: Option<&Set>) -> Result<Set> {
715148×
        self.tick()?;
716147×
        match e {
71746×
            Expr::Symbol(s) => self.symbol(s),
71823×
            Expr::Ancestors(x) => {
71923×
                let x = self.eval(x, None)?;
72023×
                self.ancestors(&x)
721
            }
7221×
            Expr::Descendants(x) => {
7231×
                let x = self.eval(x, None)?;
7241×
                self.descendants(&x)
725
            }
7261×
            Expr::Between(x, y) => {
7271×
                let x = self.eval(x, None)?;
7281×
                let y = self.eval(y, None)?;
7291×
                let down = self.descendants(&x)?;
7301×
                let up = self.ancestors(&y)?;
7311×
                Ok(down.intersection(&up).copied().collect())
732
            }
7332×
            Expr::Range(x, y) => {
7342×
                let x = self.eval(x, None)?;
7352×
                let y = self.eval(y, None)?;
7362×
                let from = self.ancestors(&x)?;
7372×
                let to = self.ancestors(&y)?;
7382×
                Ok(to.difference(&from).copied().collect())
739
            }
7403×
            Expr::Union(a, b) => {
7413×
                let mut a = self.eval(a, within)?;
7423×
                a.extend(self.eval(b, within)?);
7433×
                Ok(a)
744
            }
74512×
            Expr::Intersection(a, b) => {
74612×
                let (first, second) = if Self::is_predicate(a) && !Self::is_predicate(b) {
7479×
                    (b, a)
748
                } else {
7493×
                    (a, b)
750
                };
75112×
                let left = self.eval(first, within)?;
75212×
                let right = self.eval(second, Some(&left))?;
75312×
                Ok(left.intersection(&right).copied().collect())
754
            }
7554×
            Expr::Difference(a, b) => {
7564×
                let left = self.eval(a, within)?;
7574×
                let right = self.eval(b, Some(&left))?;
7584×
                Ok(left.difference(&right).copied().collect())
759
            }
76055×
            Expr::Call(name, args) => self.call(name, args, within),
761
        }
762148×
    }
763
76464×
    fn sort_newest_first(&self, hashes: &mut [ChangeHash]) {
765130×
        hashes.sort_by(|a, b| {
766130×
            let (ma, mb) = (self.graph.get(a), self.graph.get(b));
767130×
            mb.map(|m| m.hlc).cmp(&ma.map(|m| m.hlc)).then(b.cmp(a))
768130×
        });
76964×
    }
770
}
771
772
impl Repo {
773
    /// Evaluate a revset within [`REVSET_BUDGET`].
77468×
    pub fn revset(&self, src: &str) -> Result<Revset> {
77568×
        self.revset_with_budget(src, REVSET_BUDGET)
77668×
    }
777
778
    /// Evaluate a revset: the changes it selects, newest first, with
779
    /// their metadata. Read-only. Fails past `budget`.
78069×
    pub fn revset_with_budget(&self, src: &str, budget: Duration) -> Result<Revset> {
78169×
        let expr = revset::parse(src).map_err(|e| err(format!("revset {src:?}: {e}")))?;
78268×
        let mut ev = Eval {
78368×
            repo: self,
78468×
            graph: HashMap::new(),
78568×
            loaded: HashSet::new(),
78668×
            all_loaded: false,
78768×
            dependents: None,
78868×
            names: HashMap::new(),
78968×
            auth: HashMap::new(),
79068×
            deadline: Instant::now() + budget,
79168×
            budget,
79268×
            now_ms: Hlc::now().wall_ms,
79368×
            depth: 0,
79468×
        };
79568×
        let set = ev.eval(&expr, None)?;
79663×
        let mut hashes: Vec<ChangeHash> = set.into_iter().collect();
79763×
        ev.sort_newest_first(&mut hashes);
79863×
        let metas = hashes
79963×
            .iter()
800119×
            .filter_map(|h| ev.graph.get(h).map(|m| (*h, m.clone())))
80163×
            .collect();
80263×
        Ok(Revset { hashes, metas })
80369×
    }
804
805
    /// The log entries a revset selects, newest first. A head of the
806
    /// current bookmark is marked as in `log`.
8072×
    pub fn log_revset(&self, src: &str) -> Result<Vec<LogEntry>> {
8082×
        let r = self.revset(src)?;
8092×
        let heads: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
8102×
        let wc = if self.is_bare() {
8110×
            None
812
        } else {
8132×
            self.working_copy().ok().map(|(h, _)| h)
814
        };
8152×
        let mut entries: Vec<LogEntry> = r
8162×
            .hashes
8172×
            .iter()
8187×
            .filter_map(|h| {
8197×
                r.metas.get(h).map(|m| LogEntry {
8207×
                    hash: *h,
8217×
                    change: m.clone(),
8227×
                    is_working_copy: Some(*h) == wc,
8237×
                    is_head: heads.contains(h),
8247×
                })
8257×
            })
8262×
            .collect();
827
        // The working copy first, as `log` shows it.
82810×
        entries.sort_by_key(|e| !e.is_working_copy);
8292×
        Ok(entries)
8302×
    }
831
}