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