Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up DAP install code #51

Merged
merged 7 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/dap/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ http_client.workspace = true
log.workspace = true
node_runtime.workspace = true
parking_lot.workspace = true
paths.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
settings.workspace = true
smallvec.workspace = true
smol.workspace = true
task.workspace = true
util.workspace = true
91 changes: 88 additions & 3 deletions crates/dap/src/adapters.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
use crate::transport::Transport;
use ::fs::Fs;
use anyhow::Result;
use anyhow::{anyhow, bail, Context, Result};
use async_trait::async_trait;
use http_client::HttpClient;
use http_client::{github::latest_github_release, HttpClient};
use node_runtime::NodeRuntime;
use serde_json::Value;
use std::{collections::HashMap, ffi::OsString, path::Path, sync::Arc};
use smol::{self, fs::File, process};
use std::{
collections::HashMap,
ffi::OsString,
fmt::Debug,
path::{Path, PathBuf},
sync::Arc,
};
use task::DebugAdapterConfig;

pub trait DapDelegate {
Expand Down Expand Up @@ -35,8 +42,86 @@ pub struct DebugAdapterBinary {
pub envs: Option<HashMap<String, String>>,
}

pub async fn download_adapter_from_github(
adapter_name: DebugAdapterName,
github_repo: GithubRepo,
delegate: &dyn DapDelegate,
) -> Result<PathBuf> {
let adapter_path = paths::debug_adapters_dir().join(&adapter_name);
let fs = delegate.fs();

if let Some(http_client) = delegate.http_client() {
if !adapter_path.exists() {
fs.create_dir(&adapter_path.as_path()).await?;
}

let repo_name_with_owner = format!("{}/{}", github_repo.repo_owner, github_repo.repo_name);
let release =
latest_github_release(&repo_name_with_owner, false, false, http_client.clone()).await?;

let asset_name = format!("{}_{}.zip", &adapter_name, release.tag_name);
let zip_path = adapter_path.join(&asset_name);

if smol::fs::metadata(&zip_path).await.is_err() {
let mut response = http_client
.get(&release.zipball_url, Default::default(), true)
.await
.context("Error downloading release")?;

let mut file = File::create(&zip_path).await?;
futures::io::copy(response.body_mut(), &mut file).await?;

let _unzip_status = process::Command::new("unzip")
.current_dir(&adapter_path)
.arg(&zip_path)
.output()
.await?
.status;

fs.remove_file(&zip_path.as_path(), Default::default())
.await?;

let file_name = util::fs::find_file_name_in_dir(&adapter_path.as_path(), |file_name| {
file_name.contains(&adapter_name.to_string())
})
.await
.ok_or_else(|| anyhow!("Unzipped directory not found"));

let file_name = file_name?;
let downloaded_path = adapter_path
.join(format!("{}_{}", adapter_name, release.tag_name))
.to_owned();

fs.rename(
file_name.as_path(),
downloaded_path.as_path(),
Default::default(),
)
.await?;

// if !unzip_status.success() {
// dbg!(unzip_status);
// Err(anyhow!("failed to unzip downloaded dap archive"))?;
// }

return Ok(downloaded_path);
}
}

bail!("Install failed to download & counldn't preinstalled dap")
}

pub struct GithubRepo {
pub repo_name: String,
pub repo_owner: String,
}

#[async_trait(?Send)]
pub trait DebugAdapter: 'static + Send + Sync {
fn id(&self) -> String {
"".to_string()
}

fn name(&self) -> DebugAdapterName;

fn transport(&self) -> Box<dyn Transport>;
Expand Down
1 change: 1 addition & 0 deletions crates/dap_adapters/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ serde.workspace = true
serde_json.workspace = true
smol.workspace = true
task.workspace = true
util.workspace = true
16 changes: 6 additions & 10 deletions crates/dap_adapters/src/dap_adapters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,18 @@ mod lldb;
mod php;
mod python;

use anyhow::{anyhow, bail, Result};
use async_trait::async_trait;
use custom::CustomDebugAdapter;
use dap::adapters::{
self, DapDelegate, DebugAdapter, DebugAdapterBinary, DebugAdapterName, GithubRepo,
};
use javascript::JsDebugAdapter;
use lldb::LldbDebugAdapter;
use php::PhpDebugAdapter;
use python::PythonDebugAdapter;

use anyhow::{anyhow, bail, Context, Result};
use async_trait::async_trait;
use dap::adapters::{DapDelegate, DebugAdapter, DebugAdapterBinary, DebugAdapterName};
use http_client::github::latest_github_release;
use serde_json::{json, Value};
use smol::{
fs::{self, File},
process,
};
use std::{fmt::Debug, process::Stdio};
use std::fmt::Debug;
use task::{CustomArgs, DebugAdapterConfig, DebugAdapterKind, DebugConnectionType, TCPHost};

pub fn build_adapter(adapter_config: &DebugAdapterConfig) -> Result<Box<dyn DebugAdapter>> {
Expand Down
116 changes: 24 additions & 92 deletions crates/dap_adapters/src/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ impl DebugAdapter for JsDebugAdapter {
.ok_or(anyhow!("Couldn't get npm runtime"))?;

let adapter_path = paths::debug_adapters_dir().join(self.name());
let adapter_path = util::fs::find_file_name_in_dir(adapter_path.as_path(), |file_name| {
file_name.starts_with("vscode-js-debug_")
})
.await
.ok_or_else(|| anyhow!("Couldn't find javascript dap directory"))?;

Ok(DebugAdapterBinary {
command: node_runtime
Expand All @@ -54,102 +59,29 @@ impl DebugAdapter for JsDebugAdapter {
}

async fn install_binary(&self, delegate: &dyn DapDelegate) -> Result<()> {
let adapter_path = paths::debug_adapters_dir().join(self.name());
let fs = delegate.fs();

if fs.is_dir(adapter_path.as_path()).await {
return Ok(());
}

if let Some(http_client) = delegate.http_client() {
if !adapter_path.exists() {
fs.create_dir(&adapter_path.as_path()).await?;
}

let release = latest_github_release(
"microsoft/vscode-js-debug",
false,
false,
http_client.clone(),
)
.await?;

let asset_name = format!("{}-{}", self.name(), release.tag_name);
let zip_path = adapter_path.join(asset_name);

if fs::metadata(&zip_path).await.is_err() {
let mut response = http_client
.get(&release.zipball_url, Default::default(), true)
.await
.context("Error downloading release")?;

let mut file = File::create(&zip_path).await?;
futures::io::copy(response.body_mut(), &mut file).await?;

let _unzip_status = process::Command::new("unzip")
.current_dir(&adapter_path)
.arg(&zip_path)
.output()
.await?
.status;
let github_repo = GithubRepo {
repo_name: "vscode-js-debug".to_string(),
repo_owner: "microsoft".to_string(),
};

let mut ls = process::Command::new("ls")
.current_dir(&adapter_path)
.stdout(Stdio::piped())
.spawn()?;
let adapter_path =
adapters::download_adapter_from_github(self.name(), github_repo, delegate).await?;

let std = ls
.stdout
.take()
.ok_or(anyhow!("Failed to list directories"))?
.into_stdio()
.await?;

let file_name = String::from_utf8(
process::Command::new("grep")
.arg("microsoft-vscode-js-debug")
.stdin(std)
.output()
.await?
.stdout,
)?;

let file_name = file_name.trim_end();

process::Command::new("sh")
.current_dir(&adapter_path)
.arg("-c")
.arg(format!("mv {file_name}/* ."))
.output()
.await?;

process::Command::new("rm")
.current_dir(&adapter_path)
.arg("-rf")
.arg(file_name)
.arg(zip_path)
.output()
.await?;

let _ = delegate
.node_runtime()
.ok_or(anyhow!("Couldn't get npm runtime"))?
.run_npm_subcommand(&adapter_path, "install", &[])
.await
.ok();

let _ = delegate
.node_runtime()
.ok_or(anyhow!("Couldn't get npm runtime"))?
.run_npm_subcommand(&adapter_path, "run", &["compile"])
.await
.ok();
let _ = delegate
.node_runtime()
.ok_or(anyhow!("Couldn't get npm runtime"))?
.run_npm_subcommand(&adapter_path, "install", &[])
.await
.ok();

return Ok(());
}
}
let _ = delegate
.node_runtime()
.ok_or(anyhow!("Couldn't get npm runtime"))?
.run_npm_subcommand(&adapter_path, "run", &["compile"])
.await
.ok();

bail!("Install or fetch not implemented for Javascript debug adapter (yet)");
return Ok(());
}

fn request_args(&self, config: &DebugAdapterConfig) -> Value {
Expand Down
24 changes: 21 additions & 3 deletions crates/dap_adapters/src/lldb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,34 @@ impl DebugAdapter for LldbDebugAdapter {
Box::new(StdioTransport::new())
}

async fn install_binary(&self, _: &dyn DapDelegate) -> Result<()> {
bail!("Install or fetch not implemented for lldb debug adapter (yet)")
async fn install_binary(&self, _delegate: &dyn DapDelegate) -> Result<()> {
bail!("Install binary is not support for install_binary (yet)")
}

async fn fetch_binary(
&self,
_: &dyn DapDelegate,
_: &DebugAdapterConfig,
) -> Result<DebugAdapterBinary> {
bail!("Install or fetch not implemented for lldb debug adapter (yet)")
#[cfg(target_os = "macos")]
{
let output = std::process::Command::new("xcrun")
.args(&["-f", "lldb-dap"])
.output()?;
let lldb_dap_path = String::from_utf8(output.stdout)?.trim().to_string();

Ok(DebugAdapterBinary {
command: lldb_dap_path,
arguments: None,
envs: None,
})
}
#[cfg(not(target_os = "macos"))]
{
Err(anyhow::anyhow!(
"LLDB-DAP is only supported on macOS (Right now)"
))
}
}

fn request_args(&self, config: &DebugAdapterConfig) -> Value {
Expand Down
Loading
Loading