1use anyhow::{anyhow, Ok};
2use async_compression::futures::bufread::GzipDecoder;
3use client::Client;
4use gpui::{actions, MutableAppContext};
5use smol::{fs, io::BufReader, stream::StreamExt};
6use std::{env::consts, path::PathBuf, sync::Arc};
7use util::{
8 fs::remove_matching, github::latest_github_release, http::HttpClient, paths, ResultExt,
9};
10
11actions!(copilot, [SignIn]);
12
13pub fn init(client: Arc<Client>, cx: &mut MutableAppContext) {
14 cx.add_global_action(move |_: &SignIn, cx: &mut MutableAppContext| {
15 Copilot::sign_in(client.http_client(), cx)
16 });
17}
18
19struct Copilot {
20 copilot_server: PathBuf,
21}
22
23impl Copilot {
24 fn sign_in(http: Arc<dyn HttpClient>, cx: &mut MutableAppContext) {
25 let copilot = cx.global::<Option<Arc<Copilot>>>().clone();
26
27 cx.spawn(|mut cx| async move {
28 // Lazily download / initialize copilot LSP
29 let copilot = if let Some(copilot) = copilot {
30 copilot
31 } else {
32 let copilot_server = get_lsp_binary(http).await?; // TODO: Make this error user visible
33 let new_copilot = Arc::new(Copilot { copilot_server });
34 cx.update({
35 let new_copilot = new_copilot.clone();
36 move |cx| cx.set_global(Some(new_copilot.clone()))
37 });
38 new_copilot
39 };
40
41 Ok(())
42 })
43 .detach();
44 }
45}
46
47async fn get_lsp_binary(http: Arc<dyn HttpClient>) -> anyhow::Result<PathBuf> {
48 ///Check for the latest copilot language server and download it if we haven't already
49 async fn fetch_latest(http: Arc<dyn HttpClient>) -> anyhow::Result<PathBuf> {
50 let release = latest_github_release("zed-industries/copilotserver", http.clone()).await?;
51 let asset_name = format!("copilot-darwin-{}.gz", consts::ARCH);
52 let asset = release
53 .assets
54 .iter()
55 .find(|asset| asset.name == asset_name)
56 .ok_or_else(|| anyhow!("no asset found matching {:?}", asset_name))?;
57
58 let destination_path =
59 paths::COPILOT_DIR.join(format!("copilot-{}-{}", release.name, consts::ARCH));
60
61 if fs::metadata(&destination_path).await.is_err() {
62 let mut response = http
63 .get(&asset.browser_download_url, Default::default(), true)
64 .await
65 .map_err(|err| anyhow!("error downloading release: {}", err))?;
66 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
67 let mut file = fs::File::create(&destination_path).await?;
68 futures::io::copy(decompressed_bytes, &mut file).await?;
69 fs::set_permissions(
70 &destination_path,
71 <fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
72 )
73 .await?;
74
75 remove_matching(&paths::COPILOT_DIR, |entry| entry != destination_path).await;
76 }
77
78 Ok(destination_path)
79 }
80
81 match fetch_latest(http).await {
82 ok @ Result::Ok(..) => ok,
83 e @ Err(..) => {
84 e.log_err();
85 // Fetch a cached binary, if it exists
86 (|| async move {
87 let mut last = None;
88 let mut entries = fs::read_dir(paths::COPILOT_DIR.as_path()).await?;
89 while let Some(entry) = entries.next().await {
90 last = Some(entry?.path());
91 }
92 last.ok_or_else(|| anyhow!("no cached binary"))
93 })()
94 .await
95 }
96 }
97}