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