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