jj_lib/
repo.rs

1// Copyright 2020 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![allow(missing_docs)]
16
17use std::collections::hash_map::Entry;
18use std::collections::BTreeMap;
19use std::collections::HashMap;
20use std::collections::HashSet;
21use std::fmt::Debug;
22use std::fmt::Formatter;
23use std::fs;
24use std::path::Path;
25use std::slice;
26use std::sync::Arc;
27
28use itertools::Itertools as _;
29use once_cell::sync::OnceCell;
30use thiserror::Error;
31use tracing::instrument;
32
33use self::dirty_cell::DirtyCell;
34use crate::backend::Backend;
35use crate::backend::BackendError;
36use crate::backend::BackendInitError;
37use crate::backend::BackendLoadError;
38use crate::backend::BackendResult;
39use crate::backend::ChangeId;
40use crate::backend::CommitId;
41use crate::backend::MergedTreeId;
42use crate::commit::Commit;
43use crate::commit::CommitByCommitterTimestamp;
44use crate::commit_builder::CommitBuilder;
45use crate::commit_builder::DetachedCommitBuilder;
46use crate::dag_walk;
47use crate::default_index::DefaultIndexStore;
48use crate::default_index::DefaultMutableIndex;
49use crate::default_submodule_store::DefaultSubmoduleStore;
50use crate::file_util::IoResultExt as _;
51use crate::file_util::PathError;
52use crate::index::ChangeIdIndex;
53use crate::index::Index;
54use crate::index::IndexReadError;
55use crate::index::IndexStore;
56use crate::index::MutableIndex;
57use crate::index::ReadonlyIndex;
58use crate::merge::trivial_merge;
59use crate::merge::MergeBuilder;
60use crate::object_id::HexPrefix;
61use crate::object_id::ObjectId as _;
62use crate::object_id::PrefixResolution;
63use crate::op_heads_store;
64use crate::op_heads_store::OpHeadResolutionError;
65use crate::op_heads_store::OpHeadsStore;
66use crate::op_heads_store::OpHeadsStoreError;
67use crate::op_store;
68use crate::op_store::OpStore;
69use crate::op_store::OpStoreError;
70use crate::op_store::OpStoreResult;
71use crate::op_store::OperationId;
72use crate::op_store::RefTarget;
73use crate::op_store::RemoteRef;
74use crate::op_store::RemoteRefState;
75use crate::op_store::RootOperationData;
76use crate::operation::Operation;
77use crate::ref_name::GitRefName;
78use crate::ref_name::RefName;
79use crate::ref_name::RemoteName;
80use crate::ref_name::RemoteRefSymbol;
81use crate::ref_name::WorkspaceName;
82use crate::ref_name::WorkspaceNameBuf;
83use crate::refs::diff_named_commit_ids;
84use crate::refs::diff_named_ref_targets;
85use crate::refs::diff_named_remote_refs;
86use crate::refs::merge_ref_targets;
87use crate::refs::merge_remote_refs;
88use crate::revset;
89use crate::revset::RevsetEvaluationError;
90use crate::revset::RevsetExpression;
91use crate::revset::RevsetIteratorExt as _;
92use crate::rewrite::merge_commit_trees;
93use crate::rewrite::rebase_commit_with_options;
94use crate::rewrite::CommitRewriter;
95use crate::rewrite::RebaseOptions;
96use crate::rewrite::RebasedCommit;
97use crate::rewrite::RewriteRefsOptions;
98use crate::settings::UserSettings;
99use crate::signing::SignInitError;
100use crate::signing::Signer;
101use crate::simple_backend::SimpleBackend;
102use crate::simple_op_heads_store::SimpleOpHeadsStore;
103use crate::simple_op_store::SimpleOpStore;
104use crate::store::Store;
105use crate::submodule_store::SubmoduleStore;
106use crate::transaction::Transaction;
107use crate::transaction::TransactionCommitError;
108use crate::view::RenameWorkspaceError;
109use crate::view::View;
110
111pub trait Repo {
112    /// Base repository that contains all committed data. Returns `self` if this
113    /// is a `ReadonlyRepo`,
114    fn base_repo(&self) -> &ReadonlyRepo;
115
116    fn store(&self) -> &Arc<Store>;
117
118    fn op_store(&self) -> &Arc<dyn OpStore>;
119
120    fn index(&self) -> &dyn Index;
121
122    fn view(&self) -> &View;
123
124    fn submodule_store(&self) -> &Arc<dyn SubmoduleStore>;
125
126    fn resolve_change_id(&self, change_id: &ChangeId) -> Option<Vec<CommitId>> {
127        // Replace this if we added more efficient lookup method.
128        let prefix = HexPrefix::from_bytes(change_id.as_bytes());
129        match self.resolve_change_id_prefix(&prefix) {
130            PrefixResolution::NoMatch => None,
131            PrefixResolution::SingleMatch(entries) => Some(entries),
132            PrefixResolution::AmbiguousMatch => panic!("complete change_id should be unambiguous"),
133        }
134    }
135
136    fn resolve_change_id_prefix(&self, prefix: &HexPrefix) -> PrefixResolution<Vec<CommitId>>;
137
138    fn shortest_unique_change_id_prefix_len(&self, target_id_bytes: &ChangeId) -> usize;
139}
140
141pub struct ReadonlyRepo {
142    loader: RepoLoader,
143    operation: Operation,
144    index: Box<dyn ReadonlyIndex>,
145    change_id_index: OnceCell<Box<dyn ChangeIdIndex>>,
146    // TODO: This should eventually become part of the index and not be stored fully in memory.
147    view: View,
148}
149
150impl Debug for ReadonlyRepo {
151    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
152        f.debug_struct("ReadonlyRepo")
153            .field("store", &self.loader.store)
154            .finish_non_exhaustive()
155    }
156}
157
158#[derive(Error, Debug)]
159pub enum RepoInitError {
160    #[error(transparent)]
161    Backend(#[from] BackendInitError),
162    #[error(transparent)]
163    OpHeadsStore(#[from] OpHeadsStoreError),
164    #[error(transparent)]
165    Path(#[from] PathError),
166}
167
168impl ReadonlyRepo {
169    pub fn default_op_store_initializer() -> &'static OpStoreInitializer<'static> {
170        &|_settings, store_path, root_data| {
171            Ok(Box::new(SimpleOpStore::init(store_path, root_data)?))
172        }
173    }
174
175    pub fn default_op_heads_store_initializer() -> &'static OpHeadsStoreInitializer<'static> {
176        &|_settings, store_path| Ok(Box::new(SimpleOpHeadsStore::init(store_path)?))
177    }
178
179    pub fn default_index_store_initializer() -> &'static IndexStoreInitializer<'static> {
180        &|_settings, store_path| Ok(Box::new(DefaultIndexStore::init(store_path)?))
181    }
182
183    pub fn default_submodule_store_initializer() -> &'static SubmoduleStoreInitializer<'static> {
184        &|_settings, store_path| Ok(Box::new(DefaultSubmoduleStore::init(store_path)))
185    }
186
187    #[expect(clippy::too_many_arguments)]
188    pub fn init(
189        settings: &UserSettings,
190        repo_path: &Path,
191        backend_initializer: &BackendInitializer,
192        signer: Signer,
193        op_store_initializer: &OpStoreInitializer,
194        op_heads_store_initializer: &OpHeadsStoreInitializer,
195        index_store_initializer: &IndexStoreInitializer,
196        submodule_store_initializer: &SubmoduleStoreInitializer,
197    ) -> Result<Arc<ReadonlyRepo>, RepoInitError> {
198        let repo_path = dunce::canonicalize(repo_path).context(repo_path)?;
199
200        let store_path = repo_path.join("store");
201        fs::create_dir(&store_path).context(&store_path)?;
202        let backend = backend_initializer(settings, &store_path)?;
203        let backend_path = store_path.join("type");
204        fs::write(&backend_path, backend.name()).context(&backend_path)?;
205        let store = Store::new(backend, signer);
206
207        let op_store_path = repo_path.join("op_store");
208        fs::create_dir(&op_store_path).context(&op_store_path)?;
209        let root_op_data = RootOperationData {
210            root_commit_id: store.root_commit_id().clone(),
211        };
212        let op_store = op_store_initializer(settings, &op_store_path, root_op_data)?;
213        let op_store_type_path = op_store_path.join("type");
214        fs::write(&op_store_type_path, op_store.name()).context(&op_store_type_path)?;
215        let op_store: Arc<dyn OpStore> = Arc::from(op_store);
216
217        let op_heads_path = repo_path.join("op_heads");
218        fs::create_dir(&op_heads_path).context(&op_heads_path)?;
219        let op_heads_store = op_heads_store_initializer(settings, &op_heads_path)?;
220        let op_heads_type_path = op_heads_path.join("type");
221        fs::write(&op_heads_type_path, op_heads_store.name()).context(&op_heads_type_path)?;
222        op_heads_store.update_op_heads(&[], op_store.root_operation_id())?;
223        let op_heads_store: Arc<dyn OpHeadsStore> = Arc::from(op_heads_store);
224
225        let index_path = repo_path.join("index");
226        fs::create_dir(&index_path).context(&index_path)?;
227        let index_store = index_store_initializer(settings, &index_path)?;
228        let index_type_path = index_path.join("type");
229        fs::write(&index_type_path, index_store.name()).context(&index_type_path)?;
230        let index_store: Arc<dyn IndexStore> = Arc::from(index_store);
231
232        let submodule_store_path = repo_path.join("submodule_store");
233        fs::create_dir(&submodule_store_path).context(&submodule_store_path)?;
234        let submodule_store = submodule_store_initializer(settings, &submodule_store_path)?;
235        let submodule_store_type_path = submodule_store_path.join("type");
236        fs::write(&submodule_store_type_path, submodule_store.name())
237            .context(&submodule_store_type_path)?;
238        let submodule_store = Arc::from(submodule_store);
239
240        let loader = RepoLoader {
241            settings: settings.clone(),
242            store,
243            op_store,
244            op_heads_store,
245            index_store,
246            submodule_store,
247        };
248
249        let root_operation = loader.root_operation();
250        let root_view = root_operation.view().expect("failed to read root view");
251        assert!(!root_view.heads().is_empty());
252        let index = loader
253            .index_store
254            .get_index_at_op(&root_operation, &loader.store)
255            // If the root op index couldn't be read, the index backend wouldn't
256            // be initialized properly.
257            .map_err(|err| BackendInitError(err.into()))?;
258        Ok(Arc::new(ReadonlyRepo {
259            loader,
260            operation: root_operation,
261            index,
262            change_id_index: OnceCell::new(),
263            view: root_view,
264        }))
265    }
266
267    pub fn loader(&self) -> &RepoLoader {
268        &self.loader
269    }
270
271    pub fn op_id(&self) -> &OperationId {
272        self.operation.id()
273    }
274
275    pub fn operation(&self) -> &Operation {
276        &self.operation
277    }
278
279    pub fn view(&self) -> &View {
280        &self.view
281    }
282
283    pub fn readonly_index(&self) -> &dyn ReadonlyIndex {
284        self.index.as_ref()
285    }
286
287    fn change_id_index(&self) -> &dyn ChangeIdIndex {
288        self.change_id_index
289            .get_or_init(|| {
290                self.readonly_index()
291                    .change_id_index(&mut self.view().heads().iter())
292            })
293            .as_ref()
294    }
295
296    pub fn op_heads_store(&self) -> &Arc<dyn OpHeadsStore> {
297        self.loader.op_heads_store()
298    }
299
300    pub fn index_store(&self) -> &Arc<dyn IndexStore> {
301        self.loader.index_store()
302    }
303
304    pub fn settings(&self) -> &UserSettings {
305        self.loader.settings()
306    }
307
308    pub fn start_transaction(self: &Arc<ReadonlyRepo>) -> Transaction {
309        let mut_repo = MutableRepo::new(self.clone(), self.readonly_index(), &self.view);
310        Transaction::new(mut_repo, self.settings())
311    }
312
313    pub fn reload_at_head(&self) -> Result<Arc<ReadonlyRepo>, RepoLoaderError> {
314        self.loader().load_at_head()
315    }
316
317    #[instrument]
318    pub fn reload_at(&self, operation: &Operation) -> Result<Arc<ReadonlyRepo>, RepoLoaderError> {
319        self.loader().load_at(operation)
320    }
321}
322
323impl Repo for ReadonlyRepo {
324    fn base_repo(&self) -> &ReadonlyRepo {
325        self
326    }
327
328    fn store(&self) -> &Arc<Store> {
329        self.loader.store()
330    }
331
332    fn op_store(&self) -> &Arc<dyn OpStore> {
333        self.loader.op_store()
334    }
335
336    fn index(&self) -> &dyn Index {
337        self.readonly_index().as_index()
338    }
339
340    fn view(&self) -> &View {
341        &self.view
342    }
343
344    fn submodule_store(&self) -> &Arc<dyn SubmoduleStore> {
345        self.loader.submodule_store()
346    }
347
348    fn resolve_change_id_prefix(&self, prefix: &HexPrefix) -> PrefixResolution<Vec<CommitId>> {
349        self.change_id_index().resolve_prefix(prefix)
350    }
351
352    fn shortest_unique_change_id_prefix_len(&self, target_id: &ChangeId) -> usize {
353        self.change_id_index().shortest_unique_prefix_len(target_id)
354    }
355}
356
357pub type BackendInitializer<'a> =
358    dyn Fn(&UserSettings, &Path) -> Result<Box<dyn Backend>, BackendInitError> + 'a;
359#[rustfmt::skip] // auto-formatted line would exceed the maximum width
360pub type OpStoreInitializer<'a> =
361    dyn Fn(&UserSettings, &Path, RootOperationData) -> Result<Box<dyn OpStore>, BackendInitError>
362    + 'a;
363pub type OpHeadsStoreInitializer<'a> =
364    dyn Fn(&UserSettings, &Path) -> Result<Box<dyn OpHeadsStore>, BackendInitError> + 'a;
365pub type IndexStoreInitializer<'a> =
366    dyn Fn(&UserSettings, &Path) -> Result<Box<dyn IndexStore>, BackendInitError> + 'a;
367pub type SubmoduleStoreInitializer<'a> =
368    dyn Fn(&UserSettings, &Path) -> Result<Box<dyn SubmoduleStore>, BackendInitError> + 'a;
369
370type BackendFactory =
371    Box<dyn Fn(&UserSettings, &Path) -> Result<Box<dyn Backend>, BackendLoadError>>;
372type OpStoreFactory = Box<
373    dyn Fn(&UserSettings, &Path, RootOperationData) -> Result<Box<dyn OpStore>, BackendLoadError>,
374>;
375type OpHeadsStoreFactory =
376    Box<dyn Fn(&UserSettings, &Path) -> Result<Box<dyn OpHeadsStore>, BackendLoadError>>;
377type IndexStoreFactory =
378    Box<dyn Fn(&UserSettings, &Path) -> Result<Box<dyn IndexStore>, BackendLoadError>>;
379type SubmoduleStoreFactory =
380    Box<dyn Fn(&UserSettings, &Path) -> Result<Box<dyn SubmoduleStore>, BackendLoadError>>;
381
382pub fn merge_factories_map<F>(base: &mut HashMap<String, F>, ext: HashMap<String, F>) {
383    for (name, factory) in ext {
384        match base.entry(name) {
385            Entry::Vacant(v) => {
386                v.insert(factory);
387            }
388            Entry::Occupied(o) => {
389                panic!("Conflicting factory definitions for '{}' factory", o.key())
390            }
391        }
392    }
393}
394
395pub struct StoreFactories {
396    backend_factories: HashMap<String, BackendFactory>,
397    op_store_factories: HashMap<String, OpStoreFactory>,
398    op_heads_store_factories: HashMap<String, OpHeadsStoreFactory>,
399    index_store_factories: HashMap<String, IndexStoreFactory>,
400    submodule_store_factories: HashMap<String, SubmoduleStoreFactory>,
401}
402
403impl Default for StoreFactories {
404    fn default() -> Self {
405        let mut factories = StoreFactories::empty();
406
407        // Backends
408        factories.add_backend(
409            SimpleBackend::name(),
410            Box::new(|_settings, store_path| Ok(Box::new(SimpleBackend::load(store_path)))),
411        );
412        #[cfg(feature = "git")]
413        factories.add_backend(
414            crate::git_backend::GitBackend::name(),
415            Box::new(|settings, store_path| {
416                Ok(Box::new(crate::git_backend::GitBackend::load(
417                    settings, store_path,
418                )?))
419            }),
420        );
421        #[cfg(feature = "testing")]
422        factories.add_backend(
423            crate::secret_backend::SecretBackend::name(),
424            Box::new(|settings, store_path| {
425                Ok(Box::new(crate::secret_backend::SecretBackend::load(
426                    settings, store_path,
427                )?))
428            }),
429        );
430
431        // OpStores
432        factories.add_op_store(
433            SimpleOpStore::name(),
434            Box::new(|_settings, store_path, root_data| {
435                Ok(Box::new(SimpleOpStore::load(store_path, root_data)))
436            }),
437        );
438
439        // OpHeadsStores
440        factories.add_op_heads_store(
441            SimpleOpHeadsStore::name(),
442            Box::new(|_settings, store_path| Ok(Box::new(SimpleOpHeadsStore::load(store_path)))),
443        );
444
445        // Index
446        factories.add_index_store(
447            DefaultIndexStore::name(),
448            Box::new(|_settings, store_path| Ok(Box::new(DefaultIndexStore::load(store_path)))),
449        );
450
451        // SubmoduleStores
452        factories.add_submodule_store(
453            DefaultSubmoduleStore::name(),
454            Box::new(|_settings, store_path| Ok(Box::new(DefaultSubmoduleStore::load(store_path)))),
455        );
456
457        factories
458    }
459}
460
461#[derive(Debug, Error)]
462pub enum StoreLoadError {
463    #[error("Unsupported {store} backend type '{store_type}'")]
464    UnsupportedType {
465        store: &'static str,
466        store_type: String,
467    },
468    #[error("Failed to read {store} backend type")]
469    ReadError {
470        store: &'static str,
471        source: PathError,
472    },
473    #[error(transparent)]
474    Backend(#[from] BackendLoadError),
475    #[error(transparent)]
476    Signing(#[from] SignInitError),
477}
478
479impl StoreFactories {
480    pub fn empty() -> Self {
481        StoreFactories {
482            backend_factories: HashMap::new(),
483            op_store_factories: HashMap::new(),
484            op_heads_store_factories: HashMap::new(),
485            index_store_factories: HashMap::new(),
486            submodule_store_factories: HashMap::new(),
487        }
488    }
489
490    pub fn merge(&mut self, ext: StoreFactories) {
491        let StoreFactories {
492            backend_factories,
493            op_store_factories,
494            op_heads_store_factories,
495            index_store_factories,
496            submodule_store_factories,
497        } = ext;
498
499        merge_factories_map(&mut self.backend_factories, backend_factories);
500        merge_factories_map(&mut self.op_store_factories, op_store_factories);
501        merge_factories_map(&mut self.op_heads_store_factories, op_heads_store_factories);
502        merge_factories_map(&mut self.index_store_factories, index_store_factories);
503        merge_factories_map(
504            &mut self.submodule_store_factories,
505            submodule_store_factories,
506        );
507    }
508
509    pub fn add_backend(&mut self, name: &str, factory: BackendFactory) {
510        self.backend_factories.insert(name.to_string(), factory);
511    }
512
513    pub fn load_backend(
514        &self,
515        settings: &UserSettings,
516        store_path: &Path,
517    ) -> Result<Box<dyn Backend>, StoreLoadError> {
518        let backend_type = read_store_type("commit", store_path.join("type"))?;
519        let backend_factory = self.backend_factories.get(&backend_type).ok_or_else(|| {
520            StoreLoadError::UnsupportedType {
521                store: "commit",
522                store_type: backend_type.to_string(),
523            }
524        })?;
525        Ok(backend_factory(settings, store_path)?)
526    }
527
528    pub fn add_op_store(&mut self, name: &str, factory: OpStoreFactory) {
529        self.op_store_factories.insert(name.to_string(), factory);
530    }
531
532    pub fn load_op_store(
533        &self,
534        settings: &UserSettings,
535        store_path: &Path,
536        root_data: RootOperationData,
537    ) -> Result<Box<dyn OpStore>, StoreLoadError> {
538        let op_store_type = read_store_type("operation", store_path.join("type"))?;
539        let op_store_factory = self.op_store_factories.get(&op_store_type).ok_or_else(|| {
540            StoreLoadError::UnsupportedType {
541                store: "operation",
542                store_type: op_store_type.to_string(),
543            }
544        })?;
545        Ok(op_store_factory(settings, store_path, root_data)?)
546    }
547
548    pub fn add_op_heads_store(&mut self, name: &str, factory: OpHeadsStoreFactory) {
549        self.op_heads_store_factories
550            .insert(name.to_string(), factory);
551    }
552
553    pub fn load_op_heads_store(
554        &self,
555        settings: &UserSettings,
556        store_path: &Path,
557    ) -> Result<Box<dyn OpHeadsStore>, StoreLoadError> {
558        let op_heads_store_type = read_store_type("operation heads", store_path.join("type"))?;
559        let op_heads_store_factory = self
560            .op_heads_store_factories
561            .get(&op_heads_store_type)
562            .ok_or_else(|| StoreLoadError::UnsupportedType {
563                store: "operation heads",
564                store_type: op_heads_store_type.to_string(),
565            })?;
566        Ok(op_heads_store_factory(settings, store_path)?)
567    }
568
569    pub fn add_index_store(&mut self, name: &str, factory: IndexStoreFactory) {
570        self.index_store_factories.insert(name.to_string(), factory);
571    }
572
573    pub fn load_index_store(
574        &self,
575        settings: &UserSettings,
576        store_path: &Path,
577    ) -> Result<Box<dyn IndexStore>, StoreLoadError> {
578        let index_store_type = read_store_type("index", store_path.join("type"))?;
579        let index_store_factory = self
580            .index_store_factories
581            .get(&index_store_type)
582            .ok_or_else(|| StoreLoadError::UnsupportedType {
583                store: "index",
584                store_type: index_store_type.to_string(),
585            })?;
586        Ok(index_store_factory(settings, store_path)?)
587    }
588
589    pub fn add_submodule_store(&mut self, name: &str, factory: SubmoduleStoreFactory) {
590        self.submodule_store_factories
591            .insert(name.to_string(), factory);
592    }
593
594    pub fn load_submodule_store(
595        &self,
596        settings: &UserSettings,
597        store_path: &Path,
598    ) -> Result<Box<dyn SubmoduleStore>, StoreLoadError> {
599        let submodule_store_type = read_store_type("submodule_store", store_path.join("type"))?;
600        let submodule_store_factory = self
601            .submodule_store_factories
602            .get(&submodule_store_type)
603            .ok_or_else(|| StoreLoadError::UnsupportedType {
604                store: "submodule_store",
605                store_type: submodule_store_type.to_string(),
606            })?;
607
608        Ok(submodule_store_factory(settings, store_path)?)
609    }
610}
611
612pub fn read_store_type(
613    store: &'static str,
614    path: impl AsRef<Path>,
615) -> Result<String, StoreLoadError> {
616    let path = path.as_ref();
617    fs::read_to_string(path)
618        .context(path)
619        .map_err(|source| StoreLoadError::ReadError { store, source })
620}
621
622#[derive(Debug, Error)]
623pub enum RepoLoaderError {
624    #[error(transparent)]
625    Backend(#[from] BackendError),
626    #[error(transparent)]
627    IndexRead(#[from] IndexReadError),
628    #[error(transparent)]
629    OpHeadResolution(#[from] OpHeadResolutionError),
630    #[error(transparent)]
631    OpHeadsStoreError(#[from] OpHeadsStoreError),
632    #[error(transparent)]
633    OpStore(#[from] OpStoreError),
634    #[error(transparent)]
635    TransactionCommit(#[from] TransactionCommitError),
636}
637
638/// Helps create `ReadonlyRepo` instances of a repo at the head operation or at
639/// a given operation.
640#[derive(Clone)]
641pub struct RepoLoader {
642    settings: UserSettings,
643    store: Arc<Store>,
644    op_store: Arc<dyn OpStore>,
645    op_heads_store: Arc<dyn OpHeadsStore>,
646    index_store: Arc<dyn IndexStore>,
647    submodule_store: Arc<dyn SubmoduleStore>,
648}
649
650impl RepoLoader {
651    pub fn new(
652        settings: UserSettings,
653        store: Arc<Store>,
654        op_store: Arc<dyn OpStore>,
655        op_heads_store: Arc<dyn OpHeadsStore>,
656        index_store: Arc<dyn IndexStore>,
657        submodule_store: Arc<dyn SubmoduleStore>,
658    ) -> Self {
659        Self {
660            settings,
661            store,
662            op_store,
663            op_heads_store,
664            index_store,
665            submodule_store,
666        }
667    }
668
669    /// Creates a `RepoLoader` for the repo at `repo_path` by reading the
670    /// various `.jj/repo/<backend>/type` files and loading the right
671    /// backends from `store_factories`.
672    pub fn init_from_file_system(
673        settings: &UserSettings,
674        repo_path: &Path,
675        store_factories: &StoreFactories,
676    ) -> Result<Self, StoreLoadError> {
677        let store = Store::new(
678            store_factories.load_backend(settings, &repo_path.join("store"))?,
679            Signer::from_settings(settings)?,
680        );
681        let root_op_data = RootOperationData {
682            root_commit_id: store.root_commit_id().clone(),
683        };
684        let op_store = Arc::from(store_factories.load_op_store(
685            settings,
686            &repo_path.join("op_store"),
687            root_op_data,
688        )?);
689        let op_heads_store =
690            Arc::from(store_factories.load_op_heads_store(settings, &repo_path.join("op_heads"))?);
691        let index_store =
692            Arc::from(store_factories.load_index_store(settings, &repo_path.join("index"))?);
693        let submodule_store = Arc::from(
694            store_factories.load_submodule_store(settings, &repo_path.join("submodule_store"))?,
695        );
696        Ok(Self {
697            settings: settings.clone(),
698            store,
699            op_store,
700            op_heads_store,
701            index_store,
702            submodule_store,
703        })
704    }
705
706    pub fn settings(&self) -> &UserSettings {
707        &self.settings
708    }
709
710    pub fn store(&self) -> &Arc<Store> {
711        &self.store
712    }
713
714    pub fn index_store(&self) -> &Arc<dyn IndexStore> {
715        &self.index_store
716    }
717
718    pub fn op_store(&self) -> &Arc<dyn OpStore> {
719        &self.op_store
720    }
721
722    pub fn op_heads_store(&self) -> &Arc<dyn OpHeadsStore> {
723        &self.op_heads_store
724    }
725
726    pub fn submodule_store(&self) -> &Arc<dyn SubmoduleStore> {
727        &self.submodule_store
728    }
729
730    pub fn load_at_head(&self) -> Result<Arc<ReadonlyRepo>, RepoLoaderError> {
731        let op = op_heads_store::resolve_op_heads(
732            self.op_heads_store.as_ref(),
733            &self.op_store,
734            |op_heads| self._resolve_op_heads(op_heads),
735        )?;
736        let view = op.view()?;
737        self._finish_load(op, view)
738    }
739
740    #[instrument(skip(self))]
741    pub fn load_at(&self, op: &Operation) -> Result<Arc<ReadonlyRepo>, RepoLoaderError> {
742        let view = op.view()?;
743        self._finish_load(op.clone(), view)
744    }
745
746    pub fn create_from(
747        &self,
748        operation: Operation,
749        view: View,
750        index: Box<dyn ReadonlyIndex>,
751    ) -> Arc<ReadonlyRepo> {
752        let repo = ReadonlyRepo {
753            loader: self.clone(),
754            operation,
755            index,
756            change_id_index: OnceCell::new(),
757            view,
758        };
759        Arc::new(repo)
760    }
761
762    // If we add a higher-level abstraction of OpStore, root_operation() and
763    // load_operation() will be moved there.
764
765    /// Returns the root operation.
766    pub fn root_operation(&self) -> Operation {
767        self.load_operation(self.op_store.root_operation_id())
768            .expect("failed to read root operation")
769    }
770
771    /// Loads the specified operation from the operation store.
772    pub fn load_operation(&self, id: &OperationId) -> OpStoreResult<Operation> {
773        let data = self.op_store.read_operation(id)?;
774        Ok(Operation::new(self.op_store.clone(), id.clone(), data))
775    }
776
777    /// Merges the given `operations` into a single operation. Returns the root
778    /// operation if the `operations` is empty.
779    pub fn merge_operations(
780        &self,
781        operations: Vec<Operation>,
782        tx_description: Option<&str>,
783    ) -> Result<Operation, RepoLoaderError> {
784        let num_operations = operations.len();
785        let mut operations = operations.into_iter();
786        let Some(base_op) = operations.next() else {
787            return Ok(self.root_operation());
788        };
789        let final_op = if num_operations > 1 {
790            let base_repo = self.load_at(&base_op)?;
791            let mut tx = base_repo.start_transaction();
792            for other_op in operations {
793                tx.merge_operation(other_op)?;
794                tx.repo_mut().rebase_descendants()?;
795            }
796            let tx_description = tx_description.map_or_else(
797                || format!("merge {num_operations} operations"),
798                |tx_description| tx_description.to_string(),
799            );
800            let merged_repo = tx.write(tx_description)?.leave_unpublished();
801            merged_repo.operation().clone()
802        } else {
803            base_op
804        };
805
806        Ok(final_op)
807    }
808
809    fn _resolve_op_heads(&self, op_heads: Vec<Operation>) -> Result<Operation, RepoLoaderError> {
810        assert!(!op_heads.is_empty());
811        self.merge_operations(op_heads, Some("reconcile divergent operations"))
812    }
813
814    fn _finish_load(
815        &self,
816        operation: Operation,
817        view: View,
818    ) -> Result<Arc<ReadonlyRepo>, RepoLoaderError> {
819        let index = self.index_store.get_index_at_op(&operation, &self.store)?;
820        let repo = ReadonlyRepo {
821            loader: self.clone(),
822            operation,
823            index,
824            change_id_index: OnceCell::new(),
825            view,
826        };
827        Ok(Arc::new(repo))
828    }
829}
830
831#[derive(Clone, Debug, PartialEq, Eq)]
832enum Rewrite {
833    /// The old commit was rewritten as this new commit. Children should be
834    /// rebased onto the new commit.
835    Rewritten(CommitId),
836    /// The old commit was rewritten as multiple other commits. Children should
837    /// not be rebased.
838    Divergent(Vec<CommitId>),
839    /// The old commit was abandoned. Children should be rebased onto the given
840    /// commits (typically the parents of the old commit).
841    Abandoned(Vec<CommitId>),
842}
843
844impl Rewrite {
845    fn new_parent_ids(&self) -> &[CommitId] {
846        match self {
847            Rewrite::Rewritten(new_parent_id) => std::slice::from_ref(new_parent_id),
848            Rewrite::Divergent(new_parent_ids) => new_parent_ids.as_slice(),
849            Rewrite::Abandoned(new_parent_ids) => new_parent_ids.as_slice(),
850        }
851    }
852}
853
854pub struct MutableRepo {
855    base_repo: Arc<ReadonlyRepo>,
856    index: Box<dyn MutableIndex>,
857    view: DirtyCell<View>,
858    /// Mapping from new commit to its predecessors.
859    ///
860    /// This is similar to (the reverse of) `parent_mapping`, but
861    /// `commit_predecessors` will never be cleared on `rebase_descendants()`.
862    commit_predecessors: BTreeMap<CommitId, Vec<CommitId>>,
863    // The commit identified by the key has been replaced by all the ones in the value.
864    // * Bookmarks pointing to the old commit should be updated to the new commit, resulting in a
865    //   conflict if there multiple new commits.
866    // * Children of the old commit should be rebased onto the new commits. However, if the type is
867    //   `Divergent`, they should be left in place.
868    // * Working copies pointing to the old commit should be updated to the first of the new
869    //   commits. However, if the type is `Abandoned`, a new working-copy commit should be created
870    //   on top of all of the new commits instead.
871    parent_mapping: HashMap<CommitId, Rewrite>,
872}
873
874impl MutableRepo {
875    pub fn new(
876        base_repo: Arc<ReadonlyRepo>,
877        index: &dyn ReadonlyIndex,
878        view: &View,
879    ) -> MutableRepo {
880        let mut_view = view.clone();
881        let mut_index = index.start_modification();
882        MutableRepo {
883            base_repo,
884            index: mut_index,
885            view: DirtyCell::with_clean(mut_view),
886            commit_predecessors: Default::default(),
887            parent_mapping: Default::default(),
888        }
889    }
890
891    pub fn base_repo(&self) -> &Arc<ReadonlyRepo> {
892        &self.base_repo
893    }
894
895    fn view_mut(&mut self) -> &mut View {
896        self.view.get_mut()
897    }
898
899    pub fn mutable_index(&self) -> &dyn MutableIndex {
900        self.index.as_ref()
901    }
902
903    pub fn has_changes(&self) -> bool {
904        self.view.ensure_clean(|v| self.enforce_view_invariants(v));
905        !(self.commit_predecessors.is_empty()
906            && self.parent_mapping.is_empty()
907            && self.view() == &self.base_repo.view)
908    }
909
910    pub(crate) fn consume(
911        self,
912    ) -> (
913        Box<dyn MutableIndex>,
914        View,
915        BTreeMap<CommitId, Vec<CommitId>>,
916    ) {
917        self.view.ensure_clean(|v| self.enforce_view_invariants(v));
918        (self.index, self.view.into_inner(), self.commit_predecessors)
919    }
920
921    /// Returns a [`CommitBuilder`] to write new commit to the repo.
922    pub fn new_commit(&mut self, parents: Vec<CommitId>, tree_id: MergedTreeId) -> CommitBuilder {
923        let settings = self.base_repo.settings();
924        DetachedCommitBuilder::for_new_commit(self, settings, parents, tree_id).attach(self)
925    }
926
927    /// Returns a [`CommitBuilder`] to rewrite an existing commit in the repo.
928    pub fn rewrite_commit(&mut self, predecessor: &Commit) -> CommitBuilder {
929        let settings = self.base_repo.settings();
930        DetachedCommitBuilder::for_rewrite_from(self, settings, predecessor).attach(self)
931        // CommitBuilder::write will record the rewrite in
932        // `self.rewritten_commits`
933    }
934
935    pub(crate) fn set_predecessors(&mut self, id: CommitId, predecessors: Vec<CommitId>) {
936        self.commit_predecessors.insert(id, predecessors);
937    }
938
939    /// Record a commit as having been rewritten to another commit in this
940    /// transaction.
941    ///
942    /// This record is used by `rebase_descendants` to know which commits have
943    /// children that need to be rebased, and where to rebase them to. See the
944    /// docstring for `record_rewritten_commit` for details.
945    pub fn set_rewritten_commit(&mut self, old_id: CommitId, new_id: CommitId) {
946        assert_ne!(old_id, *self.store().root_commit_id());
947        self.parent_mapping
948            .insert(old_id, Rewrite::Rewritten(new_id));
949    }
950
951    /// Record a commit as being rewritten into multiple other commits in this
952    /// transaction.
953    ///
954    /// A later call to `rebase_descendants()` will update bookmarks pointing to
955    /// `old_id` be conflicted and pointing to all pf `new_ids`. Working copies
956    /// pointing to `old_id` will be updated to point to the first commit in
957    /// `new_ids``. Descendants of `old_id` will be left alone.
958    pub fn set_divergent_rewrite(
959        &mut self,
960        old_id: CommitId,
961        new_ids: impl IntoIterator<Item = CommitId>,
962    ) {
963        assert_ne!(old_id, *self.store().root_commit_id());
964        self.parent_mapping.insert(
965            old_id.clone(),
966            Rewrite::Divergent(new_ids.into_iter().collect()),
967        );
968    }
969
970    /// Record a commit as having been abandoned in this transaction.
971    ///
972    /// This record is used by `rebase_descendants` to know which commits have
973    /// children that need to be rebased, and where to rebase the children to.
974    ///
975    /// The `rebase_descendants` logic will rebase the descendants of the old
976    /// commit to become the descendants of parent(s) of the old commit. Any
977    /// bookmarks at the old commit will be either moved to the parent(s) of the
978    /// old commit or deleted depending on [`RewriteRefsOptions`].
979    pub fn record_abandoned_commit(&mut self, old_commit: &Commit) {
980        assert_ne!(old_commit.id(), self.store().root_commit_id());
981        // Descendants should be rebased onto the commit's parents
982        self.record_abandoned_commit_with_parents(
983            old_commit.id().clone(),
984            old_commit.parent_ids().iter().cloned(),
985        );
986    }
987
988    /// Record a commit as having been abandoned in this transaction.
989    ///
990    /// A later `rebase_descendants()` will rebase children of `old_id` onto
991    /// `new_parent_ids`. A working copy pointing to `old_id` will point to a
992    /// new commit on top of `new_parent_ids`.
993    pub fn record_abandoned_commit_with_parents(
994        &mut self,
995        old_id: CommitId,
996        new_parent_ids: impl IntoIterator<Item = CommitId>,
997    ) {
998        assert_ne!(old_id, *self.store().root_commit_id());
999        self.parent_mapping.insert(
1000            old_id,
1001            Rewrite::Abandoned(new_parent_ids.into_iter().collect()),
1002        );
1003    }
1004
1005    pub fn has_rewrites(&self) -> bool {
1006        !self.parent_mapping.is_empty()
1007    }
1008
1009    /// Calculates new parents for a commit that's currently based on the given
1010    /// parents. It does that by considering how previous commits have been
1011    /// rewritten and abandoned.
1012    ///
1013    /// If `parent_mapping` contains cycles, this function may either panic or
1014    /// drop parents that caused cycles.
1015    pub fn new_parents(&self, old_ids: &[CommitId]) -> Vec<CommitId> {
1016        self.rewritten_ids_with(old_ids, |rewrite| !matches!(rewrite, Rewrite::Divergent(_)))
1017    }
1018
1019    fn rewritten_ids_with(
1020        &self,
1021        old_ids: &[CommitId],
1022        mut predicate: impl FnMut(&Rewrite) -> bool,
1023    ) -> Vec<CommitId> {
1024        assert!(!old_ids.is_empty());
1025        let mut new_ids = Vec::with_capacity(old_ids.len());
1026        let mut to_visit = old_ids.iter().rev().collect_vec();
1027        let mut visited = HashSet::new();
1028        while let Some(id) = to_visit.pop() {
1029            if !visited.insert(id) {
1030                continue;
1031            }
1032            match self.parent_mapping.get(id).filter(|&v| predicate(v)) {
1033                None => {
1034                    new_ids.push(id.clone());
1035                }
1036                Some(rewrite) => {
1037                    let replacements = rewrite.new_parent_ids();
1038                    assert!(
1039                        // Each commit must have a parent, so a parent can
1040                        // not just be mapped to nothing. This assertion
1041                        // could be removed if this function is used for
1042                        // mapping something other than a commit's parents.
1043                        !replacements.is_empty(),
1044                        "Found empty value for key {id:?} in the parent mapping",
1045                    );
1046                    to_visit.extend(replacements.iter().rev());
1047                }
1048            }
1049        }
1050        assert!(
1051            !new_ids.is_empty(),
1052            "new ids become empty because of cycle in the parent mapping"
1053        );
1054        debug_assert!(new_ids.iter().all_unique());
1055        new_ids
1056    }
1057
1058    /// Fully resolves transitive replacements in `parent_mapping`.
1059    ///
1060    /// If `parent_mapping` contains cycles, this function will panic.
1061    fn resolve_rewrite_mapping_with(
1062        &self,
1063        mut predicate: impl FnMut(&Rewrite) -> bool,
1064    ) -> HashMap<CommitId, Vec<CommitId>> {
1065        let sorted_ids = dag_walk::topo_order_forward(
1066            self.parent_mapping.keys(),
1067            |&id| id,
1068            |&id| match self.parent_mapping.get(id).filter(|&v| predicate(v)) {
1069                None => &[],
1070                Some(rewrite) => rewrite.new_parent_ids(),
1071            },
1072        );
1073        let mut new_mapping: HashMap<CommitId, Vec<CommitId>> = HashMap::new();
1074        for old_id in sorted_ids {
1075            let Some(rewrite) = self.parent_mapping.get(old_id).filter(|&v| predicate(v)) else {
1076                continue;
1077            };
1078            let lookup = |id| new_mapping.get(id).map_or(slice::from_ref(id), |ids| ids);
1079            let new_ids = match rewrite.new_parent_ids() {
1080                [id] => lookup(id).to_vec(), // unique() not needed
1081                ids => ids.iter().flat_map(lookup).unique().cloned().collect(),
1082            };
1083            debug_assert_eq!(
1084                new_ids,
1085                self.rewritten_ids_with(slice::from_ref(old_id), &mut predicate)
1086            );
1087            new_mapping.insert(old_id.clone(), new_ids);
1088        }
1089        new_mapping
1090    }
1091
1092    /// Updates bookmarks, working copies, and anonymous heads after rewriting
1093    /// and/or abandoning commits.
1094    pub fn update_rewritten_references(
1095        &mut self,
1096        options: &RewriteRefsOptions,
1097    ) -> BackendResult<()> {
1098        self.update_all_references(options)?;
1099        self.update_heads()
1100            .map_err(|err| err.into_backend_error())?;
1101        Ok(())
1102    }
1103
1104    fn update_all_references(&mut self, options: &RewriteRefsOptions) -> BackendResult<()> {
1105        let rewrite_mapping = self.resolve_rewrite_mapping_with(|_| true);
1106        self.update_local_bookmarks(&rewrite_mapping, options);
1107        self.update_wc_commits(&rewrite_mapping)?;
1108        Ok(())
1109    }
1110
1111    fn update_local_bookmarks(
1112        &mut self,
1113        rewrite_mapping: &HashMap<CommitId, Vec<CommitId>>,
1114        options: &RewriteRefsOptions,
1115    ) {
1116        let changed_branches = self
1117            .view()
1118            .local_bookmarks()
1119            .flat_map(|(name, target)| {
1120                target.added_ids().filter_map(|id| {
1121                    let change = rewrite_mapping.get_key_value(id)?;
1122                    Some((name.to_owned(), change))
1123                })
1124            })
1125            .collect_vec();
1126        for (bookmark_name, (old_commit_id, new_commit_ids)) in changed_branches {
1127            let should_delete = options.delete_abandoned_bookmarks
1128                && matches!(
1129                    self.parent_mapping.get(old_commit_id),
1130                    Some(Rewrite::Abandoned(_))
1131                );
1132            let old_target = RefTarget::normal(old_commit_id.clone());
1133            let new_target = if should_delete {
1134                RefTarget::absent()
1135            } else {
1136                let ids = itertools::intersperse(new_commit_ids, old_commit_id)
1137                    .map(|id| Some(id.clone()));
1138                RefTarget::from_merge(MergeBuilder::from_iter(ids).build())
1139            };
1140
1141            self.merge_local_bookmark(&bookmark_name, &old_target, &new_target);
1142        }
1143    }
1144
1145    fn update_wc_commits(
1146        &mut self,
1147        rewrite_mapping: &HashMap<CommitId, Vec<CommitId>>,
1148    ) -> BackendResult<()> {
1149        let changed_wc_commits = self
1150            .view()
1151            .wc_commit_ids()
1152            .iter()
1153            .filter_map(|(name, commit_id)| {
1154                let change = rewrite_mapping.get_key_value(commit_id)?;
1155                Some((name.to_owned(), change))
1156            })
1157            .collect_vec();
1158        let mut recreated_wc_commits: HashMap<&CommitId, Commit> = HashMap::new();
1159        for (name, (old_commit_id, new_commit_ids)) in changed_wc_commits {
1160            let abandoned_old_commit = matches!(
1161                self.parent_mapping.get(old_commit_id),
1162                Some(Rewrite::Abandoned(_))
1163            );
1164            let new_wc_commit = if !abandoned_old_commit {
1165                // We arbitrarily pick a new working-copy commit among the candidates.
1166                self.store().get_commit(&new_commit_ids[0])?
1167            } else if let Some(commit) = recreated_wc_commits.get(old_commit_id) {
1168                commit.clone()
1169            } else {
1170                let new_commits: Vec<_> = new_commit_ids
1171                    .iter()
1172                    .map(|id| self.store().get_commit(id))
1173                    .try_collect()?;
1174                let merged_parents_tree = merge_commit_trees(self, &new_commits)?;
1175                let commit = self
1176                    .new_commit(new_commit_ids.clone(), merged_parents_tree.id().clone())
1177                    .write()?;
1178                recreated_wc_commits.insert(old_commit_id, commit.clone());
1179                commit
1180            };
1181            self.edit(name, &new_wc_commit).map_err(|err| match err {
1182                EditCommitError::BackendError(backend_error) => backend_error,
1183                EditCommitError::WorkingCopyCommitNotFound(_)
1184                | EditCommitError::RewriteRootCommit(_) => panic!("unexpected error: {err:?}"),
1185            })?;
1186        }
1187        Ok(())
1188    }
1189
1190    fn update_heads(&mut self) -> Result<(), RevsetEvaluationError> {
1191        let old_commits_expression =
1192            RevsetExpression::commits(self.parent_mapping.keys().cloned().collect());
1193        let heads_to_add_expression = old_commits_expression
1194            .parents()
1195            .minus(&old_commits_expression);
1196        let heads_to_add: Vec<_> = heads_to_add_expression
1197            .evaluate(self)?
1198            .iter()
1199            .try_collect()?;
1200
1201        let mut view = self.view().store_view().clone();
1202        for commit_id in self.parent_mapping.keys() {
1203            view.head_ids.remove(commit_id);
1204        }
1205        view.head_ids.extend(heads_to_add);
1206        self.set_view(view);
1207        Ok(())
1208    }
1209
1210    /// Find descendants of `root`, unless they've already been rewritten
1211    /// (according to `parent_mapping`).
1212    pub fn find_descendants_for_rebase(&self, roots: Vec<CommitId>) -> BackendResult<Vec<Commit>> {
1213        let to_visit_revset = RevsetExpression::commits(roots)
1214            .descendants()
1215            .minus(&RevsetExpression::commits(
1216                self.parent_mapping.keys().cloned().collect(),
1217            ))
1218            .evaluate(self)
1219            .map_err(|err| err.into_backend_error())?;
1220        let to_visit = to_visit_revset
1221            .iter()
1222            .commits(self.store())
1223            .try_collect()
1224            .map_err(|err| err.into_backend_error())?;
1225        Ok(to_visit)
1226    }
1227
1228    /// Order a set of commits in an order they should be rebased in. The result
1229    /// is in reverse order so the next value can be removed from the end.
1230    fn order_commits_for_rebase(
1231        &self,
1232        to_visit: Vec<Commit>,
1233        new_parents_map: &HashMap<CommitId, Vec<CommitId>>,
1234    ) -> BackendResult<Vec<Commit>> {
1235        let to_visit_set: HashSet<CommitId> =
1236            to_visit.iter().map(|commit| commit.id().clone()).collect();
1237        let mut visited = HashSet::new();
1238        // Calculate an order where we rebase parents first, but if the parents were
1239        // rewritten, make sure we rebase the rewritten parent first.
1240        let store = self.store();
1241        dag_walk::topo_order_reverse_ok(
1242            to_visit.into_iter().map(Ok),
1243            |commit| commit.id().clone(),
1244            |commit| -> Vec<BackendResult<Commit>> {
1245                visited.insert(commit.id().clone());
1246                let mut dependents = vec![];
1247                let parent_ids = new_parents_map
1248                    .get(commit.id())
1249                    .map_or(commit.parent_ids(), |parent_ids| parent_ids);
1250                for parent_id in parent_ids {
1251                    let parent = store.get_commit(parent_id);
1252                    let Ok(parent) = parent else {
1253                        dependents.push(parent);
1254                        continue;
1255                    };
1256                    if let Some(rewrite) = self.parent_mapping.get(parent.id()) {
1257                        for target in rewrite.new_parent_ids() {
1258                            if to_visit_set.contains(target) && !visited.contains(target) {
1259                                dependents.push(store.get_commit(target));
1260                            }
1261                        }
1262                    }
1263                    if to_visit_set.contains(parent.id()) {
1264                        dependents.push(Ok(parent));
1265                    }
1266                }
1267                dependents
1268            },
1269        )
1270    }
1271
1272    /// Rewrite descendants of the given roots.
1273    ///
1274    /// The callback will be called for each commit with the new parents
1275    /// prepopulated. The callback may change the parents and write the new
1276    /// commit, or it may abandon the commit, or it may leave the old commit
1277    /// unchanged.
1278    ///
1279    /// The set of commits to visit is determined at the start. If the callback
1280    /// adds new descendants, then the callback will not be called for those.
1281    /// Similarly, if the callback rewrites unrelated commits, then the callback
1282    /// will not be called for descendants of those commits.
1283    pub fn transform_descendants(
1284        &mut self,
1285        roots: Vec<CommitId>,
1286        callback: impl FnMut(CommitRewriter) -> BackendResult<()>,
1287    ) -> BackendResult<()> {
1288        let options = RewriteRefsOptions::default();
1289        self.transform_descendants_with_options(roots, &HashMap::new(), &options, callback)
1290    }
1291
1292    /// Rewrite descendants of the given roots with options.
1293    ///
1294    /// If a commit is in the `new_parents_map` is provided, it will be rebased
1295    /// onto the new parents provided in the map instead of its original
1296    /// parents.
1297    ///
1298    /// See [`Self::transform_descendants()`] for details.
1299    pub fn transform_descendants_with_options(
1300        &mut self,
1301        roots: Vec<CommitId>,
1302        new_parents_map: &HashMap<CommitId, Vec<CommitId>>,
1303        options: &RewriteRefsOptions,
1304        callback: impl FnMut(CommitRewriter) -> BackendResult<()>,
1305    ) -> BackendResult<()> {
1306        let descendants = self.find_descendants_for_rebase(roots)?;
1307        self.transform_commits(descendants, new_parents_map, options, callback)
1308    }
1309
1310    /// Rewrite the given commits in reverse topological order.
1311    ///
1312    /// `commits` should be a connected range.
1313    ///
1314    /// This function is similar to
1315    /// [`Self::transform_descendants_with_options()`], but only rewrites the
1316    /// `commits` provided, and does not rewrite their descendants.
1317    pub fn transform_commits(
1318        &mut self,
1319        commits: Vec<Commit>,
1320        new_parents_map: &HashMap<CommitId, Vec<CommitId>>,
1321        options: &RewriteRefsOptions,
1322        mut callback: impl FnMut(CommitRewriter) -> BackendResult<()>,
1323    ) -> BackendResult<()> {
1324        let mut to_visit = self.order_commits_for_rebase(commits, new_parents_map)?;
1325        while let Some(old_commit) = to_visit.pop() {
1326            let parent_ids = new_parents_map
1327                .get(old_commit.id())
1328                .map_or(old_commit.parent_ids(), |parent_ids| parent_ids);
1329            let new_parent_ids = self.new_parents(parent_ids);
1330            let rewriter = CommitRewriter::new(self, old_commit, new_parent_ids);
1331            callback(rewriter)?;
1332        }
1333        self.update_rewritten_references(options)?;
1334        // Since we didn't necessarily visit all descendants of rewritten commits (e.g.
1335        // if they were rewritten in the callback), there can still be commits left to
1336        // rebase, so we don't clear `parent_mapping` here.
1337        // TODO: Should we make this stricter? We could check that there were no
1338        // rewrites before this function was called, and we can check that only
1339        // commits in the `to_visit` set were added by the callback. Then we
1340        // could clear `parent_mapping` here and not have to scan it again at
1341        // the end of the transaction when we call `rebase_descendants()`.
1342
1343        Ok(())
1344    }
1345
1346    /// Rebase descendants of the rewritten commits with options and callback.
1347    ///
1348    /// The descendants of the commits registered in `self.parent_mappings` will
1349    /// be recursively rebased onto the new version of their parents.
1350    ///
1351    /// If `options.empty` is the default (`EmptyBehaviour::Keep`), all rebased
1352    /// descendant commits will be preserved even if they were emptied following
1353    /// the rebase operation. Otherwise, this function may rebase some commits
1354    /// and abandon others, based on the given `EmptyBehaviour`. The behavior is
1355    /// such that only commits with a single parent will ever be abandoned. The
1356    /// parent will inherit the descendants and the bookmarks of the abandoned
1357    /// commit.
1358    ///
1359    /// The `progress` callback will be invoked for each rebase operation with
1360    /// `(old_commit, rebased_commit)` as arguments.
1361    pub fn rebase_descendants_with_options(
1362        &mut self,
1363        options: &RebaseOptions,
1364        mut progress: impl FnMut(Commit, RebasedCommit),
1365    ) -> BackendResult<()> {
1366        let roots = self.parent_mapping.keys().cloned().collect();
1367        self.transform_descendants_with_options(
1368            roots,
1369            &HashMap::new(),
1370            &options.rewrite_refs,
1371            |rewriter| {
1372                if rewriter.parents_changed() {
1373                    let old_commit = rewriter.old_commit().clone();
1374                    let rebased_commit = rebase_commit_with_options(rewriter, options)?;
1375                    progress(old_commit, rebased_commit);
1376                }
1377                Ok(())
1378            },
1379        )?;
1380        self.parent_mapping.clear();
1381        Ok(())
1382    }
1383
1384    /// Rebase descendants of the rewritten commits.
1385    ///
1386    /// The descendants of the commits registered in `self.parent_mappings` will
1387    /// be recursively rebased onto the new version of their parents.
1388    /// Returns the number of rebased descendants.
1389    ///
1390    /// All rebased descendant commits will be preserved even if they were
1391    /// emptied following the rebase operation. To customize the rebase
1392    /// behavior, use [`MutableRepo::rebase_descendants_with_options`].
1393    pub fn rebase_descendants(&mut self) -> BackendResult<usize> {
1394        let options = RebaseOptions::default();
1395        let mut num_rebased = 0;
1396        self.rebase_descendants_with_options(&options, |_old_commit, _rebased_commit| {
1397            num_rebased += 1;
1398        })?;
1399        Ok(num_rebased)
1400    }
1401
1402    /// Reparent descendants of the rewritten commits.
1403    ///
1404    /// The descendants of the commits registered in `self.parent_mappings` will
1405    /// be recursively reparented onto the new version of their parents.
1406    /// The content of those descendants will remain untouched.
1407    /// Returns the number of reparented descendants.
1408    pub fn reparent_descendants(&mut self) -> BackendResult<usize> {
1409        let roots = self.parent_mapping.keys().cloned().collect_vec();
1410        let mut num_reparented = 0;
1411        self.transform_descendants(roots, |rewriter| {
1412            if rewriter.parents_changed() {
1413                let builder = rewriter.reparent();
1414                builder.write()?;
1415                num_reparented += 1;
1416            }
1417            Ok(())
1418        })?;
1419        self.parent_mapping.clear();
1420        Ok(num_reparented)
1421    }
1422
1423    pub fn set_wc_commit(
1424        &mut self,
1425        name: WorkspaceNameBuf,
1426        commit_id: CommitId,
1427    ) -> Result<(), RewriteRootCommit> {
1428        if &commit_id == self.store().root_commit_id() {
1429            return Err(RewriteRootCommit);
1430        }
1431        self.view_mut().set_wc_commit(name, commit_id);
1432        Ok(())
1433    }
1434
1435    pub fn remove_wc_commit(&mut self, name: &WorkspaceName) -> Result<(), EditCommitError> {
1436        self.maybe_abandon_wc_commit(name)?;
1437        self.view_mut().remove_wc_commit(name);
1438        Ok(())
1439    }
1440
1441    /// Merges working-copy commit. If there's a conflict, and if the workspace
1442    /// isn't removed at either side, we keep the self side.
1443    fn merge_wc_commit(
1444        &mut self,
1445        name: &WorkspaceName,
1446        base_id: Option<&CommitId>,
1447        other_id: Option<&CommitId>,
1448    ) {
1449        let view = self.view.get_mut();
1450        let self_id = view.get_wc_commit_id(name);
1451        // Not using merge_ref_targets(). Since the working-copy pointer moves
1452        // towards random direction, it doesn't make sense to resolve conflict
1453        // based on ancestry.
1454        let new_id = if let Some(resolved) = trivial_merge(&[self_id, base_id, other_id]) {
1455            resolved.cloned()
1456        } else if self_id.is_none() || other_id.is_none() {
1457            // We want to remove the workspace even if the self side changed the
1458            // working-copy commit.
1459            None
1460        } else {
1461            self_id.cloned()
1462        };
1463        match new_id {
1464            Some(id) => view.set_wc_commit(name.to_owned(), id),
1465            None => view.remove_wc_commit(name),
1466        }
1467    }
1468
1469    pub fn rename_workspace(
1470        &mut self,
1471        old_name: &WorkspaceName,
1472        new_name: WorkspaceNameBuf,
1473    ) -> Result<(), RenameWorkspaceError> {
1474        self.view_mut().rename_workspace(old_name, new_name)
1475    }
1476
1477    pub fn check_out(
1478        &mut self,
1479        name: WorkspaceNameBuf,
1480        commit: &Commit,
1481    ) -> Result<Commit, CheckOutCommitError> {
1482        let wc_commit = self
1483            .new_commit(vec![commit.id().clone()], commit.tree_id().clone())
1484            .write()?;
1485        self.edit(name, &wc_commit)?;
1486        Ok(wc_commit)
1487    }
1488
1489    pub fn edit(&mut self, name: WorkspaceNameBuf, commit: &Commit) -> Result<(), EditCommitError> {
1490        self.maybe_abandon_wc_commit(&name)?;
1491        self.add_head(commit)?;
1492        Ok(self.set_wc_commit(name, commit.id().clone())?)
1493    }
1494
1495    fn maybe_abandon_wc_commit(
1496        &mut self,
1497        workspace_name: &WorkspaceName,
1498    ) -> Result<(), EditCommitError> {
1499        let is_commit_referenced = |view: &View, commit_id: &CommitId| -> bool {
1500            view.wc_commit_ids()
1501                .iter()
1502                .filter(|&(name, _)| name != workspace_name)
1503                .map(|(_, wc_id)| wc_id)
1504                .chain(
1505                    view.local_bookmarks()
1506                        .flat_map(|(_, target)| target.added_ids()),
1507                )
1508                .any(|id| id == commit_id)
1509        };
1510
1511        let maybe_wc_commit_id = self
1512            .view
1513            .with_ref(|v| v.get_wc_commit_id(workspace_name).cloned());
1514        if let Some(wc_commit_id) = maybe_wc_commit_id {
1515            let wc_commit = self
1516                .store()
1517                .get_commit(&wc_commit_id)
1518                .map_err(EditCommitError::WorkingCopyCommitNotFound)?;
1519            if wc_commit.is_discardable(self)?
1520                && self
1521                    .view
1522                    .with_ref(|v| !is_commit_referenced(v, wc_commit.id()))
1523                && self.view().heads().contains(wc_commit.id())
1524            {
1525                // Abandon the working-copy commit we're leaving if it's
1526                // discardable, not pointed by local bookmark or other working
1527                // copies, and a head commit.
1528                self.record_abandoned_commit(&wc_commit);
1529            }
1530        }
1531
1532        Ok(())
1533    }
1534
1535    fn enforce_view_invariants(&self, view: &mut View) {
1536        let view = view.store_view_mut();
1537        let root_commit_id = self.store().root_commit_id();
1538        if view.head_ids.is_empty() {
1539            view.head_ids.insert(root_commit_id.clone());
1540        } else if view.head_ids.len() > 1 {
1541            // An empty head_ids set is padded with the root_commit_id, but the
1542            // root id is unwanted during the heads resolution.
1543            view.head_ids.remove(root_commit_id);
1544            // It is unclear if `heads` can never fail for default implementation,
1545            // but it can definitely fail for non-default implementations.
1546            // TODO: propagate errors.
1547            view.head_ids = self
1548                .index()
1549                .heads(&mut view.head_ids.iter())
1550                .unwrap()
1551                .into_iter()
1552                .collect();
1553        }
1554        assert!(!view.head_ids.is_empty());
1555    }
1556
1557    /// Ensures that the given `head` and ancestor commits are reachable from
1558    /// the visible heads.
1559    pub fn add_head(&mut self, head: &Commit) -> BackendResult<()> {
1560        self.add_heads(slice::from_ref(head))
1561    }
1562
1563    /// Ensures that the given `heads` and ancestor commits are reachable from
1564    /// the visible heads.
1565    ///
1566    /// The `heads` may contain redundant commits such as already visible ones
1567    /// and ancestors of the other heads. The `heads` and ancestor commits
1568    /// should exist in the store.
1569    pub fn add_heads(&mut self, heads: &[Commit]) -> BackendResult<()> {
1570        let current_heads = self.view.get_mut().heads();
1571        // Use incremental update for common case of adding a single commit on top a
1572        // current head. TODO: Also use incremental update when adding a single
1573        // commit on top a non-head.
1574        match heads {
1575            [] => {}
1576            [head]
1577                if head
1578                    .parent_ids()
1579                    .iter()
1580                    .all(|parent_id| current_heads.contains(parent_id)) =>
1581            {
1582                self.index.add_commit(head);
1583                self.view.get_mut().add_head(head.id());
1584                for parent_id in head.parent_ids() {
1585                    self.view.get_mut().remove_head(parent_id);
1586                }
1587            }
1588            _ => {
1589                let missing_commits = dag_walk::topo_order_reverse_ord_ok(
1590                    heads
1591                        .iter()
1592                        .cloned()
1593                        .map(CommitByCommitterTimestamp)
1594                        .map(Ok),
1595                    |CommitByCommitterTimestamp(commit)| commit.id().clone(),
1596                    |CommitByCommitterTimestamp(commit)| {
1597                        commit
1598                            .parent_ids()
1599                            .iter()
1600                            .filter(|id| !self.index().has_id(id))
1601                            .map(|id| self.store().get_commit(id))
1602                            .map_ok(CommitByCommitterTimestamp)
1603                            .collect_vec()
1604                    },
1605                )?;
1606                for CommitByCommitterTimestamp(missing_commit) in missing_commits.iter().rev() {
1607                    self.index.add_commit(missing_commit);
1608                }
1609                for head in heads {
1610                    self.view.get_mut().add_head(head.id());
1611                }
1612                self.view.mark_dirty();
1613            }
1614        }
1615        Ok(())
1616    }
1617
1618    pub fn remove_head(&mut self, head: &CommitId) {
1619        self.view_mut().remove_head(head);
1620        self.view.mark_dirty();
1621    }
1622
1623    pub fn get_local_bookmark(&self, name: &RefName) -> RefTarget {
1624        self.view.with_ref(|v| v.get_local_bookmark(name).clone())
1625    }
1626
1627    pub fn set_local_bookmark_target(&mut self, name: &RefName, target: RefTarget) {
1628        let view = self.view_mut();
1629        for id in target.added_ids() {
1630            view.add_head(id);
1631        }
1632        view.set_local_bookmark_target(name, target);
1633        self.view.mark_dirty();
1634    }
1635
1636    pub fn merge_local_bookmark(
1637        &mut self,
1638        name: &RefName,
1639        base_target: &RefTarget,
1640        other_target: &RefTarget,
1641    ) {
1642        let view = self.view.get_mut();
1643        let index = self.index.as_index();
1644        let self_target = view.get_local_bookmark(name);
1645        let new_target = merge_ref_targets(index, self_target, base_target, other_target);
1646        self.set_local_bookmark_target(name, new_target);
1647    }
1648
1649    pub fn get_remote_bookmark(&self, symbol: RemoteRefSymbol<'_>) -> RemoteRef {
1650        self.view
1651            .with_ref(|v| v.get_remote_bookmark(symbol).clone())
1652    }
1653
1654    pub fn set_remote_bookmark(&mut self, symbol: RemoteRefSymbol<'_>, remote_ref: RemoteRef) {
1655        self.view_mut().set_remote_bookmark(symbol, remote_ref);
1656    }
1657
1658    fn merge_remote_bookmark(
1659        &mut self,
1660        symbol: RemoteRefSymbol<'_>,
1661        base_ref: &RemoteRef,
1662        other_ref: &RemoteRef,
1663    ) {
1664        let view = self.view.get_mut();
1665        let index = self.index.as_index();
1666        let self_ref = view.get_remote_bookmark(symbol);
1667        let new_ref = merge_remote_refs(index, self_ref, base_ref, other_ref);
1668        view.set_remote_bookmark(symbol, new_ref);
1669    }
1670
1671    /// Merges the specified remote bookmark in to local bookmark, and starts
1672    /// tracking it.
1673    pub fn track_remote_bookmark(&mut self, symbol: RemoteRefSymbol<'_>) {
1674        let mut remote_ref = self.get_remote_bookmark(symbol);
1675        let base_target = remote_ref.tracked_target();
1676        self.merge_local_bookmark(symbol.name, base_target, &remote_ref.target);
1677        remote_ref.state = RemoteRefState::Tracked;
1678        self.set_remote_bookmark(symbol, remote_ref);
1679    }
1680
1681    /// Stops tracking the specified remote bookmark.
1682    pub fn untrack_remote_bookmark(&mut self, symbol: RemoteRefSymbol<'_>) {
1683        let mut remote_ref = self.get_remote_bookmark(symbol);
1684        remote_ref.state = RemoteRefState::New;
1685        self.set_remote_bookmark(symbol, remote_ref);
1686    }
1687
1688    pub fn remove_remote(&mut self, remote_name: &RemoteName) {
1689        self.view_mut().remove_remote(remote_name);
1690    }
1691
1692    pub fn rename_remote(&mut self, old: &RemoteName, new: &RemoteName) {
1693        self.view_mut().rename_remote(old, new);
1694    }
1695
1696    pub fn get_tag(&self, name: &RefName) -> RefTarget {
1697        self.view.with_ref(|v| v.get_tag(name).clone())
1698    }
1699
1700    pub fn set_tag_target(&mut self, name: &RefName, target: RefTarget) {
1701        self.view_mut().set_tag_target(name, target);
1702    }
1703
1704    pub fn merge_tag(&mut self, name: &RefName, base_target: &RefTarget, other_target: &RefTarget) {
1705        let view = self.view.get_mut();
1706        let index = self.index.as_index();
1707        let self_target = view.get_tag(name);
1708        let new_target = merge_ref_targets(index, self_target, base_target, other_target);
1709        view.set_tag_target(name, new_target);
1710    }
1711
1712    pub fn get_git_ref(&self, name: &GitRefName) -> RefTarget {
1713        self.view.with_ref(|v| v.get_git_ref(name).clone())
1714    }
1715
1716    pub fn set_git_ref_target(&mut self, name: &GitRefName, target: RefTarget) {
1717        self.view_mut().set_git_ref_target(name, target);
1718    }
1719
1720    fn merge_git_ref(
1721        &mut self,
1722        name: &GitRefName,
1723        base_target: &RefTarget,
1724        other_target: &RefTarget,
1725    ) {
1726        let view = self.view.get_mut();
1727        let index = self.index.as_index();
1728        let self_target = view.get_git_ref(name);
1729        let new_target = merge_ref_targets(index, self_target, base_target, other_target);
1730        view.set_git_ref_target(name, new_target);
1731    }
1732
1733    pub fn git_head(&self) -> RefTarget {
1734        self.view.with_ref(|v| v.git_head().clone())
1735    }
1736
1737    pub fn set_git_head_target(&mut self, target: RefTarget) {
1738        self.view_mut().set_git_head_target(target);
1739    }
1740
1741    pub fn set_view(&mut self, data: op_store::View) {
1742        self.view_mut().set_view(data);
1743        self.view.mark_dirty();
1744    }
1745
1746    pub fn merge(
1747        &mut self,
1748        base_repo: &ReadonlyRepo,
1749        other_repo: &ReadonlyRepo,
1750    ) -> BackendResult<()> {
1751        // First, merge the index, so we can take advantage of a valid index when
1752        // merging the view. Merging in base_repo's index isn't typically
1753        // necessary, but it can be if base_repo is ahead of either self or other_repo
1754        // (e.g. because we're undoing an operation that hasn't been published).
1755        self.index.merge_in(base_repo.readonly_index());
1756        self.index.merge_in(other_repo.readonly_index());
1757
1758        self.view.ensure_clean(|v| self.enforce_view_invariants(v));
1759        self.merge_view(&base_repo.view, &other_repo.view)?;
1760        self.view.mark_dirty();
1761        Ok(())
1762    }
1763
1764    pub fn merge_index(&mut self, other_repo: &ReadonlyRepo) {
1765        self.index.merge_in(other_repo.readonly_index());
1766    }
1767
1768    fn merge_view(&mut self, base: &View, other: &View) -> BackendResult<()> {
1769        let changed_wc_commits = diff_named_commit_ids(base.wc_commit_ids(), other.wc_commit_ids());
1770        for (name, (base_id, other_id)) in changed_wc_commits {
1771            self.merge_wc_commit(name, base_id, other_id);
1772        }
1773
1774        let base_heads = base.heads().iter().cloned().collect_vec();
1775        let own_heads = self.view().heads().iter().cloned().collect_vec();
1776        let other_heads = other.heads().iter().cloned().collect_vec();
1777
1778        // HACK: Don't walk long ranges of commits to find rewrites when using other
1779        // custom implementations. The only custom index implementation we're currently
1780        // aware of is Google's. That repo has too high commit rate for it to be
1781        // feasible to walk all added and removed commits.
1782        // TODO: Fix this somehow. Maybe a method on `Index` to find rewritten commits
1783        // given `base_heads`, `own_heads` and `other_heads`?
1784        if self.index.as_any().is::<DefaultMutableIndex>() {
1785            self.record_rewrites(&base_heads, &own_heads)?;
1786            self.record_rewrites(&base_heads, &other_heads)?;
1787            // No need to remove heads removed by `other` because we already
1788            // marked them abandoned or rewritten.
1789        } else {
1790            for removed_head in base.heads().difference(other.heads()) {
1791                self.view_mut().remove_head(removed_head);
1792            }
1793        }
1794        for added_head in other.heads().difference(base.heads()) {
1795            self.view_mut().add_head(added_head);
1796        }
1797
1798        let changed_local_bookmarks =
1799            diff_named_ref_targets(base.local_bookmarks(), other.local_bookmarks());
1800        for (name, (base_target, other_target)) in changed_local_bookmarks {
1801            self.merge_local_bookmark(name, base_target, other_target);
1802        }
1803
1804        let changed_tags = diff_named_ref_targets(base.tags(), other.tags());
1805        for (name, (base_target, other_target)) in changed_tags {
1806            self.merge_tag(name, base_target, other_target);
1807        }
1808
1809        let changed_git_refs = diff_named_ref_targets(base.git_refs(), other.git_refs());
1810        for (name, (base_target, other_target)) in changed_git_refs {
1811            self.merge_git_ref(name, base_target, other_target);
1812        }
1813
1814        let changed_remote_bookmarks =
1815            diff_named_remote_refs(base.all_remote_bookmarks(), other.all_remote_bookmarks());
1816        for (symbol, (base_ref, other_ref)) in changed_remote_bookmarks {
1817            self.merge_remote_bookmark(symbol, base_ref, other_ref);
1818        }
1819
1820        let new_git_head_target = merge_ref_targets(
1821            self.index(),
1822            self.view().git_head(),
1823            base.git_head(),
1824            other.git_head(),
1825        );
1826        self.set_git_head_target(new_git_head_target);
1827
1828        Ok(())
1829    }
1830
1831    /// Finds and records commits that were rewritten or abandoned between
1832    /// `old_heads` and `new_heads`.
1833    fn record_rewrites(
1834        &mut self,
1835        old_heads: &[CommitId],
1836        new_heads: &[CommitId],
1837    ) -> BackendResult<()> {
1838        let mut removed_changes: HashMap<ChangeId, Vec<CommitId>> = HashMap::new();
1839        for item in revset::walk_revs(self, old_heads, new_heads)
1840            .map_err(|err| err.into_backend_error())?
1841            .commit_change_ids()
1842        {
1843            let (commit_id, change_id) = item.map_err(|err| err.into_backend_error())?;
1844            removed_changes
1845                .entry(change_id)
1846                .or_default()
1847                .push(commit_id);
1848        }
1849        if removed_changes.is_empty() {
1850            return Ok(());
1851        }
1852
1853        let mut rewritten_changes = HashSet::new();
1854        let mut rewritten_commits: HashMap<CommitId, Vec<CommitId>> = HashMap::new();
1855        for item in revset::walk_revs(self, new_heads, old_heads)
1856            .map_err(|err| err.into_backend_error())?
1857            .commit_change_ids()
1858        {
1859            let (commit_id, change_id) = item.map_err(|err| err.into_backend_error())?;
1860            if let Some(old_commits) = removed_changes.get(&change_id) {
1861                for old_commit in old_commits {
1862                    rewritten_commits
1863                        .entry(old_commit.clone())
1864                        .or_default()
1865                        .push(commit_id.clone());
1866                }
1867            }
1868            rewritten_changes.insert(change_id);
1869        }
1870        for (old_commit, new_commits) in rewritten_commits {
1871            if new_commits.len() == 1 {
1872                self.set_rewritten_commit(
1873                    old_commit.clone(),
1874                    new_commits.into_iter().next().unwrap(),
1875                );
1876            } else {
1877                self.set_divergent_rewrite(old_commit.clone(), new_commits);
1878            }
1879        }
1880
1881        for (change_id, removed_commit_ids) in &removed_changes {
1882            if !rewritten_changes.contains(change_id) {
1883                for id in removed_commit_ids {
1884                    let commit = self.store().get_commit(id)?;
1885                    self.record_abandoned_commit(&commit);
1886                }
1887            }
1888        }
1889
1890        Ok(())
1891    }
1892}
1893
1894impl Repo for MutableRepo {
1895    fn base_repo(&self) -> &ReadonlyRepo {
1896        &self.base_repo
1897    }
1898
1899    fn store(&self) -> &Arc<Store> {
1900        self.base_repo.store()
1901    }
1902
1903    fn op_store(&self) -> &Arc<dyn OpStore> {
1904        self.base_repo.op_store()
1905    }
1906
1907    fn index(&self) -> &dyn Index {
1908        self.index.as_index()
1909    }
1910
1911    fn view(&self) -> &View {
1912        self.view
1913            .get_or_ensure_clean(|v| self.enforce_view_invariants(v))
1914    }
1915
1916    fn submodule_store(&self) -> &Arc<dyn SubmoduleStore> {
1917        self.base_repo.submodule_store()
1918    }
1919
1920    fn resolve_change_id_prefix(&self, prefix: &HexPrefix) -> PrefixResolution<Vec<CommitId>> {
1921        let change_id_index = self.index.change_id_index(&mut self.view().heads().iter());
1922        change_id_index.resolve_prefix(prefix)
1923    }
1924
1925    fn shortest_unique_change_id_prefix_len(&self, target_id: &ChangeId) -> usize {
1926        let change_id_index = self.index.change_id_index(&mut self.view().heads().iter());
1927        change_id_index.shortest_unique_prefix_len(target_id)
1928    }
1929}
1930
1931/// Error from attempts to check out the root commit for editing
1932#[derive(Debug, Error)]
1933#[error("Cannot rewrite the root commit")]
1934pub struct RewriteRootCommit;
1935
1936/// Error from attempts to edit a commit
1937#[derive(Debug, Error)]
1938pub enum EditCommitError {
1939    #[error("Current working-copy commit not found")]
1940    WorkingCopyCommitNotFound(#[source] BackendError),
1941    #[error(transparent)]
1942    RewriteRootCommit(#[from] RewriteRootCommit),
1943    #[error(transparent)]
1944    BackendError(#[from] BackendError),
1945}
1946
1947/// Error from attempts to check out a commit
1948#[derive(Debug, Error)]
1949pub enum CheckOutCommitError {
1950    #[error("Failed to create new working-copy commit")]
1951    CreateCommit(#[from] BackendError),
1952    #[error("Failed to edit commit")]
1953    EditCommit(#[from] EditCommitError),
1954}
1955
1956mod dirty_cell {
1957    use std::cell::OnceCell;
1958    use std::cell::RefCell;
1959
1960    /// Cell that lazily updates the value after `mark_dirty()`.
1961    ///
1962    /// A clean value can be immutably borrowed within the `self` lifetime.
1963    #[derive(Clone, Debug)]
1964    pub struct DirtyCell<T> {
1965        // Either clean or dirty value is set. The value is boxed to reduce stack space
1966        // and memcopy overhead.
1967        clean: OnceCell<Box<T>>,
1968        dirty: RefCell<Option<Box<T>>>,
1969    }
1970
1971    impl<T> DirtyCell<T> {
1972        pub fn with_clean(value: T) -> Self {
1973            DirtyCell {
1974                clean: OnceCell::from(Box::new(value)),
1975                dirty: RefCell::new(None),
1976            }
1977        }
1978
1979        pub fn get_or_ensure_clean(&self, f: impl FnOnce(&mut T)) -> &T {
1980            self.clean.get_or_init(|| {
1981                // Panics if ensure_clean() is invoked from with_ref() callback for example.
1982                let mut value = self.dirty.borrow_mut().take().unwrap();
1983                f(&mut value);
1984                value
1985            })
1986        }
1987
1988        pub fn ensure_clean(&self, f: impl FnOnce(&mut T)) {
1989            self.get_or_ensure_clean(f);
1990        }
1991
1992        pub fn into_inner(self) -> T {
1993            *self
1994                .clean
1995                .into_inner()
1996                .or_else(|| self.dirty.into_inner())
1997                .unwrap()
1998        }
1999
2000        pub fn with_ref<R>(&self, f: impl FnOnce(&T) -> R) -> R {
2001            if let Some(value) = self.clean.get() {
2002                f(value)
2003            } else {
2004                f(self.dirty.borrow().as_ref().unwrap())
2005            }
2006        }
2007
2008        pub fn get_mut(&mut self) -> &mut T {
2009            self.clean
2010                .get_mut()
2011                .or_else(|| self.dirty.get_mut().as_mut())
2012                .unwrap()
2013        }
2014
2015        pub fn mark_dirty(&mut self) {
2016            if let Some(value) = self.clean.take() {
2017                *self.dirty.get_mut() = Some(value);
2018            }
2019        }
2020    }
2021}