1use adapters::latest_github_release;
2use anyhow::Context as _;
3use anyhow::bail;
4use dap::StartDebuggingRequestArguments;
5use dap::StartDebuggingRequestArgumentsRequest;
6use dap::adapters::{DebugTaskDefinition, TcpArguments};
7use gpui::{AsyncApp, SharedString};
8use language::LanguageName;
9use std::{collections::HashMap, path::PathBuf, sync::OnceLock};
10use util::ResultExt;
11
12use crate::*;
13
14#[derive(Default)]
15pub(crate) struct PhpDebugAdapter {
16 checked: OnceLock<()>,
17}
18
19impl PhpDebugAdapter {
20 const ADAPTER_NAME: &'static str = "PHP";
21 const ADAPTER_PACKAGE_NAME: &'static str = "vscode-php-debug";
22 const ADAPTER_PATH: &'static str = "extension/out/phpDebug.js";
23
24 async fn fetch_latest_adapter_version(
25 &self,
26 delegate: &Arc<dyn DapDelegate>,
27 ) -> Result<AdapterVersion> {
28 let release = latest_github_release(
29 &format!("{}/{}", "xdebug", Self::ADAPTER_PACKAGE_NAME),
30 true,
31 false,
32 delegate.http_client(),
33 )
34 .await?;
35
36 let asset_name = format!("php-debug-{}.vsix", release.tag_name.replace("v", ""));
37
38 Ok(AdapterVersion {
39 tag_name: release.tag_name,
40 url: release
41 .assets
42 .iter()
43 .find(|asset| asset.name == asset_name)
44 .with_context(|| format!("no asset found matching {asset_name:?}"))?
45 .browser_download_url
46 .clone(),
47 })
48 }
49
50 async fn get_installed_binary(
51 &self,
52 delegate: &Arc<dyn DapDelegate>,
53 task_definition: &DebugTaskDefinition,
54 user_installed_path: Option<PathBuf>,
55 _: &mut AsyncApp,
56 ) -> Result<DebugAdapterBinary> {
57 let adapter_path = if let Some(user_installed_path) = user_installed_path {
58 user_installed_path
59 } else {
60 let adapter_path = paths::debug_adapters_dir().join(self.name().as_ref());
61
62 let file_name_prefix = format!("{}_", self.name());
63
64 util::fs::find_file_name_in_dir(adapter_path.as_path(), |file_name| {
65 file_name.starts_with(&file_name_prefix)
66 })
67 .await
68 .context("Couldn't find PHP dap directory")?
69 };
70
71 let tcp_connection = task_definition.tcp_connection.clone().unwrap_or_default();
72 let (host, port, timeout) = crate::configure_tcp_connection(tcp_connection).await?;
73
74 Ok(DebugAdapterBinary {
75 command: Some(
76 delegate
77 .node_runtime()
78 .binary_path()
79 .await?
80 .to_string_lossy()
81 .into_owned(),
82 ),
83 arguments: vec![
84 adapter_path
85 .join(Self::ADAPTER_PATH)
86 .to_string_lossy()
87 .to_string(),
88 format!("--server={}", port),
89 ],
90 connection: Some(TcpArguments {
91 port,
92 host,
93 timeout,
94 }),
95 cwd: Some(delegate.worktree_root_path().to_path_buf()),
96 envs: HashMap::default(),
97 request_args: StartDebuggingRequestArguments {
98 configuration: task_definition.config.clone(),
99 request: <Self as DebugAdapter>::request_kind(self, &task_definition.config)?,
100 },
101 })
102 }
103}
104
105#[async_trait(?Send)]
106impl DebugAdapter for PhpDebugAdapter {
107 async fn dap_schema(&self) -> serde_json::Value {
108 json!({
109 "properties": {
110 "request": {
111 "type": "string",
112 "enum": ["launch"],
113 "description": "The request type for the PHP debug adapter, always \"launch\"",
114 "default": "launch"
115 },
116 "hostname": {
117 "type": "string",
118 "description": "The address to bind to when listening for Xdebug (default: all IPv6 connections if available, else all IPv4 connections) or Unix Domain socket (prefix with unix://) or Windows Pipe (\\\\?\\pipe\\name) - cannot be combined with port"
119 },
120 "port": {
121 "type": "integer",
122 "description": "The port on which to listen for Xdebug (default: 9003). If port is set to 0 a random port is chosen by the system and a placeholder ${port} is replaced with the chosen port in env and runtimeArgs.",
123 "default": 9003
124 },
125 "program": {
126 "type": "string",
127 "description": "The PHP script to debug (typically a path to a file)",
128 "default": "${file}"
129 },
130 "cwd": {
131 "type": "string",
132 "description": "Working directory for the debugged program"
133 },
134 "args": {
135 "type": "array",
136 "items": {
137 "type": "string"
138 },
139 "description": "Command line arguments to pass to the program"
140 },
141 "env": {
142 "type": "object",
143 "description": "Environment variables to pass to the program",
144 "additionalProperties": {
145 "type": "string"
146 }
147 },
148 "stopOnEntry": {
149 "type": "boolean",
150 "description": "Whether to break at the beginning of the script",
151 "default": false
152 },
153 "pathMappings": {
154 "type": "object",
155 "description": "A mapping of server paths to local paths.",
156 },
157 "log": {
158 "type": "boolean",
159 "description": "Whether to log all communication between editor and the adapter to the debug console",
160 "default": false
161 },
162 "ignore": {
163 "type": "array",
164 "description": "An array of glob patterns that errors should be ignored from (for example **/vendor/**/*.php)",
165 "items": {
166 "type": "string"
167 }
168 },
169 "ignoreExceptions": {
170 "type": "array",
171 "description": "An array of exception class names that should be ignored (for example BaseException, \\NS1\\Exception, \\*\\Exception or \\**\\Exception*)",
172 "items": {
173 "type": "string"
174 }
175 },
176 "skipFiles": {
177 "type": "array",
178 "description": "An array of glob patterns to skip when debugging. Star patterns and negations are allowed.",
179 "items": {
180 "type": "string"
181 }
182 },
183 "skipEntryPaths": {
184 "type": "array",
185 "description": "An array of glob patterns to immediately detach from and ignore for debugging if the entry script matches",
186 "items": {
187 "type": "string"
188 }
189 },
190 "maxConnections": {
191 "type": "integer",
192 "description": "Accept only this number of parallel debugging sessions. Additional connections will be dropped.",
193 "default": 1
194 },
195 "proxy": {
196 "type": "object",
197 "description": "DBGp Proxy settings",
198 "properties": {
199 "enable": {
200 "type": "boolean",
201 "description": "To enable proxy registration",
202 "default": false
203 },
204 "host": {
205 "type": "string",
206 "description": "The address of the proxy. Supports host name, IP address, or Unix domain socket.",
207 "default": "127.0.0.1"
208 },
209 "port": {
210 "type": "integer",
211 "description": "The port where the adapter will register with the proxy",
212 "default": 9001
213 },
214 "key": {
215 "type": "string",
216 "description": "A unique key that allows the proxy to match requests to your editor",
217 "default": "vsc"
218 },
219 "timeout": {
220 "type": "integer",
221 "description": "The number of milliseconds to wait before giving up on the connection to proxy",
222 "default": 3000
223 },
224 "allowMultipleSessions": {
225 "type": "boolean",
226 "description": "If the proxy should forward multiple sessions/connections at the same time or not",
227 "default": true
228 }
229 }
230 },
231 "xdebugSettings": {
232 "type": "object",
233 "description": "Allows you to override Xdebug's remote debugging settings to fine tune Xdebug to your needs",
234 "properties": {
235 "max_children": {
236 "type": "integer",
237 "description": "Max number of array or object children to initially retrieve"
238 },
239 "max_data": {
240 "type": "integer",
241 "description": "Max amount of variable data to initially retrieve"
242 },
243 "max_depth": {
244 "type": "integer",
245 "description": "Maximum depth that the debugger engine may return when sending arrays, hashes or object structures to the IDE"
246 },
247 "show_hidden": {
248 "type": "integer",
249 "description": "Whether to show detailed internal information on properties (e.g. private members of classes). Zero means hidden members are not shown.",
250 "enum": [0, 1]
251 },
252 "breakpoint_include_return_value": {
253 "type": "boolean",
254 "description": "Determines whether to enable an additional \"return from function\" debugging step, allowing inspection of the return value when a function call returns"
255 }
256 }
257 },
258 "xdebugCloudToken": {
259 "type": "string",
260 "description": "Instead of listening locally, open a connection and register with Xdebug Cloud and accept debugging sessions on that connection"
261 },
262 "stream": {
263 "type": "object",
264 "description": "Allows to influence DBGp streams. Xdebug only supports stdout",
265 "properties": {
266 "stdout": {
267 "type": "integer",
268 "description": "Redirect stdout stream: 0 (disable), 1 (copy), 2 (redirect)",
269 "enum": [0, 1, 2],
270 "default": 0
271 }
272 }
273 }
274 },
275 "required": ["request", "program"]
276 })
277 }
278
279 fn name(&self) -> DebugAdapterName {
280 DebugAdapterName(Self::ADAPTER_NAME.into())
281 }
282
283 fn adapter_language_name(&self) -> Option<LanguageName> {
284 Some(SharedString::new_static("PHP").into())
285 }
286
287 fn request_kind(&self, _: &serde_json::Value) -> Result<StartDebuggingRequestArgumentsRequest> {
288 Ok(StartDebuggingRequestArgumentsRequest::Launch)
289 }
290
291 fn config_from_zed_format(&self, zed_scenario: ZedDebugConfig) -> Result<DebugScenario> {
292 let obj = match &zed_scenario.request {
293 dap::DebugRequest::Attach(_) => {
294 bail!("Php adapter doesn't support attaching")
295 }
296 dap::DebugRequest::Launch(launch_config) => json!({
297 "program": launch_config.program,
298 "cwd": launch_config.cwd,
299 "args": launch_config.args,
300 "env": launch_config.env_json(),
301 "stopOnEntry": zed_scenario.stop_on_entry.unwrap_or_default(),
302 }),
303 };
304
305 Ok(DebugScenario {
306 adapter: zed_scenario.adapter,
307 label: zed_scenario.label,
308 build: None,
309 config: obj,
310 tcp_connection: None,
311 })
312 }
313
314 async fn get_binary(
315 &self,
316 delegate: &Arc<dyn DapDelegate>,
317 task_definition: &DebugTaskDefinition,
318 user_installed_path: Option<PathBuf>,
319 cx: &mut AsyncApp,
320 ) -> Result<DebugAdapterBinary> {
321 if self.checked.set(()).is_ok() {
322 delegate.output_to_console(format!("Checking latest version of {}...", self.name()));
323 if let Some(version) = self.fetch_latest_adapter_version(delegate).await.log_err() {
324 adapters::download_adapter_from_github(
325 self.name(),
326 version,
327 adapters::DownloadedFileType::Vsix,
328 delegate.as_ref(),
329 )
330 .await?;
331 }
332 }
333
334 self.get_installed_binary(delegate, &task_definition, user_installed_path, cx)
335 .await
336 }
337}