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