diff --git a/src/main.js b/src/main.js index a78dee41..d5a0a93d 100644 --- a/src/main.js +++ b/src/main.js @@ -102,6 +102,7 @@ const { editorCandidates, detectEditors, matchDetectedEditor, openSiteInEditor, const { handleDeepLink, pickDeepLinkArg, createDeepLinkQueue, protocolRegistration } = require('./deep-link.cjs'); const { mainWindowSize } = require('./window-size.cjs'); const { appendExcludeBlock } = require('./exclude-file.cjs'); +const { xdebugLaunchConfigFile } = require('./xdebug-launch-file.cjs'); const LOCAL_EXCLUDES_MARKER = '# WordPress Contributor Toolkit local excludes'; const LOCAL_EXCLUDES = [ @@ -3844,6 +3845,22 @@ ipcMain.handle('editor:list', async () => ({ names: Object.fromEntries(editorCandidates({ platform: process.platform }).map(({ id, name }) => [id, name])) })); +ipcMain.handle('xdebug:launch-config-file', async (_e, sitePath, config, create) => { + const s = await getStore(); + const result = await xdebugLaunchConfigFile(sitePath, { + sites: s.get('sites'), + pending: setupTracker.paths(), + realPath: (target) => fs.promises.realpath(target), + stat: (target) => fs.promises.stat(target), + mkdir: (target, options) => fs.promises.mkdir(target, options), + writeFile: (target, content, options) => fs.promises.writeFile(target, content, options), + config, + create + }); + if (!result.ok) logEvent('xdebug', `could not prepare .vscode/launch.json (${result.reason})`); + return result; +}); + // The application the contributor just named, or null for "one this list does // not have" — which opens the file dialog, and is the reason no editor is ever // shown as unavailable with nothing to do about it. diff --git a/src/preload.js b/src/preload.js index 425d3aba..81a2780e 100644 --- a/src/preload.js +++ b/src/preload.js @@ -90,6 +90,8 @@ contextBridge.exposeInMainWorld('api', { // ones, which main checks. Without one, the file dialog answers instead. // `relPath` is a file of the site to open with it (#669). openInEditor: (sitePath, editorPath = null, relPath = null) => ipcRenderer.invoke('editor:open', sitePath, editorPath, relPath) +, + xdebugLaunchConfigFile: (sitePath, config, create = false) => ipcRenderer.invoke('xdebug:launch-config-file', sitePath, config, create) , // Who the patch came from and where, app-wide (#166). An empty ref forgets // the field it is passed to. diff --git a/src/renderer/components/xdebug-setup-dialog.jsx b/src/renderer/components/xdebug-setup-dialog.jsx index 54649438..34640b5e 100644 --- a/src/renderer/components/xdebug-setup-dialog.jsx +++ b/src/renderer/components/xdebug-setup-dialog.jsx @@ -41,11 +41,11 @@ function CopyButton({ text, label = __('Copy'), describedBy, onCopy }) { } // One numbered step: its words, and what goes with them, under the words. -function Step({ children, words }) { +function Step({ children, words, markup = STEP_MARKUP }) { return (
  • - {createInterpolateElement(words, STEP_MARKUP)} + {createInterpolateElement(words, markup)} {children}
  • @@ -66,18 +66,104 @@ function OneSiteNote() { ); } -// VS Code reads its debug setup from a file in the project, so it gets the -// whole file to paste. -function VsCodeSteps({ config, onCopy }) { +const PHP_DEBUG_EXTENSION_URL = 'https://marketplace.visualstudio.com/items?itemName=xdebug.php-debug'; + +// VS Code reads its debug setup from a file in the project. The app can create +// it when missing, and opens an existing file without replacing its contents. +function VsCodeSteps({ config, onCopy, sitePath, editorPath, editorName, isOpen }) { + const [fileStatus, setFileStatus] = useState('checking'); + const [fileBusy, setFileBusy] = useState(false); + const [fileError, setFileError] = useState(''); + + useEffect(() => { + if (!isOpen) return undefined; + let cancelled = false; + setFileStatus('checking'); + window.api.xdebugLaunchConfigFile(sitePath, config, false) + .then((result) => { + if (cancelled) return; + if (result?.ok) setFileStatus(result.exists ? 'exists' : 'missing'); + else setFileStatus('unknown'); + }) + .catch((error) => { + if (!cancelled) { + setFileStatus('unknown'); + // eslint-disable-next-line no-console -- reaches the log file through spyRendererConsole. + console.error('Could not check the Xdebug launch file:', error); + } + }); + return () => { cancelled = true; }; + }, [config, isOpen, sitePath]); + + const openLaunchFile = useCallback(async () => { + setFileBusy(true); + setFileError(''); + try { + const prepared = await window.api.xdebugLaunchConfigFile(sitePath, config, true); + if (!prepared?.ok) { + setFileError(__('Could not create .vscode/launch.json. You can still copy the configuration below.')); + return; + } + setFileStatus('exists'); + const opened = await window.api.openInEditor(sitePath, editorPath, '.vscode/launch.json'); + if (!opened?.ok) { + setFileError(sprintf( + // translators: %s: an editor's name, such as VS Code. + __('The file is ready, but %s could not open it. Open .vscode/launch.json from the site folder instead.'), + editorName + )); + } + } catch (error) { + // eslint-disable-next-line no-console -- reaches the log file through spyRendererConsole. + console.error('Could not create or open the Xdebug launch file:', error); + setFileError(__('Could not create or open .vscode/launch.json. You can still copy the configuration below.')); + } finally { + setFileBusy(false); + } + }, [config, editorName, editorPath, sitePath]); + + const fileButtonLabel = () => { + if (fileStatus === 'checking') return __('Checking launch.json…'); + if (fileStatus === 'exists') { + return sprintf( + // translators: %s: an editor's name, such as VS Code. + __('Open launch.json in %s to edit'), + editorName + ); + } + if (fileStatus === 'unknown') { + return sprintf( + // translators: %s: an editor's name, such as VS Code. + __('Add or open launch.json in %s'), + editorName + ); + } + return sprintf( + // translators: %s: an editor's name, such as VS Code. + __('Add launch.json and open in %s'), + editorName + ); + }; + const extensionLink = ( + { event.preventDefault(); window.api.openExternal(PHP_DEBUG_EXTENSION_URL); }} + /> + ); + return (
      - PHP Debug extension by Xdebug.')} /> + PHP Debug extension for VS Code.')} markup={{ ...STEP_MARKUP, link: extensionLink }} /> .vscode/launch.json:')}>
      {config}
      - + + + {fileError ? {fileError} : null}
      Run and Debug, start “Listen for Xdebug”, set a breakpoint, and load the site.')} /> @@ -189,19 +275,21 @@ function PhpStormSteps({ values, onCopy }) { * one editor, picked from the Debugging row's menu: VS Code or Cursor, with * the launch.json they need, Zed, with its debug.json, Sublime Text, with its * project file, or PhpStorm, with the values its settings need. The app - * shows and copies them, and never writes them into the checkout, where they - * would end up in a patch. + * shows and copies them; for VS Code it can add the launch file if it is + * missing, but never replaces one already there. * * @param {Object} props - * @param {?Object} props.editor The editor while open, from `xdebugEditors`: `{id, name, setup}`; or null. - * @param {string} props.config The launch.json, from `xdebugLaunchConfig`. - * @param {string} props.zed The debug.json, from `zedDebugConfig`. - * @param {string} props.sublime The .sublime-project, from `sublimeProjectConfig`. - * @param {Array} props.phpStorm The PhpStorm values, from `phpStormSettings`. - * @param {Function} props.onCopy Copies a text, resolving to whether it worked. + * @param {?Object} props.editor The editor while open, from `xdebugEditors`: `{id, name, setup}`; or null. + * @param {string} props.config The launch.json, from `xdebugLaunchConfig`. + * @param {string} props.sitePath The site's folder. + * @param {?string} props.editorPath The detected application path to open the setup file in. + * @param {string} props.zed The debug.json, from `zedDebugConfig`. + * @param {string} props.sublime The .sublime-project, from `sublimeProjectConfig`. + * @param {Array} props.phpStorm The PhpStorm values, from `phpStormSettings`. + * @param {Function} props.onCopy Copies a text, resolving to whether it worked. * @param {Function} props.onClose */ -export function XdebugSetupDialog({ editor, config, zed, sublime, phpStorm, onCopy, onClose }) { +export function XdebugSetupDialog({ editor, config, zed, sublime, phpStorm, sitePath, editorPath, onCopy, onClose }) { // The editor stays drawn while the dialog closes, when `editor` is already // null. const [shown, setShown] = useState(editor); @@ -227,7 +315,7 @@ export function XdebugSetupDialog({ editor, config, zed, sublime, phpStorm, onCo - {steps[setup] || } + {steps[setup] || } {phpStormShown ? ( {__('If the site starts on another port, PhpStorm asks which server it is; update the Host above.')} diff --git a/src/renderer/index.jsx b/src/renderer/index.jsx index 8b4327f3..8eb58fdb 100644 --- a/src/renderer/index.jsx +++ b/src/renderer/index.jsx @@ -1431,6 +1431,7 @@ function SiteRow({ sitePath, initialized, createdAt, label, projectType = null, const setupEditors = useMemo(() => xdebugEditors(detectedEditors), [detectedEditors]); // The editor chosen in Settings opens its setup without the menu (#767). const setupEditor = xdebugSetupEditor({ editors: setupEditors, preferred: settings?.editor ?? null }); + const xdebugEditorPath = detectedEditors.find((entry) => entry.id === xdebugEditor)?.path ?? null; // A copy that failed says so on its button, and why in the log. const copyXdebugConfig = useCallback(async (text) => { try { @@ -2614,7 +2615,7 @@ function SiteRow({ sitePath, initialized, createdAt, label, projectType = null, onClose={() => setDirtyModalOpen(false)} /> ) : null} - entry.id === xdebugEditor) || null : null} config={xdebug ? xdebug.config : ''} zed={xdebug ? xdebug.zed : ''} sublime={xdebug ? xdebug.sublime : ''} phpStorm={xdebug ? xdebug.phpStorm : []} onCopy={copyXdebugConfig} onClose={() => setXdebugEditor(null)} /> + entry.id === xdebugEditor) || null : null} config={xdebug ? xdebug.config : ''} zed={xdebug ? xdebug.zed : ''} sublime={xdebug ? xdebug.sublime : ''} phpStorm={xdebug ? xdebug.phpStorm : []} sitePath={sitePath} editorPath={xdebugEditorPath} onCopy={copyXdebugConfig} onClose={() => setXdebugEditor(null)} /> asking.action()} onClose={() => setAsking(null)} /> {isPatchOpen && ( diff --git a/src/xdebug-launch-file.cjs b/src/xdebug-launch-file.cjs new file mode 100644 index 00000000..653a8381 --- /dev/null +++ b/src/xdebug-launch-file.cjs @@ -0,0 +1,108 @@ +'use strict'; + +const path = require('node:path'); +const { isActionableSite } = require('./site-registry'); + +const NOT_THERE = new Set(['ENOENT', 'ENOTDIR']); +const MAX_CONFIG_BYTES = 16 * 1024; + +function inside(root, target) { + const relative = path.relative(root, target); + return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative); +} + +function refusal(reason) { + return { ok: false, reason }; +} + +async function existingLaunchFile(file, root, { realPath, stat }) { + let realFile; + try { + realFile = await realPath(file); + } catch (error) { + const code = typeof error?.code === 'string' ? error.code : 'UNKNOWN'; + return NOT_THERE.has(code) ? { ok: true, exists: false, created: false } : refusal('file-unavailable'); + } + if (!inside(root, realFile)) return refusal('outside-site'); + try { + const info = await stat(file); + return info.isFile() ? { ok: true, exists: true, created: false } : refusal('invalid-file'); + } catch (error) { + const code = typeof error?.code === 'string' ? error.code : 'UNKNOWN'; + return NOT_THERE.has(code) ? { ok: true, exists: false, created: false } : refusal('file-unavailable'); + } +} + +/** + * Check for, or create without replacing, the Xdebug launch file for a site. + * + * @param {string} sitePath + * @param {Object} deps + * @param {Array} deps.sites + * @param {Array} deps.pending + * @param {Function} deps.realPath + * @param {Function} deps.stat + * @param {Function} deps.mkdir + * @param {Function} deps.writeFile + * @param {string} [deps.config] + * @param {boolean} [deps.create] + * @return {Promise<{ok: boolean, exists?: boolean, created?: boolean, reason?: string}>} + */ +async function xdebugLaunchConfigFile(sitePath, { sites, pending, realPath, stat, mkdir, writeFile, config, create = false } = {}) { + if (!isActionableSite(sitePath, { sites, pending })) return refusal('unregistered-site'); + if (create) { + if (typeof config !== 'string' || Buffer.byteLength(config, 'utf8') > MAX_CONFIG_BYTES) return refusal('invalid-config'); + try { + JSON.parse(config); + } catch { + return refusal('invalid-config'); + } + } + + const rootPath = path.resolve(sitePath); + let root; + try { + root = await realPath(rootPath); + } catch { + return refusal('file-unavailable'); + } + + const directory = path.join(root, '.vscode'); + let directoryInfo; + try { + directoryInfo = await stat(directory); + } catch (error) { + const code = typeof error?.code === 'string' ? error.code : 'UNKNOWN'; + if (!NOT_THERE.has(code)) return refusal('file-unavailable'); + if (!create) return { ok: true, exists: false, created: false }; + try { + await mkdir(directory, { recursive: true }); + directoryInfo = await stat(directory); + } catch { + return refusal('file-unavailable'); + } + } + if (!directoryInfo.isDirectory()) return refusal('invalid-directory'); + + let realDirectory; + try { + realDirectory = await realPath(directory); + } catch { + return refusal('file-unavailable'); + } + if (!inside(root, realDirectory)) return refusal('outside-site'); + + const file = path.join(directory, 'launch.json'); + const current = await existingLaunchFile(file, root, { realPath, stat }); + if (!current.ok || current.exists || !create) return current; + + try { + await writeFile(file, config, { encoding: 'utf8', flag: 'wx' }); + return { ok: true, exists: true, created: true }; + } catch (error) { + if (error?.code === 'EEXIST') return existingLaunchFile(file, root, { realPath, stat }); + return refusal('file-unavailable'); + } +} + +module.exports = { xdebugLaunchConfigFile }; \ No newline at end of file diff --git a/tests/e2e/journeys/xdebug.spec.js b/tests/e2e/journeys/xdebug.spec.js index b77d6023..5d589bf3 100644 --- a/tests/e2e/journeys/xdebug.spec.js +++ b/tests/e2e/journeys/xdebug.spec.js @@ -22,6 +22,7 @@ */ const path = require( 'node:path' ); +const fs = require( 'node:fs' ); const { test, expect } = require( '../helpers/app.cjs' ); const ui = require( '../helpers/ui.cjs' ); const { makeSite } = require( '../helpers/git-site.cjs' ); @@ -78,6 +79,7 @@ async function setXdebug( page, on ) { } test( 'the Debugging row says when Xdebug is on, and a server started with it offers the editor setup', async ( { session } ) => { + test.setTimeout( 90_000 ); const site = await makeSite( session ); const { app, page } = await session.start( site.settings ); const followSetting = await stubServer( app, session ); @@ -127,6 +129,39 @@ test( 'the Debugging row says when Xdebug is on, and a server started with it of // INVARIANT — the launch.json listens on this machine only. expect( launch.configurations[ 0 ].hostname ).toBe( '127.0.0.1' ); + // INVARIANT — the extension link opens the requested Marketplace page, and + // a missing launch.json can be created and opened in the detected editor. + await app.evaluate( ( { ipcMain, shell } ) => { + global.e2eOpened = []; + global.e2eEditorOpens = []; + shell.openExternal = async ( url ) => { global.e2eOpened.push( url ); }; + ipcMain.removeHandler( 'editor:open' ); + ipcMain.handle( 'editor:open', ( _event, sitePath, editorPath, relPath ) => { + global.e2eEditorOpens.push( { sitePath, editorPath, relPath } ); + return { ok: true }; + } ); + } ); + const extension = vscode.getByRole( 'link', { name: /PHP Debug/ } ); + await expect( extension ).toHaveAttribute( 'href', 'https://marketplace.visualstudio.com/items?itemName=xdebug.php-debug' ); + await extension.click(); + await expect.poll( () => app.evaluate( () => global.e2eOpened ) ).toEqual( [ 'https://marketplace.visualstudio.com/items?itemName=xdebug.php-debug' ] ); + const addLaunch = vscode.getByRole( 'button', { name: 'Add launch.json and open in VS Code', exact: true } ); + await expect( addLaunch ).toBeEnabled(); + await addLaunch.click(); + const launchFile = path.join( site.dir, '.vscode', 'launch.json' ); + expect( fs.readFileSync( launchFile, 'utf8' ) ).toBe( await vscode.locator( '.xdebug-launch-config' ).textContent() ); + await expect.poll( () => app.evaluate( () => global.e2eEditorOpens ) ).toEqual( [ { sitePath: site.dir, editorPath: '/e2e/vscode', relPath: '.vscode/launch.json' } ] ); + + // INVARIANT — reopening an existing file offers the edit action and does + // not replace the contributor's configuration. + const contributorConfig = '{"myConfiguration":true}\n'; + fs.writeFileSync( launchFile, contributorConfig ); + const editLaunch = vscode.getByRole( 'button', { name: 'Open launch.json in VS Code to edit', exact: true } ); + await expect( editLaunch ).toBeEnabled(); + await editLaunch.click(); + await expect.poll( () => app.evaluate( () => global.e2eEditorOpens ) ).toHaveLength( 2 ); + expect( fs.readFileSync( launchFile, 'utf8' ) ).toBe( contributorConfig ); + // INVARIANT — copying follows the design system's pattern: the button // keeps its name, shows a check for two seconds after the copy, an error // icon for a copy that failed, and the result is said. A second copy diff --git a/tests/e2e/packaged/smoke.spec.js b/tests/e2e/packaged/smoke.spec.js index 2a9a09e0..687bde2d 100644 --- a/tests/e2e/packaged/smoke.spec.js +++ b/tests/e2e/packaged/smoke.spec.js @@ -117,6 +117,7 @@ const EXPECTED_API_KEYS = [ 'switchBranch', 'takeResumeList', 'updateTrunk', + 'xdebugLaunchConfigFile', ]; /** diff --git a/tests/unit/ipc-wiring.test.cjs b/tests/unit/ipc-wiring.test.cjs index 41720c32..d59f3794 100644 --- a/tests/unit/ipc-wiring.test.cjs +++ b/tests/unit/ipc-wiring.test.cjs @@ -7101,6 +7101,32 @@ test('editor:list asks editor-launch what is installed, without a shell', async assert.equal(result.names.cursor, 'Cursor'); }); +test('xdebug:launch-config-file delegates with the registered sites and generated config', async () => { + const xdebugLaunchConfigFile = spy(async () => ({ ok: true, exists: true, created: true })); + const main = loadMain({ + stubs: { + ...silentLogging(), + ...fakeSettingsStore({ sites: [SITE] }).stubs, + './xdebug-launch-file.cjs': { xdebugLaunchConfigFile } + } + }); + const config = '{"version":"0.2.0"}'; + + assert.deepEqual(await main.invoke('xdebug:launch-config-file', SITE, config, true), { ok: true, exists: true, created: true }); + + assert.equal(xdebugLaunchConfigFile.calls.length, 1); + const [sitePath, options] = xdebugLaunchConfigFile.calls[0]; + assert.equal(sitePath, SITE); + assert.deepEqual(options.sites, [SITE]); + assert.ok(Array.isArray(options.pending)); + assert.equal(options.config, config); + assert.equal(options.create, true); + assert.equal(typeof options.realPath, 'function'); + assert.equal(typeof options.stat, 'function'); + assert.equal(typeof options.mkdir, 'function'); + assert.equal(typeof options.writeFile, 'function'); +}); + test('dir:show asks site-registry whether the path may be revealed', async () => { const revealRegisteredSite = spy(async () => ({ ok: true })); const main = loadMain({ @@ -8374,6 +8400,7 @@ const WIRED = new Set([ 'trac:list-attachments', 'editor:list', 'editor:open', + 'xdebug:launch-config-file', 'dir:show', 'wordpress:setup', 'wp-debug:clear', diff --git a/tests/unit/xdebug-launch-file.test.cjs b/tests/unit/xdebug-launch-file.test.cjs new file mode 100644 index 00000000..61256f1a --- /dev/null +++ b/tests/unit/xdebug-launch-file.test.cjs @@ -0,0 +1,58 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { xdebugLaunchConfigFile } = require('../../src/xdebug-launch-file.cjs'); + +function makeSite(t) { + const site = fs.mkdtempSync(path.join(os.tmpdir(), 'xdebug-launch-file-')); + t.after(() => fs.rmSync(site, { recursive: true, force: true })); + return site; +} + +function dependencies(site, overrides = {}) { + return { + sites: [site], + pending: [], + realPath: (target) => fs.promises.realpath(target), + stat: (target) => fs.promises.stat(target), + mkdir: (target, options) => fs.promises.mkdir(target, options), + writeFile: (target, content, options) => fs.promises.writeFile(target, content, options), + ...overrides + }; +} + +test('checks for launch.json, creates it when missing, and leaves an existing file untouched', async (t) => { + const site = makeSite(t); + const config = JSON.stringify({ version: '0.2.0', configurations: [{ name: 'Listen for Xdebug' }] }, null, 2); + const deps = dependencies(site, { config }); + + assert.deepEqual(await xdebugLaunchConfigFile(site, deps), { ok: true, exists: false, created: false }); + assert.deepEqual(await xdebugLaunchConfigFile(site, { ...deps, create: true }), { ok: true, exists: true, created: true }); + const launchFile = path.join(site, '.vscode', 'launch.json'); + assert.equal(fs.readFileSync(launchFile, 'utf8'), config); + + const contributorConfig = '{"myConfiguration":true}\n'; + fs.writeFileSync(launchFile, contributorConfig); + assert.deepEqual(await xdebugLaunchConfigFile(site, { ...deps, create: true }), { ok: true, exists: true, created: false }); + assert.equal(fs.readFileSync(launchFile, 'utf8'), contributorConfig); +}); + +test('refuses to create a launch file for an unregistered site', async (t) => { + const site = makeSite(t); + const result = await xdebugLaunchConfigFile(site, dependencies(site, { sites: [], create: true, config: '{}' })); + + assert.deepEqual(result, { ok: false, reason: 'unregistered-site' }); + assert.equal(fs.existsSync(path.join(site, '.vscode')), false); +}); + +test('refuses an invalid launch configuration without creating a file', async (t) => { + const site = makeSite(t); + const result = await xdebugLaunchConfigFile(site, dependencies(site, { create: true, config: 'not JSON' })); + + assert.deepEqual(result, { ok: false, reason: 'invalid-config' }); + assert.equal(fs.existsSync(path.join(site, '.vscode')), false); +}); \ No newline at end of file