1use anyhow::{anyhow, Context as _, Result};
2use extension::ExtensionHostProxy;
3use extension_host::headless_host::HeadlessExtensionStore;
4use fs::{CreateOptions, Fs};
5use git::{repository::RepoPath, COMMIT_MESSAGE};
6use gpui::{App, AppContext as _, AsyncApp, Context, Entity, PromptLevel, SharedString};
7use http_client::HttpClient;
8use language::{proto::serialize_operation, Buffer, BufferEvent, LanguageRegistry};
9use node_runtime::NodeRuntime;
10use project::{
11 buffer_store::{BufferStore, BufferStoreEvent},
12 git::{GitRepo, GitState, RepositoryHandle},
13 project_settings::SettingsObserver,
14 search::SearchQuery,
15 task_store::TaskStore,
16 worktree_store::WorktreeStore,
17 LspStore, LspStoreEvent, PrettierStore, ProjectEntryId, ProjectPath, ToolchainStore,
18 WorktreeId,
19};
20use remote::ssh_session::ChannelClient;
21use rpc::{
22 proto::{self, SSH_PEER_ID, SSH_PROJECT_ID},
23 AnyProtoClient, TypedEnvelope,
24};
25
26use settings::initial_server_settings_content;
27use smol::stream::StreamExt;
28use std::{
29 path::{Path, PathBuf},
30 sync::{atomic::AtomicUsize, Arc},
31};
32use util::ResultExt;
33use worktree::Worktree;
34
35pub struct HeadlessProject {
36 pub fs: Arc<dyn Fs>,
37 pub session: AnyProtoClient,
38 pub worktree_store: Entity<WorktreeStore>,
39 pub buffer_store: Entity<BufferStore>,
40 pub lsp_store: Entity<LspStore>,
41 pub task_store: Entity<TaskStore>,
42 pub settings_observer: Entity<SettingsObserver>,
43 pub next_entry_id: Arc<AtomicUsize>,
44 pub languages: Arc<LanguageRegistry>,
45 pub extensions: Entity<HeadlessExtensionStore>,
46 pub git_state: Entity<GitState>,
47}
48
49pub struct HeadlessAppState {
50 pub session: Arc<ChannelClient>,
51 pub fs: Arc<dyn Fs>,
52 pub http_client: Arc<dyn HttpClient>,
53 pub node_runtime: NodeRuntime,
54 pub languages: Arc<LanguageRegistry>,
55 pub extension_host_proxy: Arc<ExtensionHostProxy>,
56}
57
58impl HeadlessProject {
59 pub fn init(cx: &mut App) {
60 settings::init(cx);
61 language::init(cx);
62 project::Project::init_settings(cx);
63 }
64
65 pub fn new(
66 HeadlessAppState {
67 session,
68 fs,
69 http_client,
70 node_runtime,
71 languages,
72 extension_host_proxy: proxy,
73 }: HeadlessAppState,
74 cx: &mut Context<Self>,
75 ) -> Self {
76 language_extension::init(proxy.clone(), languages.clone());
77 languages::init(languages.clone(), node_runtime.clone(), cx);
78
79 let worktree_store = cx.new(|cx| {
80 let mut store = WorktreeStore::local(true, fs.clone());
81 store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
82 store
83 });
84
85 let git_state = cx.new(|cx| GitState::new(&worktree_store, None, None, cx));
86
87 let buffer_store = cx.new(|cx| {
88 let mut buffer_store = BufferStore::local(worktree_store.clone(), cx);
89 buffer_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
90 buffer_store
91 });
92 let prettier_store = cx.new(|cx| {
93 PrettierStore::new(
94 node_runtime.clone(),
95 fs.clone(),
96 languages.clone(),
97 worktree_store.clone(),
98 cx,
99 )
100 });
101 let environment = project::ProjectEnvironment::new(&worktree_store, None, cx);
102 let toolchain_store = cx.new(|cx| {
103 ToolchainStore::local(
104 languages.clone(),
105 worktree_store.clone(),
106 environment.clone(),
107 cx,
108 )
109 });
110
111 let task_store = cx.new(|cx| {
112 let mut task_store = TaskStore::local(
113 fs.clone(),
114 buffer_store.downgrade(),
115 worktree_store.clone(),
116 toolchain_store.read(cx).as_language_toolchain_store(),
117 environment.clone(),
118 cx,
119 );
120 task_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
121 task_store
122 });
123 let settings_observer = cx.new(|cx| {
124 let mut observer = SettingsObserver::new_local(
125 fs.clone(),
126 worktree_store.clone(),
127 task_store.clone(),
128 cx,
129 );
130 observer.shared(SSH_PROJECT_ID, session.clone().into(), cx);
131 observer
132 });
133
134 let lsp_store = cx.new(|cx| {
135 let mut lsp_store = LspStore::new_local(
136 buffer_store.clone(),
137 worktree_store.clone(),
138 prettier_store.clone(),
139 toolchain_store.clone(),
140 environment,
141 languages.clone(),
142 http_client.clone(),
143 fs.clone(),
144 cx,
145 );
146 lsp_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
147 lsp_store
148 });
149
150 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
151
152 cx.subscribe(
153 &buffer_store,
154 |_this, _buffer_store, event, cx| match event {
155 BufferStoreEvent::BufferAdded(buffer) => {
156 cx.subscribe(buffer, Self::on_buffer_event).detach();
157 }
158 _ => {}
159 },
160 )
161 .detach();
162
163 let extensions = HeadlessExtensionStore::new(
164 fs.clone(),
165 http_client.clone(),
166 paths::remote_extensions_dir().to_path_buf(),
167 proxy,
168 node_runtime,
169 cx,
170 );
171
172 let client: AnyProtoClient = session.clone().into();
173
174 // local_machine -> ssh handlers
175 session.subscribe_to_entity(SSH_PROJECT_ID, &worktree_store);
176 session.subscribe_to_entity(SSH_PROJECT_ID, &buffer_store);
177 session.subscribe_to_entity(SSH_PROJECT_ID, &cx.entity());
178 session.subscribe_to_entity(SSH_PROJECT_ID, &lsp_store);
179 session.subscribe_to_entity(SSH_PROJECT_ID, &task_store);
180 session.subscribe_to_entity(SSH_PROJECT_ID, &toolchain_store);
181 session.subscribe_to_entity(SSH_PROJECT_ID, &settings_observer);
182
183 client.add_request_handler(cx.weak_entity(), Self::handle_list_remote_directory);
184 client.add_request_handler(cx.weak_entity(), Self::handle_get_path_metadata);
185 client.add_request_handler(cx.weak_entity(), Self::handle_shutdown_remote_server);
186 client.add_request_handler(cx.weak_entity(), Self::handle_ping);
187
188 client.add_model_request_handler(Self::handle_add_worktree);
189 client.add_request_handler(cx.weak_entity(), Self::handle_remove_worktree);
190
191 client.add_model_request_handler(Self::handle_open_buffer_by_path);
192 client.add_model_request_handler(Self::handle_open_new_buffer);
193 client.add_model_request_handler(Self::handle_find_search_candidates);
194 client.add_model_request_handler(Self::handle_open_server_settings);
195
196 client.add_model_request_handler(BufferStore::handle_update_buffer);
197 client.add_model_message_handler(BufferStore::handle_close_buffer);
198
199 client.add_model_request_handler(Self::handle_stage);
200 client.add_model_request_handler(Self::handle_unstage);
201 client.add_model_request_handler(Self::handle_commit);
202 client.add_model_request_handler(Self::handle_open_commit_message_buffer);
203
204 client.add_request_handler(
205 extensions.clone().downgrade(),
206 HeadlessExtensionStore::handle_sync_extensions,
207 );
208 client.add_request_handler(
209 extensions.clone().downgrade(),
210 HeadlessExtensionStore::handle_install_extension,
211 );
212
213 BufferStore::init(&client);
214 WorktreeStore::init(&client);
215 SettingsObserver::init(&client);
216 LspStore::init(&client);
217 TaskStore::init(Some(&client));
218 ToolchainStore::init(&client);
219
220 HeadlessProject {
221 session: client,
222 settings_observer,
223 fs,
224 worktree_store,
225 buffer_store,
226 lsp_store,
227 task_store,
228 next_entry_id: Default::default(),
229 languages,
230 extensions,
231 git_state,
232 }
233 }
234
235 fn on_buffer_event(
236 &mut self,
237 buffer: Entity<Buffer>,
238 event: &BufferEvent,
239 cx: &mut Context<Self>,
240 ) {
241 match event {
242 BufferEvent::Operation {
243 operation,
244 is_local: true,
245 } => cx
246 .background_executor()
247 .spawn(self.session.request(proto::UpdateBuffer {
248 project_id: SSH_PROJECT_ID,
249 buffer_id: buffer.read(cx).remote_id().to_proto(),
250 operations: vec![serialize_operation(operation)],
251 }))
252 .detach(),
253 _ => {}
254 }
255 }
256
257 fn on_lsp_store_event(
258 &mut self,
259 _lsp_store: Entity<LspStore>,
260 event: &LspStoreEvent,
261 cx: &mut Context<Self>,
262 ) {
263 match event {
264 LspStoreEvent::LanguageServerUpdate {
265 language_server_id,
266 message,
267 } => {
268 self.session
269 .send(proto::UpdateLanguageServer {
270 project_id: SSH_PROJECT_ID,
271 language_server_id: language_server_id.to_proto(),
272 variant: Some(message.clone()),
273 })
274 .log_err();
275 }
276 LspStoreEvent::Notification(message) => {
277 self.session
278 .send(proto::Toast {
279 project_id: SSH_PROJECT_ID,
280 notification_id: "lsp".to_string(),
281 message: message.clone(),
282 })
283 .log_err();
284 }
285 LspStoreEvent::LanguageServerLog(language_server_id, log_type, message) => {
286 self.session
287 .send(proto::LanguageServerLog {
288 project_id: SSH_PROJECT_ID,
289 language_server_id: language_server_id.to_proto(),
290 message: message.clone(),
291 log_type: Some(log_type.to_proto()),
292 })
293 .log_err();
294 }
295 LspStoreEvent::LanguageServerPrompt(prompt) => {
296 let request = self.session.request(proto::LanguageServerPromptRequest {
297 project_id: SSH_PROJECT_ID,
298 actions: prompt
299 .actions
300 .iter()
301 .map(|action| action.title.to_string())
302 .collect(),
303 level: Some(prompt_to_proto(&prompt)),
304 lsp_name: prompt.lsp_name.clone(),
305 message: prompt.message.clone(),
306 });
307 let prompt = prompt.clone();
308 cx.background_executor()
309 .spawn(async move {
310 let response = request.await?;
311 if let Some(action_response) = response.action_response {
312 prompt.respond(action_response as usize).await;
313 }
314 anyhow::Ok(())
315 })
316 .detach();
317 }
318 _ => {}
319 }
320 }
321
322 pub async fn handle_add_worktree(
323 this: Entity<Self>,
324 message: TypedEnvelope<proto::AddWorktree>,
325 mut cx: AsyncApp,
326 ) -> Result<proto::AddWorktreeResponse> {
327 use client::ErrorCodeExt;
328 let path = shellexpand::tilde(&message.payload.path).to_string();
329
330 let fs = this.read_with(&mut cx, |this, _| this.fs.clone())?;
331 let path = PathBuf::from(path);
332
333 let canonicalized = match fs.canonicalize(&path).await {
334 Ok(path) => path,
335 Err(e) => {
336 let mut parent = path
337 .parent()
338 .ok_or(e)
339 .map_err(|_| anyhow!("{:?} does not exist", path))?;
340 if parent == Path::new("") {
341 parent = util::paths::home_dir();
342 }
343 let parent = fs.canonicalize(parent).await.map_err(|_| {
344 anyhow!(proto::ErrorCode::DevServerProjectPathDoesNotExist
345 .with_tag("path", &path.to_string_lossy().as_ref()))
346 })?;
347 parent.join(path.file_name().unwrap())
348 }
349 };
350
351 let worktree = this
352 .update(&mut cx.clone(), |this, _| {
353 Worktree::local(
354 Arc::from(canonicalized.as_path()),
355 message.payload.visible,
356 this.fs.clone(),
357 this.next_entry_id.clone(),
358 &mut cx,
359 )
360 })?
361 .await?;
362
363 let response = this.update(&mut cx, |_, cx| {
364 worktree.update(cx, |worktree, _| proto::AddWorktreeResponse {
365 worktree_id: worktree.id().to_proto(),
366 canonicalized_path: canonicalized.to_string_lossy().to_string(),
367 })
368 })?;
369
370 // We spawn this asynchronously, so that we can send the response back
371 // *before* `worktree_store.add()` can send out UpdateProject requests
372 // to the client about the new worktree.
373 //
374 // That lets the client manage the reference/handles of the newly-added
375 // worktree, before getting interrupted by an UpdateProject request.
376 //
377 // This fixes the problem of the client sending the AddWorktree request,
378 // headless project sending out a project update, client receiving it
379 // and immediately dropping the reference of the new client, causing it
380 // to be dropped on the headless project, and the client only then
381 // receiving a response to AddWorktree.
382 cx.spawn(|mut cx| async move {
383 this.update(&mut cx, |this, cx| {
384 this.worktree_store.update(cx, |worktree_store, cx| {
385 worktree_store.add(&worktree, cx);
386 });
387 })
388 .log_err();
389 })
390 .detach();
391
392 Ok(response)
393 }
394
395 pub async fn handle_remove_worktree(
396 this: Entity<Self>,
397 envelope: TypedEnvelope<proto::RemoveWorktree>,
398 mut cx: AsyncApp,
399 ) -> Result<proto::Ack> {
400 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
401 this.update(&mut cx, |this, cx| {
402 this.worktree_store.update(cx, |worktree_store, cx| {
403 worktree_store.remove_worktree(worktree_id, cx);
404 });
405 })?;
406 Ok(proto::Ack {})
407 }
408
409 pub async fn handle_open_buffer_by_path(
410 this: Entity<Self>,
411 message: TypedEnvelope<proto::OpenBufferByPath>,
412 mut cx: AsyncApp,
413 ) -> Result<proto::OpenBufferResponse> {
414 let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
415 let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
416 let buffer_store = this.buffer_store.clone();
417 let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
418 buffer_store.open_buffer(
419 ProjectPath {
420 worktree_id,
421 path: PathBuf::from(message.payload.path).into(),
422 },
423 message.payload.skip_file_contents,
424 cx,
425 )
426 });
427 anyhow::Ok((buffer_store, buffer))
428 })??;
429
430 let buffer = buffer.await?;
431 let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
432 buffer_store.update(&mut cx, |buffer_store, cx| {
433 buffer_store
434 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
435 .detach_and_log_err(cx);
436 })?;
437
438 Ok(proto::OpenBufferResponse {
439 buffer_id: buffer_id.to_proto(),
440 })
441 }
442
443 pub async fn handle_open_new_buffer(
444 this: Entity<Self>,
445 _message: TypedEnvelope<proto::OpenNewBuffer>,
446 mut cx: AsyncApp,
447 ) -> Result<proto::OpenBufferResponse> {
448 let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
449 let buffer_store = this.buffer_store.clone();
450 let buffer = this
451 .buffer_store
452 .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx));
453 anyhow::Ok((buffer_store, buffer))
454 })??;
455
456 let buffer = buffer.await?;
457 let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
458 buffer_store.update(&mut cx, |buffer_store, cx| {
459 buffer_store
460 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
461 .detach_and_log_err(cx);
462 })?;
463
464 Ok(proto::OpenBufferResponse {
465 buffer_id: buffer_id.to_proto(),
466 })
467 }
468
469 pub async fn handle_open_server_settings(
470 this: Entity<Self>,
471 _: TypedEnvelope<proto::OpenServerSettings>,
472 mut cx: AsyncApp,
473 ) -> Result<proto::OpenBufferResponse> {
474 let settings_path = paths::settings_file();
475 let (worktree, path) = this
476 .update(&mut cx, |this, cx| {
477 this.worktree_store.update(cx, |worktree_store, cx| {
478 worktree_store.find_or_create_worktree(settings_path, false, cx)
479 })
480 })?
481 .await?;
482
483 let (buffer, buffer_store) = this.update(&mut cx, |this, cx| {
484 let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
485 buffer_store.open_buffer(
486 ProjectPath {
487 worktree_id: worktree.read(cx).id(),
488 path: path.into(),
489 },
490 false,
491 cx,
492 )
493 });
494
495 (buffer, this.buffer_store.clone())
496 })?;
497
498 let buffer = buffer.await?;
499
500 let buffer_id = cx.update(|cx| {
501 if buffer.read(cx).is_empty() {
502 buffer.update(cx, |buffer, cx| {
503 buffer.edit([(0..0, initial_server_settings_content())], None, cx)
504 });
505 }
506
507 let buffer_id = buffer.read_with(cx, |b, _| b.remote_id());
508
509 buffer_store.update(cx, |buffer_store, cx| {
510 buffer_store
511 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
512 .detach_and_log_err(cx);
513 });
514
515 buffer_id
516 })?;
517
518 Ok(proto::OpenBufferResponse {
519 buffer_id: buffer_id.to_proto(),
520 })
521 }
522
523 pub async fn handle_find_search_candidates(
524 this: Entity<Self>,
525 envelope: TypedEnvelope<proto::FindSearchCandidates>,
526 mut cx: AsyncApp,
527 ) -> Result<proto::FindSearchCandidatesResponse> {
528 let message = envelope.payload;
529 let query = SearchQuery::from_proto(
530 message
531 .query
532 .ok_or_else(|| anyhow!("missing query field"))?,
533 )?;
534 let results = this.update(&mut cx, |this, cx| {
535 this.buffer_store.update(cx, |buffer_store, cx| {
536 buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
537 })
538 })?;
539
540 let mut response = proto::FindSearchCandidatesResponse {
541 buffer_ids: Vec::new(),
542 };
543
544 let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
545
546 while let Ok(buffer) = results.recv().await {
547 let buffer_id = buffer.update(&mut cx, |this, _| this.remote_id())?;
548 response.buffer_ids.push(buffer_id.to_proto());
549 buffer_store
550 .update(&mut cx, |buffer_store, cx| {
551 buffer_store.create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
552 })?
553 .await?;
554 }
555
556 Ok(response)
557 }
558
559 pub async fn handle_list_remote_directory(
560 this: Entity<Self>,
561 envelope: TypedEnvelope<proto::ListRemoteDirectory>,
562 cx: AsyncApp,
563 ) -> Result<proto::ListRemoteDirectoryResponse> {
564 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
565 let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
566
567 let mut entries = Vec::new();
568 let mut response = fs.read_dir(Path::new(&expanded)).await?;
569 while let Some(path) = response.next().await {
570 if let Some(file_name) = path?.file_name() {
571 entries.push(file_name.to_string_lossy().to_string());
572 }
573 }
574 Ok(proto::ListRemoteDirectoryResponse { entries })
575 }
576
577 pub async fn handle_get_path_metadata(
578 this: Entity<Self>,
579 envelope: TypedEnvelope<proto::GetPathMetadata>,
580 cx: AsyncApp,
581 ) -> Result<proto::GetPathMetadataResponse> {
582 let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
583 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
584
585 let metadata = fs.metadata(&PathBuf::from(expanded.clone())).await?;
586 let is_dir = metadata.map(|metadata| metadata.is_dir).unwrap_or(false);
587
588 Ok(proto::GetPathMetadataResponse {
589 exists: metadata.is_some(),
590 is_dir,
591 path: expanded,
592 })
593 }
594
595 pub async fn handle_shutdown_remote_server(
596 _this: Entity<Self>,
597 _envelope: TypedEnvelope<proto::ShutdownRemoteServer>,
598 cx: AsyncApp,
599 ) -> Result<proto::Ack> {
600 cx.spawn(|cx| async move {
601 cx.update(|cx| {
602 // TODO: This is a hack, because in a headless project, shutdown isn't executed
603 // when calling quit, but it should be.
604 cx.shutdown();
605 cx.quit();
606 })
607 })
608 .detach();
609
610 Ok(proto::Ack {})
611 }
612
613 pub async fn handle_ping(
614 _this: Entity<Self>,
615 _envelope: TypedEnvelope<proto::Ping>,
616 _cx: AsyncApp,
617 ) -> Result<proto::Ack> {
618 log::debug!("Received ping from client");
619 Ok(proto::Ack {})
620 }
621
622 async fn handle_stage(
623 this: Entity<Self>,
624 envelope: TypedEnvelope<proto::Stage>,
625 mut cx: AsyncApp,
626 ) -> Result<proto::Ack> {
627 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
628 let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
629 let repository_handle =
630 Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
631
632 let entries = envelope
633 .payload
634 .paths
635 .into_iter()
636 .map(PathBuf::from)
637 .map(RepoPath::new)
638 .collect();
639
640 repository_handle.stage_entries(entries).await?;
641 Ok(proto::Ack {})
642 }
643
644 async fn handle_unstage(
645 this: Entity<Self>,
646 envelope: TypedEnvelope<proto::Unstage>,
647 mut cx: AsyncApp,
648 ) -> Result<proto::Ack> {
649 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
650 let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
651 let repository_handle =
652 Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
653
654 let entries = envelope
655 .payload
656 .paths
657 .into_iter()
658 .map(PathBuf::from)
659 .map(RepoPath::new)
660 .collect();
661
662 repository_handle.unstage_entries(entries).await?;
663
664 Ok(proto::Ack {})
665 }
666
667 async fn handle_commit(
668 this: Entity<Self>,
669 envelope: TypedEnvelope<proto::Commit>,
670 mut cx: AsyncApp,
671 ) -> Result<proto::Ack> {
672 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
673 let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
674 let repository_handle =
675 Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
676
677 let name = envelope.payload.name.map(SharedString::from);
678 let email = envelope.payload.email.map(SharedString::from);
679
680 repository_handle.commit(name.zip(email)).await?;
681 Ok(proto::Ack {})
682 }
683
684 async fn handle_open_commit_message_buffer(
685 this: Entity<Self>,
686 envelope: TypedEnvelope<proto::OpenCommitMessageBuffer>,
687 mut cx: AsyncApp,
688 ) -> Result<proto::OpenBufferResponse> {
689 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
690 let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
691 let repository_handle =
692 Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
693 let git_repository = match &repository_handle.git_repo {
694 GitRepo::Local(git_repository) => git_repository.clone(),
695 GitRepo::Remote { .. } => {
696 anyhow::bail!("Cannot handle open commit message buffer for remote git repo")
697 }
698 };
699 let commit_message_file = git_repository.dot_git_dir().join(*COMMIT_MESSAGE);
700 let fs = this.update(&mut cx, |headless_project, _| headless_project.fs.clone())?;
701 fs.create_file(
702 &commit_message_file,
703 CreateOptions {
704 overwrite: false,
705 ignore_if_exists: true,
706 },
707 )
708 .await
709 .with_context(|| format!("creating commit message file {commit_message_file:?}"))?;
710
711 let (worktree, relative_path) = this
712 .update(&mut cx, |headless_project, cx| {
713 headless_project
714 .worktree_store
715 .update(cx, |worktree_store, cx| {
716 worktree_store.find_or_create_worktree(&commit_message_file, false, cx)
717 })
718 })?
719 .await
720 .with_context(|| {
721 format!("deriving worktree for commit message file {commit_message_file:?}")
722 })?;
723
724 let buffer = this
725 .update(&mut cx, |headless_project, cx| {
726 headless_project
727 .buffer_store
728 .update(cx, |buffer_store, cx| {
729 buffer_store.open_buffer(
730 ProjectPath {
731 worktree_id: worktree.read(cx).id(),
732 path: Arc::from(relative_path),
733 },
734 true,
735 cx,
736 )
737 })
738 })
739 .with_context(|| {
740 format!("opening buffer for commit message file {commit_message_file:?}")
741 })?
742 .await?;
743
744 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id())?;
745 this.update(&mut cx, |headless_project, cx| {
746 headless_project
747 .buffer_store
748 .update(cx, |buffer_store, cx| {
749 buffer_store
750 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
751 .detach_and_log_err(cx);
752 })
753 })?;
754
755 Ok(proto::OpenBufferResponse {
756 buffer_id: buffer_id.to_proto(),
757 })
758 }
759
760 fn repository_for_request(
761 this: &Entity<Self>,
762 worktree_id: WorktreeId,
763 work_directory_id: ProjectEntryId,
764 cx: &mut AsyncApp,
765 ) -> Result<RepositoryHandle> {
766 this.update(cx, |project, cx| {
767 let repository_handle = project
768 .git_state
769 .read(cx)
770 .all_repositories()
771 .into_iter()
772 .find(|repository_handle| {
773 repository_handle.worktree_id == worktree_id
774 && repository_handle.repository_entry.work_directory_id()
775 == work_directory_id
776 })
777 .context("missing repository handle")?;
778 anyhow::Ok(repository_handle)
779 })?
780 }
781}
782
783fn prompt_to_proto(
784 prompt: &project::LanguageServerPromptRequest,
785) -> proto::language_server_prompt_request::Level {
786 match prompt.level {
787 PromptLevel::Info => proto::language_server_prompt_request::Level::Info(
788 proto::language_server_prompt_request::Info {},
789 ),
790 PromptLevel::Warning => proto::language_server_prompt_request::Level::Warning(
791 proto::language_server_prompt_request::Warning {},
792 ),
793 PromptLevel::Critical => proto::language_server_prompt_request::Level::Critical(
794 proto::language_server_prompt_request::Critical {},
795 ),
796 }
797}