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