php.rs

  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>::validate_config(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": "array",
153                    "description": "A list of server paths mapping to the local source paths on your machine for remote host debugging",
154                    "items": {
155                        "type": "object",
156                        "properties": {
157                            "serverPath": {
158                                "type": "string",
159                                "description": "Path on the server"
160                            },
161                            "localPath": {
162                                "type": "string",
163                                "description": "Corresponding path on the local machine"
164                            }
165                        },
166                        "required": ["serverPath", "localPath"]
167                    }
168                },
169                "log": {
170                    "type": "boolean",
171                    "description": "Whether to log all communication between editor and the adapter to the debug console",
172                    "default": false
173                },
174                "ignore": {
175                    "type": "array",
176                    "description": "An array of glob patterns that errors should be ignored from (for example **/vendor/**/*.php)",
177                    "items": {
178                        "type": "string"
179                    }
180                },
181                "ignoreExceptions": {
182                    "type": "array",
183                    "description": "An array of exception class names that should be ignored (for example BaseException, \\NS1\\Exception, \\*\\Exception or \\**\\Exception*)",
184                    "items": {
185                        "type": "string"
186                    }
187                },
188                "skipFiles": {
189                    "type": "array",
190                    "description": "An array of glob patterns to skip when debugging. Star patterns and negations are allowed.",
191                    "items": {
192                        "type": "string"
193                    }
194                },
195                "skipEntryPaths": {
196                    "type": "array",
197                    "description": "An array of glob patterns to immediately detach from and ignore for debugging if the entry script matches",
198                    "items": {
199                        "type": "string"
200                    }
201                },
202                "maxConnections": {
203                    "type": "integer",
204                    "description": "Accept only this number of parallel debugging sessions. Additional connections will be dropped.",
205                    "default": 1
206                },
207                "proxy": {
208                    "type": "object",
209                    "description": "DBGp Proxy settings",
210                    "properties": {
211                        "enable": {
212                            "type": "boolean",
213                            "description": "To enable proxy registration",
214                            "default": false
215                        },
216                        "host": {
217                            "type": "string",
218                            "description": "The address of the proxy. Supports host name, IP address, or Unix domain socket.",
219                            "default": "127.0.0.1"
220                        },
221                        "port": {
222                            "type": "integer",
223                            "description": "The port where the adapter will register with the proxy",
224                            "default": 9001
225                        },
226                        "key": {
227                            "type": "string",
228                            "description": "A unique key that allows the proxy to match requests to your editor",
229                            "default": "vsc"
230                        },
231                        "timeout": {
232                            "type": "integer",
233                            "description": "The number of milliseconds to wait before giving up on the connection to proxy",
234                            "default": 3000
235                        },
236                        "allowMultipleSessions": {
237                            "type": "boolean",
238                            "description": "If the proxy should forward multiple sessions/connections at the same time or not",
239                            "default": true
240                        }
241                    }
242                },
243                "xdebugSettings": {
244                    "type": "object",
245                    "description": "Allows you to override Xdebug's remote debugging settings to fine tune Xdebug to your needs",
246                    "properties": {
247                        "max_children": {
248                            "type": "integer",
249                            "description": "Max number of array or object children to initially retrieve"
250                        },
251                        "max_data": {
252                            "type": "integer",
253                            "description": "Max amount of variable data to initially retrieve"
254                        },
255                        "max_depth": {
256                            "type": "integer",
257                            "description": "Maximum depth that the debugger engine may return when sending arrays, hashes or object structures to the IDE"
258                        },
259                        "show_hidden": {
260                            "type": "integer",
261                            "description": "Whether to show detailed internal information on properties (e.g. private members of classes). Zero means hidden members are not shown.",
262                            "enum": [0, 1]
263                        },
264                        "breakpoint_include_return_value": {
265                            "type": "boolean",
266                            "description": "Determines whether to enable an additional \"return from function\" debugging step, allowing inspection of the return value when a function call returns"
267                        }
268                    }
269                },
270                "xdebugCloudToken": {
271                    "type": "string",
272                    "description": "Instead of listening locally, open a connection and register with Xdebug Cloud and accept debugging sessions on that connection"
273                },
274                "stream": {
275                    "type": "object",
276                    "description": "Allows to influence DBGp streams. Xdebug only supports stdout",
277                    "properties": {
278                        "stdout": {
279                            "type": "integer",
280                            "description": "Redirect stdout stream: 0 (disable), 1 (copy), 2 (redirect)",
281                            "enum": [0, 1, 2],
282                            "default": 0
283                        }
284                    }
285                }
286            },
287            "required": ["request", "program"]
288        })
289    }
290
291    fn name(&self) -> DebugAdapterName {
292        DebugAdapterName(Self::ADAPTER_NAME.into())
293    }
294
295    fn adapter_language_name(&self) -> Option<LanguageName> {
296        Some(SharedString::new_static("PHP").into())
297    }
298
299    fn validate_config(
300        &self,
301        _: &serde_json::Value,
302    ) -> Result<StartDebuggingRequestArgumentsRequest> {
303        Ok(StartDebuggingRequestArgumentsRequest::Launch)
304    }
305
306    fn config_from_zed_format(&self, zed_scenario: ZedDebugConfig) -> Result<DebugScenario> {
307        let obj = match &zed_scenario.request {
308            dap::DebugRequest::Attach(_) => {
309                bail!("Php adapter doesn't support attaching")
310            }
311            dap::DebugRequest::Launch(launch_config) => json!({
312                "program": launch_config.program,
313                "cwd": launch_config.cwd,
314                "args": launch_config.args,
315                "env": launch_config.env_json(),
316                "stopOnEntry": zed_scenario.stop_on_entry.unwrap_or_default(),
317            }),
318        };
319
320        Ok(DebugScenario {
321            adapter: zed_scenario.adapter,
322            label: zed_scenario.label,
323            build: None,
324            config: obj,
325            tcp_connection: None,
326        })
327    }
328
329    async fn get_binary(
330        &self,
331        delegate: &Arc<dyn DapDelegate>,
332        task_definition: &DebugTaskDefinition,
333        user_installed_path: Option<PathBuf>,
334        cx: &mut AsyncApp,
335    ) -> Result<DebugAdapterBinary> {
336        if self.checked.set(()).is_ok() {
337            delegate.output_to_console(format!("Checking latest version of {}...", self.name()));
338            if let Some(version) = self.fetch_latest_adapter_version(delegate).await.log_err() {
339                adapters::download_adapter_from_github(
340                    self.name(),
341                    version,
342                    adapters::DownloadedFileType::Vsix,
343                    delegate.as_ref(),
344                )
345                .await?;
346            }
347        }
348
349        self.get_installed_binary(delegate, &task_definition, user_installed_path, cx)
350            .await
351    }
352}