manifest_tree.rs

  1//! This module defines a Manifest Tree.
  2//!
  3//! A Manifest Tree is responsible for determining where the manifests for subprojects are located in a project.
  4//! This then is used to provide those locations to language servers & determine locations eligible for toolchain selection.
  5
  6mod manifest_store;
  7mod path_trie;
  8mod server_tree;
  9
 10use std::{borrow::Borrow, collections::hash_map::Entry, ops::ControlFlow, path::Path, sync::Arc};
 11
 12use collections::HashMap;
 13use gpui::{App, AppContext as _, Context, Entity, Subscription};
 14use language::{ManifestDelegate, ManifestName, ManifestQuery};
 15pub use manifest_store::ManifestProvidersStore;
 16use path_trie::{LabelPresence, RootPathTrie, TriePath};
 17use settings::{SettingsStore, WorktreeId};
 18use worktree::{Event as WorktreeEvent, Snapshot, Worktree};
 19
 20use crate::{
 21    ProjectPath,
 22    worktree_store::{WorktreeStore, WorktreeStoreEvent},
 23};
 24
 25pub(crate) use server_tree::{LanguageServerTree, LanguageServerTreeNode, LaunchDisposition};
 26
 27struct WorktreeRoots {
 28    roots: RootPathTrie<ManifestName>,
 29    worktree_store: Entity<WorktreeStore>,
 30    _worktree_subscription: Subscription,
 31}
 32
 33impl WorktreeRoots {
 34    fn new(
 35        worktree_store: Entity<WorktreeStore>,
 36        worktree: Entity<Worktree>,
 37        cx: &mut App,
 38    ) -> Entity<Self> {
 39        cx.new(|cx| Self {
 40            roots: RootPathTrie::new(),
 41            worktree_store,
 42            _worktree_subscription: cx.subscribe(&worktree, |this: &mut Self, _, event, cx| {
 43                match event {
 44                    WorktreeEvent::UpdatedEntries(changes) => {
 45                        for (path, _, kind) in changes.iter() {
 46                            match kind {
 47                                worktree::PathChange::Removed => {
 48                                    let path = TriePath::from(path.as_ref());
 49                                    this.roots.remove(&path);
 50                                }
 51                                _ => {}
 52                            }
 53                        }
 54                    }
 55                    WorktreeEvent::UpdatedGitRepositories(_) => {}
 56                    WorktreeEvent::DeletedEntry(entry_id) => {
 57                        let Some(entry) = this.worktree_store.read(cx).entry_for_id(*entry_id, cx)
 58                        else {
 59                            return;
 60                        };
 61                        let path = TriePath::from(entry.path.as_ref());
 62                        this.roots.remove(&path);
 63                    }
 64                }
 65            }),
 66        })
 67    }
 68}
 69
 70pub struct ManifestTree {
 71    root_points: HashMap<WorktreeId, Entity<WorktreeRoots>>,
 72    worktree_store: Entity<WorktreeStore>,
 73    _subscriptions: [Subscription; 2],
 74}
 75
 76impl ManifestTree {
 77    pub fn new(worktree_store: Entity<WorktreeStore>, cx: &mut App) -> Entity<Self> {
 78        cx.new(|cx| Self {
 79            root_points: Default::default(),
 80            _subscriptions: [
 81                cx.subscribe(&worktree_store, Self::on_worktree_store_event),
 82                cx.observe_global::<SettingsStore>(|this, cx| {
 83                    for (_, roots) in &mut this.root_points {
 84                        roots.update(cx, |worktree_roots, _| {
 85                            worktree_roots.roots = RootPathTrie::new();
 86                        })
 87                    }
 88                }),
 89            ],
 90            worktree_store,
 91        })
 92    }
 93
 94    pub(crate) fn root_for_path(
 95        &mut self,
 96        ProjectPath { worktree_id, path }: &ProjectPath,
 97        manifest_name: &ManifestName,
 98        delegate: &Arc<dyn ManifestDelegate>,
 99        cx: &mut App,
100    ) -> Option<ProjectPath> {
101        debug_assert_eq!(delegate.worktree_id(), *worktree_id);
102        let (mut marked_path, mut current_presence) = (None, LabelPresence::KnownAbsent);
103        let worktree_roots = match self.root_points.entry(*worktree_id) {
104            Entry::Occupied(occupied_entry) => occupied_entry.get().clone(),
105            Entry::Vacant(vacant_entry) => {
106                let Some(worktree) = self
107                    .worktree_store
108                    .read(cx)
109                    .worktree_for_id(*worktree_id, cx)
110                else {
111                    return Default::default();
112                };
113                let roots = WorktreeRoots::new(self.worktree_store.clone(), worktree, cx);
114                vacant_entry.insert(roots).clone()
115            }
116        };
117
118        let key = TriePath::from(&**path);
119        worktree_roots.read_with(cx, |this, _| {
120            this.roots.walk(&key, &mut |path, labels| {
121                for (label, presence) in labels {
122                    if label == manifest_name {
123                        if current_presence > *presence {
124                            debug_assert!(false, "RootPathTrie precondition violation; while walking the tree label presence is only allowed to increase");
125                        }
126                        marked_path = Some(ProjectPath {worktree_id: *worktree_id, path: path.clone()});
127                        current_presence = *presence;
128                    }
129
130                }
131                ControlFlow::Continue(())
132            });
133        });
134
135        if current_presence == LabelPresence::KnownAbsent {
136            // Some part of the path is unexplored.
137            let depth = marked_path
138                .as_ref()
139                .map(|root_path| {
140                    path.strip_prefix(&root_path.path)
141                        .unwrap()
142                        .components()
143                        .count()
144                })
145                .unwrap_or_else(|| path.components().count() + 1);
146
147            if depth > 0
148                && let Some(provider) =
149                    ManifestProvidersStore::global(cx).get(manifest_name.borrow())
150            {
151                let root = provider.search(ManifestQuery {
152                    path: path.clone(),
153                    depth,
154                    delegate: delegate.clone(),
155                });
156                match root {
157                    Some(known_root) => worktree_roots.update(cx, |this, _| {
158                        let root = TriePath::from(&*known_root);
159                        this.roots
160                            .insert(&root, manifest_name.clone(), LabelPresence::Present);
161                        current_presence = LabelPresence::Present;
162                        marked_path = Some(ProjectPath {
163                            worktree_id: *worktree_id,
164                            path: known_root,
165                        });
166                    }),
167                    None => worktree_roots.update(cx, |this, _| {
168                        this.roots
169                            .insert(&key, manifest_name.clone(), LabelPresence::KnownAbsent);
170                    }),
171                }
172            }
173        }
174        marked_path.filter(|_| current_presence.eq(&LabelPresence::Present))
175    }
176
177    pub(crate) fn root_for_path_or_worktree_root(
178        &mut self,
179        project_path: &ProjectPath,
180        manifest_name: Option<&ManifestName>,
181        delegate: &Arc<dyn ManifestDelegate>,
182        cx: &mut App,
183    ) -> ProjectPath {
184        let worktree_id = project_path.worktree_id;
185        // Backwards-compat: Fill in any adapters for which we did not detect the root as having the project root at the root of a worktree.
186        manifest_name
187            .and_then(|manifest_name| self.root_for_path(project_path, manifest_name, delegate, cx))
188            .unwrap_or_else(|| ProjectPath {
189                worktree_id,
190                path: Arc::from(Path::new("")),
191            })
192    }
193
194    fn on_worktree_store_event(
195        &mut self,
196        _: Entity<WorktreeStore>,
197        evt: &WorktreeStoreEvent,
198        _: &mut Context<Self>,
199    ) {
200        match evt {
201            WorktreeStoreEvent::WorktreeRemoved(_, worktree_id) => {
202                self.root_points.remove(worktree_id);
203            }
204            _ => {}
205        }
206    }
207}
208
209pub(crate) struct ManifestQueryDelegate {
210    worktree: Snapshot,
211}
212
213impl ManifestQueryDelegate {
214    pub fn new(worktree: Snapshot) -> Self {
215        Self { worktree }
216    }
217}
218
219impl ManifestDelegate for ManifestQueryDelegate {
220    fn exists(&self, path: &Path, is_dir: Option<bool>) -> bool {
221        self.worktree.entry_for_path(path).map_or(false, |entry| {
222            is_dir.map_or(true, |is_required_to_be_dir| {
223                is_required_to_be_dir == entry.is_dir()
224            })
225        })
226    }
227
228    fn worktree_id(&self) -> WorktreeId {
229        self.worktree.id()
230    }
231}