From 616dc9a2a5e1b1d3e633417deec5c3ec06847e0c Mon Sep 17 00:00:00 2001 From: Noah Allen Date: Thu, 8 Apr 2021 16:04:57 -0700 Subject: [PATCH] wp-env: Remove platform-specific destroy commands (#30638) --- packages/env/CHANGELOG.md | 4 +++ packages/env/lib/commands/destroy.js | 43 +++++++++++++++------------- 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/packages/env/CHANGELOG.md b/packages/env/CHANGELOG.md index b42aa7e9c5023..ae85edbd1acb4 100644 --- a/packages/env/CHANGELOG.md +++ b/packages/env/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Bug Fix + +- `wp-env destroy` will now work in environments which don't include the `grep` or `awk` commands, such as Windows PowerShell. + ## 4.0.0 (2021-03-17) ### Breaking Change diff --git a/packages/env/lib/commands/destroy.js b/packages/env/lib/commands/destroy.js index 2bda29e110c61..5b081392209f9 100644 --- a/packages/env/lib/commands/destroy.js +++ b/packages/env/lib/commands/destroy.js @@ -68,27 +68,11 @@ module.exports = async function destroy( { spinner, debug } ) { const directoryHash = path.basename( workDirectoryPath ); - spinner.text = 'Removing docker networks and volumes.'; - const getVolumes = `docker volume ls | grep "${ directoryHash }" | awk '/ / { print $2 }'`; - const removeVolumes = `docker volume rm $(${ getVolumes })`; + spinner.text = 'Removing docker volumes.'; + await removeDockerItems( 'volume', directoryHash ); - const getNetworks = `docker network ls | grep "${ directoryHash }" | awk '/ / { print $1 }'`; - const removeNetworks = `docker network rm $(${ getNetworks })`; - - const command = `${ removeVolumes } && ${ removeNetworks }`; - - if ( debug ) { - spinner.info( - `Running command to remove volumes and networks:\n${ command }\n` - ); - } - - const { stdout } = await exec( command ); - if ( debug && stdout ) { - // Disable reason: Logging information in debug mode. - // eslint-disable-next-line no-console - console.log( `Removed volumes and networks:\n${ stdout }` ); - } + spinner.text = 'Removing docker networks.'; + await removeDockerItems( 'network', directoryHash ); spinner.text = 'Removing local files.'; @@ -96,3 +80,22 @@ module.exports = async function destroy( { spinner, debug } ) { spinner.text = 'Removed WordPress environment.'; }; + +/** + * Removes docker items, like networks or volumes, matching the given name. + * + * @param {string} itemType The item type, like "network" or "volume" + * @param {string} name Remove items whose name match this string. + */ +async function removeDockerItems( itemType, name ) { + const { stdout: items } = await exec( + `docker ${ itemType } ls -q --filter name=${ name }` + ); + if ( items ) { + await exec( + `docker ${ itemType } rm ${ items + .split( '\n' ) // TODO: use os.EOL? + .join( ' ' ) }` + ); + } +}