Skip to main content

vvv_engine/protocol/
selection.rs

1use std::collections::BTreeSet;
2
3use serde::{Deserialize, Serialize};
4
5use crate::{Match, MatchId};
6
7/// Which matches of a search a later command acts on.
8///
9/// Ids are content-derived, so a selection made from `vvv search` can be
10/// handed to `vvv rewrite` in a separate process. Ordinals are the 1-based
11/// positions in the same search's result order, which is what human output
12/// numbers rows with. Either kind that no longer resolves means the files
13/// changed in between; the selection is then refused rather than silently
14/// narrowed.
15#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "lowercase")]
17pub enum Selection {
18    #[default]
19    All,
20    Ids(BTreeSet<MatchId>),
21    Ordinals(BTreeSet<usize>),
22}
23
24#[derive(Debug, thiserror::Error, PartialEq, Eq)]
25pub enum SelectionError {
26    #[error("no match with id(s) {}; the files may have changed since the search", ids.iter().map(ToString::to_string).collect::<Vec<_>>().join(", "))]
27    Unresolved { ids: BTreeSet<MatchId> },
28    #[error("no match numbered {}; the search found {found}", ordinals.iter().map(ToString::to_string).collect::<Vec<_>>().join(", "))]
29    OutOfRange {
30        ordinals: BTreeSet<usize>,
31        found: usize,
32    },
33}
34
35impl Selection {
36    pub fn ids(ids: impl IntoIterator<Item = MatchId>) -> Self {
37        Self::Ids(ids.into_iter().collect())
38    }
39
40    pub fn ordinals(ordinals: impl IntoIterator<Item = usize>) -> Self {
41        Self::Ordinals(ordinals.into_iter().collect())
42    }
43
44    pub fn is_all(&self) -> bool {
45        matches!(self, Self::All)
46    }
47
48    pub fn narrow(&self, matches: Vec<Match>) -> Result<Vec<Match>, SelectionError> {
49        match self {
50            Self::All => Ok(matches),
51            Self::Ordinals(wanted) => {
52                let found = matches.len();
53                let out: BTreeSet<usize> = wanted
54                    .iter()
55                    .filter(|&&n| n == 0 || n > found)
56                    .copied()
57                    .collect();
58                if !out.is_empty() {
59                    return Err(SelectionError::OutOfRange {
60                        ordinals: out,
61                        found,
62                    });
63                }
64                Ok(matches
65                    .into_iter()
66                    .enumerate()
67                    .filter(|(i, _)| wanted.contains(&(i + 1)))
68                    .map(|(_, m)| m)
69                    .collect())
70            }
71            Self::Ids(wanted) => {
72                let kept: Vec<Match> = matches
73                    .into_iter()
74                    .filter(|m| wanted.contains(&m.id))
75                    .collect();
76                let found: BTreeSet<&MatchId> = kept.iter().map(|m| &m.id).collect();
77                let missing: BTreeSet<MatchId> = wanted
78                    .iter()
79                    .filter(|id| !found.contains(id))
80                    .cloned()
81                    .collect();
82                if missing.is_empty() {
83                    Ok(kept)
84                } else {
85                    Err(SelectionError::Unresolved { ids: missing })
86                }
87            }
88        }
89    }
90}
91
92impl FromIterator<MatchId> for Selection {
93    fn from_iter<I: IntoIterator<Item = MatchId>>(iter: I) -> Self {
94        Self::ids(iter)
95    }
96}