1use std::cmp::Ordering;
18use std::collections::HashMap;
19use std::collections::HashSet;
20use std::slice;
21use std::sync::Arc;
22
23use itertools::Itertools as _;
24use thiserror::Error;
25
26use crate::dag_walk;
27use crate::object_id::HexPrefix;
28use crate::object_id::PrefixResolution;
29use crate::op_heads_store;
30use crate::op_heads_store::OpHeadResolutionError;
31use crate::op_heads_store::OpHeadsStore;
32use crate::op_heads_store::OpHeadsStoreError;
33use crate::op_store::OpStore;
34use crate::op_store::OpStoreError;
35use crate::op_store::OpStoreResult;
36use crate::op_store::OperationId;
37use crate::operation::Operation;
38use crate::repo::ReadonlyRepo;
39use crate::repo::Repo as _;
40use crate::repo::RepoLoader;
41
42#[derive(Debug, Error)]
44pub enum OpsetEvaluationError {
45 #[error(transparent)]
47 OpsetResolution(#[from] OpsetResolutionError),
48 #[error(transparent)]
50 OpHeadsStore(#[from] OpHeadsStoreError),
51 #[error(transparent)]
53 OpHeadResolution(#[from] OpHeadResolutionError),
54 #[error(transparent)]
56 OpStore(#[from] OpStoreError),
57}
58
59#[derive(Debug, Error)]
62pub enum OpsetResolutionError {
63 #[error(r#"The "{expr}" expression resolved to more than one operation"#)]
67 MultipleOperations {
68 expr: String,
70 candidates: Vec<OperationId>,
72 },
73 #[error(r#"The "{0}" expression resolved to no operations"#)]
75 EmptyOperations(String),
76 #[error(r#"Operation ID "{0}" is not a valid hexadecimal prefix"#)]
78 InvalidIdPrefix(String),
79 #[error(r#"No operation ID matching "{0}""#)]
81 NoSuchOperation(String),
82 #[error(r#"Operation ID prefix "{0}" is ambiguous"#)]
84 AmbiguousIdPrefix(String),
85}
86
87pub fn resolve_op_for_load(
89 repo_loader: &RepoLoader,
90 op_str: &str,
91) -> Result<Operation, OpsetEvaluationError> {
92 let op_store = repo_loader.op_store();
93 let op_heads_store = repo_loader.op_heads_store().as_ref();
94 let get_current_op = || {
95 op_heads_store::resolve_op_heads(op_heads_store, op_store, |op_heads| {
96 Err(OpsetResolutionError::MultipleOperations {
97 expr: "@".to_owned(),
98 candidates: op_heads.iter().map(|op| op.id().clone()).collect(),
99 }
100 .into())
101 })
102 };
103 let get_head_ops = || get_current_head_ops(op_store, op_heads_store);
104 resolve_single_op(op_store, get_current_op, get_head_ops, op_str)
105}
106
107pub fn resolve_op_with_repo(
111 repo: &ReadonlyRepo,
112 op_str: &str,
113) -> Result<Operation, OpsetEvaluationError> {
114 resolve_op_at(repo.op_store(), slice::from_ref(repo.operation()), op_str)
115}
116
117pub fn resolve_op_at(
119 op_store: &Arc<dyn OpStore>,
120 head_ops: &[Operation],
121 op_str: &str,
122) -> Result<Operation, OpsetEvaluationError> {
123 let get_current_op = || match head_ops {
124 [head_op] => Ok(head_op.clone()),
125 [] => Err(OpsetResolutionError::EmptyOperations("@".to_owned()).into()),
126 _ => Err(OpsetResolutionError::MultipleOperations {
127 expr: "@".to_owned(),
128 candidates: head_ops.iter().map(|op| op.id().clone()).collect(),
129 }
130 .into()),
131 };
132 let get_head_ops = || Ok(head_ops.to_vec());
133 resolve_single_op(op_store, get_current_op, get_head_ops, op_str)
134}
135
136fn resolve_single_op(
139 op_store: &Arc<dyn OpStore>,
140 get_current_op: impl FnOnce() -> Result<Operation, OpsetEvaluationError>,
141 get_head_ops: impl FnOnce() -> Result<Vec<Operation>, OpsetEvaluationError>,
142 op_str: &str,
143) -> Result<Operation, OpsetEvaluationError> {
144 let op_symbol = op_str.trim_end_matches(['-', '+']);
145 let op_postfix = &op_str[op_symbol.len()..];
146 let head_ops = op_postfix.contains('+').then(get_head_ops).transpose()?;
147 let mut operation = match op_symbol {
148 "@" => get_current_op(),
149 s => resolve_single_op_from_store(op_store, s),
150 }?;
151 for c in op_postfix.chars() {
152 let mut neighbor_ops = match c {
153 '-' => operation.parents().try_collect()?,
154 '+' => find_child_ops(head_ops.as_ref().unwrap(), operation.id())?,
155 _ => unreachable!(),
156 };
157 operation = match neighbor_ops.len() {
158 0 => Err(OpsetResolutionError::EmptyOperations(op_str.to_owned()))?,
159 1 => neighbor_ops.pop().unwrap(),
160 _ => Err(OpsetResolutionError::MultipleOperations {
161 expr: op_str.to_owned(),
162 candidates: neighbor_ops.iter().map(|op| op.id().clone()).collect(),
163 })?,
164 };
165 }
166 Ok(operation)
167}
168
169fn resolve_single_op_from_store(
170 op_store: &Arc<dyn OpStore>,
171 op_str: &str,
172) -> Result<Operation, OpsetEvaluationError> {
173 if op_str.is_empty() {
174 return Err(OpsetResolutionError::InvalidIdPrefix(op_str.to_owned()).into());
175 }
176 let prefix = HexPrefix::new(op_str)
177 .ok_or_else(|| OpsetResolutionError::InvalidIdPrefix(op_str.to_owned()))?;
178 match op_store.resolve_operation_id_prefix(&prefix)? {
179 PrefixResolution::NoMatch => {
180 Err(OpsetResolutionError::NoSuchOperation(op_str.to_owned()).into())
181 }
182 PrefixResolution::SingleMatch(op_id) => {
183 let data = op_store.read_operation(&op_id)?;
184 Ok(Operation::new(op_store.clone(), op_id, data))
185 }
186 PrefixResolution::AmbiguousMatch => {
187 Err(OpsetResolutionError::AmbiguousIdPrefix(op_str.to_owned()).into())
188 }
189 }
190}
191
192pub fn get_current_head_ops(
195 op_store: &Arc<dyn OpStore>,
196 op_heads_store: &dyn OpHeadsStore,
197) -> Result<Vec<Operation>, OpsetEvaluationError> {
198 let mut head_ops: Vec<_> = op_heads_store
199 .get_op_heads()?
200 .into_iter()
201 .map(|id| -> OpStoreResult<Operation> {
202 let data = op_store.read_operation(&id)?;
203 Ok(Operation::new(op_store.clone(), id, data))
204 })
205 .try_collect()?;
206 head_ops.sort_by_key(|op| op.metadata().end_time.timestamp);
208 Ok(head_ops)
209}
210
211fn find_child_ops(
216 head_ops: &[Operation],
217 root_op_id: &OperationId,
218) -> OpStoreResult<Vec<Operation>> {
219 walk_ancestors(head_ops)
220 .take_while(|res| res.as_ref().map_or(true, |op| op.id() != root_op_id))
221 .filter_ok(|op| op.parent_ids().iter().any(|id| id == root_op_id))
222 .try_collect()
223}
224
225#[derive(Clone, Debug, Eq, Hash, PartialEq)]
226struct OperationByEndTime(Operation);
227
228impl Ord for OperationByEndTime {
229 fn cmp(&self, other: &Self) -> Ordering {
230 let self_end_time = &self.0.metadata().end_time;
231 let other_end_time = &other.0.metadata().end_time;
232 self_end_time
233 .cmp(other_end_time)
234 .then_with(|| self.0.cmp(&other.0)) }
236}
237
238impl PartialOrd for OperationByEndTime {
239 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
240 Some(self.cmp(other))
241 }
242}
243
244pub fn walk_ancestors(
246 head_ops: &[Operation],
247) -> impl Iterator<Item = OpStoreResult<Operation>> + use<> {
248 let mut head_ops = head_ops
250 .iter()
251 .cloned()
252 .map(OperationByEndTime)
253 .collect_vec();
254 head_ops.sort_unstable_by(|op1, op2| op1.cmp(op2).reverse());
255 dag_walk::topo_order_reverse_lazy_ok(
258 head_ops.into_iter().map(Ok),
259 |OperationByEndTime(op)| op.id().clone(),
260 |OperationByEndTime(op)| op.parents().map_ok(OperationByEndTime).collect_vec(),
261 )
262 .map_ok(|OperationByEndTime(op)| op)
263}
264
265#[derive(Clone, Debug, Eq, PartialEq)]
267pub struct ReparentStats {
268 pub new_head_ids: Vec<OperationId>,
270 pub rewritten_count: usize,
272 pub unreachable_count: usize,
275}
276
277pub fn reparent_range(
287 op_store: &dyn OpStore,
288 root_ops: &[Operation],
289 head_ops: &[Operation],
290 dest_op: &Operation,
291) -> OpStoreResult<ReparentStats> {
292 let mut unwanted_ids: HashSet<_> = walk_ancestors(root_ops)
295 .map_ok(|op| op.id().clone())
296 .try_collect()?;
297 let ops_to_reparent: Vec<_> = walk_ancestors(head_ops)
298 .filter_ok(|op| !unwanted_ids.contains(op.id()))
299 .try_collect()?;
300 for op in walk_ancestors(slice::from_ref(dest_op)) {
301 unwanted_ids.remove(op?.id());
302 }
303 let unreachable_ids = unwanted_ids;
304
305 assert!(
306 ops_to_reparent
307 .last()
308 .is_none_or(|op| op.id() != op_store.root_operation_id()),
309 "root operation cannot be rewritten"
310 );
311 let mut rewritten_ids = HashMap::new();
312 for old_op in ops_to_reparent.into_iter().rev() {
313 let mut data = old_op.store_operation().clone();
314 let mut dest_once = Some(dest_op.id());
315 data.parents = data
316 .parents
317 .iter()
318 .filter_map(|id| rewritten_ids.get(id).or_else(|| dest_once.take()))
319 .cloned()
320 .collect();
321 let new_id = op_store.write_operation(&data)?;
322 rewritten_ids.insert(old_op.id().clone(), new_id);
323 }
324
325 let mut dest_once = Some(dest_op.id());
326 let new_head_ids = head_ops
327 .iter()
328 .filter_map(|op| rewritten_ids.get(op.id()).or_else(|| dest_once.take()))
329 .cloned()
330 .collect();
331 Ok(ReparentStats {
332 new_head_ids,
333 rewritten_count: rewritten_ids.len(),
334 unreachable_count: unreachable_ids.len(),
335 })
336}