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: delegate
76 .node_runtime()
77 .binary_path()
78 .await?
79 .to_string_lossy()
80 .into_owned(),
81 arguments: vec![
82 adapter_path
83 .join(Self::ADAPTER_PATH)
84 .to_string_lossy()
85 .to_string(),
86 format!("--server={}", port),
87 ],
88 connection: Some(TcpArguments {
89 port,
90 host,
91 timeout,
92 }),
93 cwd: Some(delegate.worktree_root_path().to_path_buf()),
94 envs: HashMap::default(),
95 request_args: StartDebuggingRequestArguments {
96 configuration: task_definition.config.clone(),
97 request: <Self as DebugAdapter>::request_kind(self, &task_definition.config)?,
98 },
99 })
100 }
101}
102
103#[async_trait(?Send)]
104impl DebugAdapter for PhpDebugAdapter {
105 async fn dap_schema(&self) -> serde_json::Value {
106 json!({
107 "properties": {
108 "request": {
109 "type": "string",
110 "enum": ["launch"],
111 "description": "The request type for the PHP debug adapter, always \"launch\"",
112 "default": "launch"
113 },
114 "hostname": {
115 "type": "string",
116 "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"
117 },
118 "port": {
119 "type": "integer",
120 "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.",
121 "default": 9003
122 },
123 "program": {
124 "type": "string",
125 "description": "The PHP script to debug (typically a path to a file)",
126 "default": "${file}"
127 },
128 "cwd": {
129 "type": "string",
130 "description": "Working directory for the debugged program"
131 },
132 "args": {
133 "type": "array",
134 "items": {
135 "type": "string"
136 },
137 "description": "Command line arguments to pass to the program"
138 },
139 "env": {
140 "type": "object",
141 "description": "Environment variables to pass to the program",
142 "additionalProperties": {
143 "type": "string"
144 }
145 },
146 "stopOnEntry": {
147 "type": "boolean",
148 "description": "Whether to break at the beginning of the script",
149 "default": false
150 },
151 "pathMappings": {
152 "type": "object",
153 "description": "A mapping of server paths to local paths.",
154 },
155 "log": {
156 "type": "boolean",
157 "description": "Whether to log all communication between editor and the adapter to the debug console",
158 "default": false
159 },
160 "ignore": {
161 "type": "array",
162 "description": "An array of glob patterns that errors should be ignored from (for example **/vendor/**/*.php)",
163 "items": {
164 "type": "string"
165 }
166 },
167 "ignoreExceptions": {
168 "type": "array",
169 "description": "An array of exception class names that should be ignored (for example BaseException, \\NS1\\Exception, \\*\\Exception or \\**\\Exception*)",
170 "items": {
171 "type": "string"
172 }
173 },
174 "skipFiles": {
175 "type": "array",
176 "description": "An array of glob patterns to skip when debugging. Star patterns and negations are allowed.",
177 "items": {
178 "type": "string"
179 }
180 },
181 "skipEntryPaths": {
182 "type": "array",
183 "description": "An array of glob patterns to immediately detach from and ignore for debugging if the entry script matches",
184 "items": {
185 "type": "string"
186 }
187 },
188 "maxConnections": {
189 "type": "integer",
190 "description": "Accept only this number of parallel debugging sessions. Additional connections will be dropped.",
191 "default": 1
192 },
193 "proxy": {
194 "type": "object",
195 "description": "DBGp Proxy settings",
196 "properties": {
197 "enable": {
198 "type": "boolean",
199 "description": "To enable proxy registration",
200 "default": false
201 },
202 "host": {
203 "type": "string",
204 "description": "The address of the proxy. Supports host name, IP address, or Unix domain socket.",
205 "default": "127.0.0.1"
206 },
207 "port": {
208 "type": "integer",
209 "description": "The port where the adapter will register with the proxy",
210 "default": 9001
211 },
212 "key": {
213 "type": "string",
214 "description": "A unique key that allows the proxy to match requests to your editor",
215 "default": "vsc"
216 },
217 "timeout": {
218 "type": "integer",
219 "description": "The number of milliseconds to wait before giving up on the connection to proxy",
220 "default": 3000
221 },
222 "allowMultipleSessions": {
223 "type": "boolean",
224 "description": "If the proxy should forward multiple sessions/connections at the same time or not",
225 "default": true
226 }
227 }
228 },
229 "xdebugSettings": {
230 "type": "object",
231 "description": "Allows you to override Xdebug's remote debugging settings to fine tune Xdebug to your needs",
232 "properties": {
233 "max_children": {
234 "type": "integer",
235 "description": "Max number of array or object children to initially retrieve"
236 },
237 "max_data": {
238 "type": "integer",
239 "description": "Max amount of variable data to initially retrieve"
240 },
241 "max_depth": {
242 "type": "integer",
243 "description": "Maximum depth that the debugger engine may return when sending arrays, hashes or object structures to the IDE"
244 },
245 "show_hidden": {
246 "type": "integer",
247 "description": "Whether to show detailed internal information on properties (e.g. private members of classes). Zero means hidden members are not shown.",
248 "enum": [0, 1]
249 },
250 "breakpoint_include_return_value": {
251 "type": "boolean",
252 "description": "Determines whether to enable an additional \"return from function\" debugging step, allowing inspection of the return value when a function call returns"
253 }
254 }
255 },
256 "xdebugCloudToken": {
257 "type": "string",
258 "description": "Instead of listening locally, open a connection and register with Xdebug Cloud and accept debugging sessions on that connection"
259 },
260 "stream": {
261 "type": "object",
262 "description": "Allows to influence DBGp streams. Xdebug only supports stdout",
263 "properties": {
264 "stdout": {
265 "type": "integer",
266 "description": "Redirect stdout stream: 0 (disable), 1 (copy), 2 (redirect)",
267 "enum": [0, 1, 2],
268 "default": 0
269 }
270 }
271 }
272 },
273 "required": ["request", "program"]
274 })
275 }
276
277 fn name(&self) -> DebugAdapterName {
278 DebugAdapterName(Self::ADAPTER_NAME.into())
279 }
280
281 fn adapter_language_name(&self) -> Option<LanguageName> {
282 Some(SharedString::new_static("PHP").into())
283 }
284
285 fn request_kind(&self, _: &serde_json::Value) -> Result<StartDebuggingRequestArgumentsRequest> {
286 Ok(StartDebuggingRequestArgumentsRequest::Launch)
287 }
288
289 fn config_from_zed_format(&self, zed_scenario: ZedDebugConfig) -> Result<DebugScenario> {
290 let obj = match &zed_scenario.request {
291 dap::DebugRequest::Attach(_) => {
292 bail!("Php adapter doesn't support attaching")
293 }
294 dap::DebugRequest::Launch(launch_config) => json!({
295 "program": launch_config.program,
296 "cwd": launch_config.cwd,
297 "args": launch_config.args,
298 "env": launch_config.env_json(),
299 "stopOnEntry": zed_scenario.stop_on_entry.unwrap_or_default(),
300 }),
301 };
302
303 Ok(DebugScenario {
304 adapter: zed_scenario.adapter,
305 label: zed_scenario.label,
306 build: None,
307 config: obj,
308 tcp_connection: None,
309 })
310 }
311
312 async fn get_binary(
313 &self,
314 delegate: &Arc<dyn DapDelegate>,
315 task_definition: &DebugTaskDefinition,
316 user_installed_path: Option<PathBuf>,
317 cx: &mut AsyncApp,
318 ) -> Result<DebugAdapterBinary> {
319 if self.checked.set(()).is_ok() {
320 delegate.output_to_console(format!("Checking latest version of {}...", self.name()));
321 if let Some(version) = self.fetch_latest_adapter_version(delegate).await.log_err() {
322 adapters::download_adapter_from_github(
323 self.name(),
324 version,
325 adapters::DownloadedFileType::Vsix,
326 delegate.as_ref(),
327 )
328 .await?;
329 }
330 }
331
332 self.get_installed_binary(delegate, &task_definition, user_installed_path, cx)
333 .await
334 }
335}