@wordpress/env 10.38.1-next.v.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +158 -75
  2. package/lib/cli.js +85 -24
  3. package/lib/commands/clean.js +16 -38
  4. package/lib/commands/cleanup.js +79 -0
  5. package/lib/commands/destroy.js +33 -41
  6. package/lib/commands/index.js +6 -2
  7. package/lib/commands/logs.js +20 -62
  8. package/lib/commands/reset.js +46 -0
  9. package/lib/commands/run.js +16 -117
  10. package/lib/commands/start.js +78 -243
  11. package/lib/commands/status.js +160 -0
  12. package/lib/commands/stop.js +17 -19
  13. package/lib/config/get-config-from-environment-vars.js +2 -5
  14. package/lib/config/load-config.js +35 -5
  15. package/lib/config/parse-config.js +53 -21
  16. package/lib/config/post-process-config.js +38 -16
  17. package/lib/config/test/__snapshots__/config-integration.js.snap +16 -0
  18. package/lib/config/test/parse-config.js +33 -0
  19. package/lib/config/test/post-process-config.js +52 -0
  20. package/lib/download-sources.js +9 -53
  21. package/lib/{build-docker-compose-config.js → runtime/docker/build-docker-compose-config.js} +167 -128
  22. package/lib/runtime/docker/download-sources.js +63 -0
  23. package/lib/{download-wp-phpunit.js → runtime/docker/download-wp-phpunit.js} +4 -1
  24. package/lib/runtime/docker/index.js +863 -0
  25. package/lib/{init-config.js → runtime/docker/init-config.js} +22 -14
  26. package/lib/runtime/docker/wordpress.js +309 -0
  27. package/lib/runtime/errors.js +28 -0
  28. package/lib/runtime/index.js +91 -0
  29. package/lib/runtime/playground/blueprint-builder.js +158 -0
  30. package/lib/runtime/playground/index.js +530 -0
  31. package/lib/test/build-docker-compose-config.js +150 -3
  32. package/lib/test/cli.js +49 -13
  33. package/lib/wordpress.js +1 -297
  34. package/package.json +6 -3
  35. package/lib/commands/install-path.js +0 -21
  36. /package/lib/{get-host-user.js → runtime/docker/get-host-user.js} +0 -0
  37. /package/lib/{validate-run-container.js → runtime/docker/validate-run-container.js} +0 -0
@@ -0,0 +1,863 @@
1
+ 'use strict';
2
+ /**
3
+ * External dependencies
4
+ */
5
+ const { spawn, execSync } = require( 'child_process' );
6
+ const path = require( 'path' );
7
+ const util = require( 'util' );
8
+ const { v2: dockerCompose } = require( 'docker-compose' );
9
+ const { rimraf } = require( 'rimraf' );
10
+
11
+ /**
12
+ * Promisified dependencies
13
+ */
14
+ const exec = util.promisify( require( 'child_process' ).exec );
15
+
16
+ /**
17
+ * Internal dependencies
18
+ */
19
+ const initConfig = require( './init-config' );
20
+ const getHostUser = require( './get-host-user' );
21
+ const downloadSources = require( './download-sources' );
22
+ const downloadWPPHPUnit = require( './download-wp-phpunit' );
23
+ const {
24
+ RUN_CONTAINERS,
25
+ validateRunContainer,
26
+ } = require( './validate-run-container' );
27
+ const {
28
+ configureWordPress,
29
+ resetDatabase,
30
+ setupWordPressDirectories,
31
+ } = require( './wordpress' );
32
+ const { readWordPressVersion, canAccessWPORG } = require( '../../wordpress' );
33
+ const { didCacheChange, setCache } = require( '../../cache' );
34
+ const md5 = require( '../../md5' );
35
+ const retry = require( '../../retry' );
36
+
37
+ /**
38
+ * @typedef {import('../../config').WPConfig} WPConfig
39
+ */
40
+
41
+ const CONFIG_CACHE_KEY = 'config_checksum';
42
+
43
+ /**
44
+ * Docker runtime implementation for wp-env.
45
+ *
46
+ * This runtime uses Docker Compose for container orchestration.
47
+ */
48
+ class DockerRuntime {
49
+ /**
50
+ * Get the name of this runtime.
51
+ *
52
+ * @return {string} Runtime name.
53
+ */
54
+ getName() {
55
+ return 'docker';
56
+ }
57
+
58
+ /**
59
+ * Get supported features for this runtime.
60
+ *
61
+ * @return {Object} Feature flags.
62
+ */
63
+ getFeatures() {
64
+ return {
65
+ testsEnvironment: true,
66
+ xdebug: true,
67
+ spx: true,
68
+ phpMyAdmin: true,
69
+ multisite: true,
70
+ customPhpVersion: true,
71
+ persistentDatabase: true,
72
+ wpCli: true,
73
+ };
74
+ }
75
+
76
+ /**
77
+ * Check if Docker is available.
78
+ *
79
+ * @return {Promise<boolean>} True if Docker is available.
80
+ */
81
+ async isAvailable() {
82
+ try {
83
+ execSync( 'docker info', { stdio: 'ignore' } );
84
+ return true;
85
+ } catch {
86
+ return false;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Start the Docker containers and configure WordPress.
92
+ *
93
+ * @param {WPConfig} config The wp-env config object.
94
+ * @param {Object} options Start options.
95
+ * @param {Object} options.spinner A CLI spinner which indicates progress.
96
+ * @param {boolean} options.update If true, update sources.
97
+ * @param {string} options.xdebug The Xdebug mode to set.
98
+ * @param {string} options.spx The SPX mode to set.
99
+ * @param {boolean} options.debug True if debug mode is enabled.
100
+ * @return {Promise<Object>} Result object with message and siteUrl.
101
+ */
102
+ async start( config, { spinner, update, xdebug, spx, debug } ) {
103
+ // Initialize Docker-specific files (docker-compose.yml, Dockerfiles)
104
+ const fullConfig = await initConfig( {
105
+ spinner,
106
+ debug,
107
+ xdebug,
108
+ spx,
109
+ writeChanges: true,
110
+ customConfigPath: config.customConfigPath,
111
+ } );
112
+
113
+ const testsEnabled = fullConfig.testsEnvironment !== false;
114
+
115
+ // Check if the hash of the config has changed. If so, run configuration.
116
+ const configHash = md5( fullConfig );
117
+ const { workDirectoryPath, dockerComposeConfigPath } = fullConfig;
118
+ const shouldConfigureWp =
119
+ ( update ||
120
+ ( await didCacheChange( CONFIG_CACHE_KEY, configHash, {
121
+ workDirectoryPath,
122
+ } ) ) ) &&
123
+ // Don't reconfigure everything when we can't connect to the internet because
124
+ // the majority of update tasks involve connecting to the internet. (Such
125
+ // as downloading sources and pulling docker images.)
126
+ ( await canAccessWPORG() );
127
+
128
+ const dockerComposeConfig = {
129
+ config: dockerComposeConfigPath,
130
+ log: fullConfig.debug,
131
+ };
132
+
133
+ if ( ! ( await canAccessWPORG() ) ) {
134
+ spinner.info( 'wp-env is offline' );
135
+ }
136
+
137
+ /**
138
+ * If the Docker image is already running and the `wp-env` files have been
139
+ * deleted, the start command will not complete successfully. Stopping
140
+ * the container before continuing allows the docker entrypoint script,
141
+ * which restores the files, to run again when we start the containers.
142
+ *
143
+ * Additionally, --remove-orphans ensures containers from services that
144
+ * were removed in the new config (e.g., tests-* after setting
145
+ * testsEnvironment: false) are properly stopped.
146
+ *
147
+ * @see https://github.com/WordPress/gutenberg/pull/20253#issuecomment-587228440
148
+ */
149
+ if ( shouldConfigureWp ) {
150
+ spinner.text = 'Stopping WordPress.';
151
+ await dockerCompose.down( {
152
+ config: dockerComposeConfigPath,
153
+ log: debug,
154
+ commandOptions: [ '--remove-orphans' ],
155
+ } );
156
+ // Update the images before starting the services again.
157
+ spinner.text = 'Updating docker images.';
158
+
159
+ const directoryHash = path.basename( workDirectoryPath );
160
+
161
+ // Note: when the base docker image is updated, we want that operation to
162
+ // also update WordPress. Since we store wordpress/tests-wordpress files
163
+ // as docker volumes, simply updating the image will not change those
164
+ // files. Thus, we need to remove those volumes in order for the files
165
+ // to be updated when pulling the new images.
166
+ const volumesToRemove = testsEnabled
167
+ ? `${ directoryHash }_wordpress ${ directoryHash }_tests-wordpress`
168
+ : `${ directoryHash }_wordpress`;
169
+
170
+ try {
171
+ if ( fullConfig.debug ) {
172
+ spinner.text = `Removing the WordPress volumes: ${ volumesToRemove }`;
173
+ }
174
+ await exec( `docker volume rm ${ volumesToRemove }` );
175
+ } catch {
176
+ // Note: we do not care about this error condition because it will
177
+ // mostly happen when the volume already exists. This error would not
178
+ // stop wp-env from working correctly.
179
+ }
180
+
181
+ await dockerCompose.pullAll( dockerComposeConfig );
182
+ spinner.text = 'Downloading sources.';
183
+ }
184
+
185
+ const mysqlServices = [ 'mysql' ];
186
+ if ( testsEnabled ) {
187
+ mysqlServices.push( 'tests-mysql' );
188
+ }
189
+ await Promise.all( [
190
+ dockerCompose.upMany( mysqlServices, {
191
+ ...dockerComposeConfig,
192
+ commandOptions: shouldConfigureWp
193
+ ? [ '--build', '--force-recreate' ]
194
+ : [],
195
+ } ),
196
+ shouldConfigureWp && downloadSources( fullConfig, spinner ),
197
+ ] );
198
+
199
+ if ( shouldConfigureWp ) {
200
+ spinner.text = 'Setting up WordPress directories';
201
+
202
+ await setupWordPressDirectories( fullConfig );
203
+
204
+ // Use the WordPress versions to download the PHPUnit suite.
205
+ const wpVersionPromises = [
206
+ readWordPressVersion(
207
+ fullConfig.env.development.coreSource,
208
+ spinner,
209
+ debug
210
+ ),
211
+ ];
212
+ if ( testsEnabled ) {
213
+ wpVersionPromises.push(
214
+ readWordPressVersion(
215
+ fullConfig.env.tests.coreSource,
216
+ spinner,
217
+ debug
218
+ )
219
+ );
220
+ }
221
+ const wpVersions = await Promise.all( wpVersionPromises );
222
+ const wpVersionMap = {
223
+ development: wpVersions[ 0 ],
224
+ };
225
+ if ( testsEnabled ) {
226
+ wpVersionMap.tests = wpVersions[ 1 ];
227
+ }
228
+ await downloadWPPHPUnit( fullConfig, wpVersionMap, spinner, debug );
229
+ }
230
+
231
+ spinner.text = 'Starting WordPress.';
232
+
233
+ const wpServices = [ 'wordpress', 'cli' ];
234
+ if ( testsEnabled ) {
235
+ wpServices.push( 'tests-wordpress', 'tests-cli' );
236
+ }
237
+ await dockerCompose.upMany( wpServices, {
238
+ ...dockerComposeConfig,
239
+ commandOptions: shouldConfigureWp
240
+ ? [ '--build', '--force-recreate' ]
241
+ : [],
242
+ } );
243
+
244
+ if ( fullConfig.env.development.phpmyadminPort ) {
245
+ await dockerCompose.upOne( 'phpmyadmin', {
246
+ ...dockerComposeConfig,
247
+ commandOptions: shouldConfigureWp
248
+ ? [ '--build', '--force-recreate' ]
249
+ : [],
250
+ } );
251
+ }
252
+
253
+ if ( testsEnabled && fullConfig.env.tests.phpmyadminPort ) {
254
+ await dockerCompose.upOne( 'tests-phpmyadmin', {
255
+ ...dockerComposeConfig,
256
+ commandOptions: shouldConfigureWp
257
+ ? [ '--build', '--force-recreate' ]
258
+ : [],
259
+ } );
260
+ }
261
+
262
+ // Make sure we've consumed the custom CLI dockerfile.
263
+ if ( shouldConfigureWp ) {
264
+ await dockerCompose.buildOne( [ 'cli' ], {
265
+ ...dockerComposeConfig,
266
+ } );
267
+ }
268
+
269
+ // Only run WordPress install/configuration when config has changed.
270
+ if ( shouldConfigureWp ) {
271
+ spinner.text = 'Configuring WordPress.';
272
+
273
+ // Retry WordPress installation in case MySQL *still* wasn't ready.
274
+ const configTasks = [
275
+ retry(
276
+ () =>
277
+ configureWordPress(
278
+ 'development',
279
+ fullConfig,
280
+ spinner
281
+ ),
282
+ {
283
+ times: 2,
284
+ }
285
+ ),
286
+ ];
287
+ if ( testsEnabled ) {
288
+ configTasks.push(
289
+ retry(
290
+ () =>
291
+ configureWordPress( 'tests', fullConfig, spinner ),
292
+ {
293
+ times: 2,
294
+ }
295
+ )
296
+ );
297
+ }
298
+ await Promise.all( configTasks );
299
+
300
+ // Set the cache key once everything has been configured.
301
+ await setCache( CONFIG_CACHE_KEY, configHash, {
302
+ workDirectoryPath,
303
+ } );
304
+ }
305
+
306
+ // Get port information for the result message
307
+ const siteUrl = fullConfig.env.development.config.WP_SITEURL;
308
+
309
+ const mySQLPort = await this._getPublicDockerPort(
310
+ 'mysql',
311
+ 3306,
312
+ dockerComposeConfig
313
+ );
314
+
315
+ const phpmyadminPort = fullConfig.env.development.phpmyadminPort
316
+ ? await this._getPublicDockerPort(
317
+ 'phpmyadmin',
318
+ 80,
319
+ dockerComposeConfig
320
+ )
321
+ : null;
322
+
323
+ const message = [
324
+ 'WordPress development site started' +
325
+ ( siteUrl ? ` at ${ siteUrl }` : '.' ),
326
+ `MySQL is listening on port ${ mySQLPort }`,
327
+ phpmyadminPort &&
328
+ `phpMyAdmin started at http://localhost:${ phpmyadminPort }`,
329
+ ];
330
+
331
+ if ( testsEnabled ) {
332
+ const testsSiteUrl = fullConfig.env.tests.config.WP_SITEURL;
333
+ const testsMySQLPort = await this._getPublicDockerPort(
334
+ 'tests-mysql',
335
+ 3306,
336
+ dockerComposeConfig
337
+ );
338
+ const testsPhpmyadminPort = fullConfig.env.tests.phpmyadminPort
339
+ ? await this._getPublicDockerPort(
340
+ 'tests-phpmyadmin',
341
+ 80,
342
+ dockerComposeConfig
343
+ )
344
+ : null;
345
+
346
+ message.push(
347
+ 'WordPress test site started' +
348
+ ( testsSiteUrl ? ` at ${ testsSiteUrl }` : '.' ),
349
+ `MySQL for automated testing is listening on port ${ testsMySQLPort }`,
350
+ testsPhpmyadminPort &&
351
+ `phpMyAdmin for automated testing started at http://localhost:${ testsPhpmyadminPort }`
352
+ );
353
+ }
354
+
355
+ const formattedMessage = message.filter( Boolean ).join( '\n' );
356
+
357
+ return {
358
+ message: formattedMessage,
359
+ siteUrl,
360
+ };
361
+ }
362
+
363
+ /**
364
+ * Get the public port for a Docker service.
365
+ *
366
+ * @param {string} service The service name.
367
+ * @param {number} containerPort The container port.
368
+ * @param {Object} dockerComposeConfig The docker-compose config.
369
+ * @return {Promise<string>} The public port.
370
+ */
371
+ async _getPublicDockerPort( service, containerPort, dockerComposeConfig ) {
372
+ const { out: address } = await dockerCompose.port(
373
+ service,
374
+ containerPort,
375
+ dockerComposeConfig
376
+ );
377
+ return address.split( ':' ).pop().trim();
378
+ }
379
+
380
+ /**
381
+ * Get the warning message for destroy confirmation.
382
+ *
383
+ * @return {string} Warning message.
384
+ */
385
+ getDestroyWarningMessage() {
386
+ return 'WARNING! This will remove Docker containers, volumes, networks, and images associated with the WordPress instance.';
387
+ }
388
+
389
+ /**
390
+ * Get the warning message for cleanup confirmation.
391
+ *
392
+ * @return {string} Warning message.
393
+ */
394
+ getCleanupWarningMessage() {
395
+ return 'WARNING! This will remove Docker containers, volumes, networks, and local files associated with the WordPress instance. Docker images will be preserved.';
396
+ }
397
+
398
+ /**
399
+ * Stop the Docker containers.
400
+ *
401
+ * @param {WPConfig} config The wp-env config object.
402
+ * @param {Object} options Stop options.
403
+ * @param {Object} options.spinner A CLI spinner which indicates progress.
404
+ * @param {boolean} options.debug True if debug mode is enabled.
405
+ */
406
+ async stop( config, { spinner, debug } ) {
407
+ const { dockerComposeConfigPath } = await initConfig( {
408
+ spinner,
409
+ debug,
410
+ customConfigPath: config.customConfigPath,
411
+ } );
412
+
413
+ spinner.text = 'Stopping WordPress.';
414
+
415
+ await dockerCompose.down( {
416
+ config: dockerComposeConfigPath,
417
+ log: debug,
418
+ } );
419
+
420
+ spinner.text = 'Stopped WordPress.';
421
+ }
422
+
423
+ /**
424
+ * Destroy the Docker containers and remove local files.
425
+ *
426
+ * @param {WPConfig} config The wp-env config object.
427
+ * @param {Object} options Destroy options.
428
+ * @param {Object} options.spinner A CLI spinner which indicates progress.
429
+ * @param {boolean} options.debug True if debug mode is enabled.
430
+ */
431
+ async destroy( config, { spinner, debug } ) {
432
+ spinner.text = 'Removing docker images, volumes, and networks.';
433
+
434
+ await dockerCompose.down( {
435
+ config: config.dockerComposeConfigPath,
436
+ commandOptions: [ '--volumes', '--remove-orphans', '--rmi', 'all' ],
437
+ log: debug,
438
+ } );
439
+
440
+ spinner.text = 'Removing local files.';
441
+ // Note: there is a race condition where docker compose actually hasn't finished
442
+ // by this point, which causes rimraf to fail. We need to wait at least 2.5-5s,
443
+ // but using 10s in case it's dependent on the machine. Removing images takes
444
+ // longer so we use a longer wait time here.
445
+ await new Promise( ( resolve ) => setTimeout( resolve, 10000 ) );
446
+ await rimraf( config.workDirectoryPath );
447
+
448
+ spinner.text = 'Removed WordPress environment.';
449
+ }
450
+
451
+ /**
452
+ * Cleanup the Docker containers and remove local files, but preserve images.
453
+ *
454
+ * @param {WPConfig} config The wp-env config object.
455
+ * @param {Object} options Cleanup options.
456
+ * @param {Object} options.spinner A CLI spinner which indicates progress.
457
+ * @param {boolean} options.debug True if debug mode is enabled.
458
+ */
459
+ async cleanup( config, { spinner, debug } ) {
460
+ spinner.text = 'Removing docker containers, volumes, and networks.';
461
+
462
+ await dockerCompose.down( {
463
+ config: config.dockerComposeConfigPath,
464
+ commandOptions: [ '--volumes', '--remove-orphans' ],
465
+ log: debug,
466
+ } );
467
+
468
+ spinner.text = 'Removing local files.';
469
+ // Note: there is a race condition where docker compose actually hasn't finished
470
+ // by this point, which causes rimraf to fail. We need to wait at least 2.5-5s,
471
+ // but since we're not removing images, the wait can be shorter.
472
+ await new Promise( ( resolve ) => setTimeout( resolve, 3000 ) );
473
+ await rimraf( config.workDirectoryPath );
474
+
475
+ spinner.text = 'Cleaned up WordPress environment.';
476
+ }
477
+
478
+ /**
479
+ * Reset the WordPress database.
480
+ *
481
+ * @param {WPConfig} config The wp-env config object.
482
+ * @param {Object} options Reset options.
483
+ * @param {string} options.environment The environment to reset.
484
+ * @param {Object} options.spinner A CLI spinner which indicates progress.
485
+ * @param {boolean} options.debug True if debug mode is enabled.
486
+ */
487
+ async clean( config, { environment, spinner, debug } ) {
488
+ const fullConfig = await initConfig( {
489
+ spinner,
490
+ debug,
491
+ customConfigPath: config.customConfigPath,
492
+ } );
493
+
494
+ const testsEnabled = fullConfig.testsEnvironment !== false;
495
+
496
+ if ( ! testsEnabled && environment === 'tests' ) {
497
+ throw new Error(
498
+ 'Cannot reset the tests environment because it is disabled in the configuration.'
499
+ );
500
+ }
501
+
502
+ const description = `${ environment } environment${
503
+ environment === 'all' ? 's' : ''
504
+ }`;
505
+ spinner.text = `Resetting ${ description }.`;
506
+
507
+ const tasks = [];
508
+
509
+ // Start the appropriate MySQL service(s) first to avoid race conditions
510
+ // where parallel tasks try to create docker networks with the same name.
511
+ // The dependency chain (cli -> wordpress -> mysql with service_healthy)
512
+ // ensures MySQL is ready before database operations run.
513
+ const mysqlServices = [];
514
+ if ( environment === 'all' || environment === 'development' ) {
515
+ mysqlServices.push( 'mysql' );
516
+ }
517
+ if (
518
+ testsEnabled &&
519
+ ( environment === 'all' || environment === 'tests' )
520
+ ) {
521
+ mysqlServices.push( 'tests-mysql' );
522
+ }
523
+
524
+ await dockerCompose.upMany( mysqlServices, {
525
+ config: fullConfig.dockerComposeConfigPath,
526
+ log: fullConfig.debug,
527
+ } );
528
+
529
+ if ( environment === 'all' || environment === 'development' ) {
530
+ tasks.push(
531
+ resetDatabase( 'development', fullConfig )
532
+ .then( () =>
533
+ configureWordPress( 'development', fullConfig )
534
+ )
535
+ .catch( () => {} )
536
+ );
537
+ }
538
+
539
+ if (
540
+ testsEnabled &&
541
+ ( environment === 'all' || environment === 'tests' )
542
+ ) {
543
+ tasks.push(
544
+ resetDatabase( 'tests', fullConfig )
545
+ .then( () => configureWordPress( 'tests', fullConfig ) )
546
+ .catch( () => {} )
547
+ );
548
+ }
549
+
550
+ await Promise.all( tasks );
551
+
552
+ spinner.text = `Reset ${ description }.`;
553
+ }
554
+
555
+ /**
556
+ * Get the list of valid container names for the run command.
557
+ *
558
+ * @return {string[]} Array of valid container names.
559
+ */
560
+ getRunContainers() {
561
+ return RUN_CONTAINERS;
562
+ }
563
+
564
+ /**
565
+ * Run a command in a Docker container.
566
+ *
567
+ * @param {WPConfig} config The wp-env config object.
568
+ * @param {Object} options Run options.
569
+ * @param {string} options.container The container to run the command in.
570
+ * @param {string[]} options.command The command to run.
571
+ * @param {string} options.envCwd The working directory.
572
+ * @param {Object} options.spinner A CLI spinner which indicates progress.
573
+ * @param {boolean} options.debug True if debug mode is enabled.
574
+ */
575
+ async run( config, { container, command, envCwd, spinner, debug } ) {
576
+ // Validate the container name (throws for deprecated containers)
577
+ validateRunContainer( container );
578
+
579
+ if (
580
+ config.testsEnvironment === false &&
581
+ container.startsWith( 'tests-' )
582
+ ) {
583
+ throw new Error(
584
+ `Cannot run commands on "${ container }" because the tests environment is disabled in the configuration.`
585
+ );
586
+ }
587
+
588
+ const fullConfig = await initConfig( {
589
+ spinner,
590
+ debug,
591
+ customConfigPath: config.customConfigPath,
592
+ } );
593
+
594
+ // Shows a contextual tip for the given command.
595
+ const joinedCommand = command.join( ' ' );
596
+ this._showCommandTips( joinedCommand, container, spinner );
597
+
598
+ await this._spawnCommandDirectly(
599
+ fullConfig,
600
+ container,
601
+ command,
602
+ envCwd
603
+ );
604
+
605
+ spinner.text = `Ran \`${ joinedCommand }\` in '${ container }'.`;
606
+ }
607
+
608
+ /**
609
+ * Show logs from Docker containers.
610
+ *
611
+ * @param {WPConfig} config The wp-env config object.
612
+ * @param {Object} options Logs options.
613
+ * @param {string} options.environment The environment to show logs for.
614
+ * @param {boolean} options.watch If true, follow along with log output.
615
+ * @param {Object} options.spinner A CLI spinner which indicates progress.
616
+ * @param {boolean} options.debug True if debug mode is enabled.
617
+ */
618
+ async logs( config, { environment, watch, spinner, debug } ) {
619
+ const fullConfig = await initConfig( {
620
+ spinner,
621
+ debug,
622
+ customConfigPath: config.customConfigPath,
623
+ } );
624
+
625
+ const testsEnabled = fullConfig.testsEnvironment !== false;
626
+
627
+ if ( ! testsEnabled && environment === 'tests' ) {
628
+ throw new Error(
629
+ 'Cannot show logs for the tests environment because it is disabled in the configuration.'
630
+ );
631
+ }
632
+
633
+ // If we show text while watching the logs, it will continue showing up every
634
+ // few lines in the logs as they happen, which isn't a good look. So only
635
+ // show the message if we are not watching the logs.
636
+ if ( ! watch ) {
637
+ spinner.text = `Showing logs for the ${ environment } environment.`;
638
+ }
639
+
640
+ let servicesToWatch;
641
+ if ( environment === 'all' ) {
642
+ servicesToWatch = testsEnabled
643
+ ? [ 'tests-wordpress', 'wordpress' ]
644
+ : [ 'wordpress' ];
645
+ } else {
646
+ servicesToWatch = [
647
+ environment === 'tests' ? 'tests-wordpress' : 'wordpress',
648
+ ];
649
+ }
650
+
651
+ const output = await Promise.all( [
652
+ ...servicesToWatch.map( ( service ) =>
653
+ dockerCompose.logs( service, {
654
+ config: fullConfig.dockerComposeConfigPath,
655
+ log: watch, // Must log inline if we are watching the log output.
656
+ commandOptions: watch ? [ '--follow' ] : [],
657
+ } )
658
+ ),
659
+ ] );
660
+
661
+ // Combine the results from each docker output.
662
+ const result = output.reduce(
663
+ ( acc, current ) => {
664
+ if ( current.out ) {
665
+ acc.out = acc.out.concat( current.out );
666
+ }
667
+ if ( current.err ) {
668
+ acc.err = acc.err.concat( current.err );
669
+ }
670
+ if ( current.exitCode !== 0 ) {
671
+ acc.hasNon0ExitCode = true;
672
+ }
673
+ return acc;
674
+ },
675
+ { out: '', err: '', hasNon0ExitCode: false }
676
+ );
677
+
678
+ if ( result.out.length ) {
679
+ console.log(
680
+ process.stdout.isTTY ? `\n\n${ result.out }\n\n` : result.out
681
+ );
682
+ } else if ( result.err.length ) {
683
+ console.error(
684
+ process.stdout.isTTY ? `\n\n${ result.err }\n\n` : result.err
685
+ );
686
+ if ( result.hasNon0ExitCode ) {
687
+ throw result.err;
688
+ }
689
+ }
690
+
691
+ spinner.text = 'Finished showing logs.';
692
+ }
693
+
694
+ /**
695
+ * Get the status of the Docker environment.
696
+ *
697
+ * @param {WPConfig} config The wp-env config object.
698
+ * @param {Object} options Status options.
699
+ * @param {Object} options.spinner A CLI spinner which indicates progress.
700
+ * @param {boolean} options.debug True if debug mode is enabled.
701
+ * @return {Promise<Object>} Status object with environment information.
702
+ */
703
+ async getStatus( config, { spinner, debug } ) {
704
+ spinner.text = 'Getting environment status.';
705
+
706
+ const fullConfig = await initConfig( {
707
+ spinner,
708
+ debug,
709
+ customConfigPath: config.customConfigPath,
710
+ } );
711
+ const dockerComposeConfig = {
712
+ config: fullConfig.dockerComposeConfigPath,
713
+ log: debug,
714
+ };
715
+
716
+ // Check if containers are running by trying to get a port.
717
+ let isRunning = false;
718
+ let mySQLPort = null;
719
+ let phpmyadminPort = null;
720
+
721
+ try {
722
+ mySQLPort = await this._getPublicDockerPort(
723
+ 'mysql',
724
+ 3306,
725
+ dockerComposeConfig
726
+ );
727
+ isRunning = true;
728
+
729
+ if ( fullConfig.env.development.phpmyadminPort ) {
730
+ phpmyadminPort = await this._getPublicDockerPort(
731
+ 'phpmyadmin',
732
+ 80,
733
+ dockerComposeConfig
734
+ );
735
+ }
736
+ } catch {
737
+ // Containers are not running.
738
+ }
739
+
740
+ const siteUrl = fullConfig.env.development.config.WP_SITEURL;
741
+
742
+ const testsEnabled = fullConfig.testsEnvironment !== false;
743
+
744
+ return {
745
+ status: isRunning ? 'running' : 'stopped',
746
+ runtime: 'docker',
747
+ urls: {
748
+ development: isRunning ? siteUrl : null,
749
+ phpmyadmin:
750
+ isRunning && phpmyadminPort
751
+ ? `http://localhost:${ phpmyadminPort }`
752
+ : null,
753
+ },
754
+ ports: {
755
+ development: fullConfig.env.development.port,
756
+ ...( testsEnabled && {
757
+ tests: fullConfig.env.tests.port,
758
+ } ),
759
+ mysql: mySQLPort,
760
+ },
761
+ config: {
762
+ multisite: fullConfig.env.development.multisite,
763
+ xdebug: fullConfig.xdebug || 'off',
764
+ },
765
+ configPath: fullConfig.configDirectoryPath,
766
+ installPath: fullConfig.workDirectoryPath,
767
+ };
768
+ }
769
+
770
+ /**
771
+ * Runs an arbitrary command on the given Docker container.
772
+ *
773
+ * @param {WPConfig} config The wp-env configuration.
774
+ * @param {string} container The Docker container to run the command on.
775
+ * @param {string[]} command The command to run.
776
+ * @param {string} envCwd The working directory for the command.
777
+ * @return {Promise} Promise that resolves when the command completes.
778
+ */
779
+ _spawnCommandDirectly( config, container, command, envCwd ) {
780
+ // Both the `wordpress` and `tests-wordpress` containers have the host's
781
+ // user so that they can maintain ownership parity with the host OS.
782
+ // We should run any commands as that user so that they are able
783
+ // to interact with the files mounted from the host.
784
+ const hostUser = getHostUser();
785
+
786
+ // Since Docker requires absolute paths, we should resolve the input to a POSIX path.
787
+ // This is needed because Windows resolves relative paths from the C: drive.
788
+ envCwd = path.posix.resolve(
789
+ // Not all containers have the same starting working directory.
790
+ container === 'mysql' || container === 'tests-mysql'
791
+ ? '/'
792
+ : '/var/www/html',
793
+ // Remove spaces and single quotes from both ends of the path.
794
+ // This is needed because Windows treats single quotes as a literal character.
795
+ envCwd.trim().replace( /^'|'$/g, '' )
796
+ );
797
+
798
+ const composeCommand = [
799
+ 'compose',
800
+ '-f',
801
+ config.dockerComposeConfigPath,
802
+ 'exec',
803
+ '-w',
804
+ envCwd,
805
+ '--user',
806
+ hostUser.fullUser,
807
+ ];
808
+
809
+ if ( ! process.stdout.isTTY ) {
810
+ composeCommand.push( '-T' );
811
+ }
812
+
813
+ composeCommand.push( container, ...command );
814
+
815
+ return new Promise( ( resolve, reject ) => {
816
+ // Note: since the npm docker-compose package uses the -T option, we
817
+ // cannot use it to spawn an interactive command. Thus, we run docker-
818
+ // compose on the CLI directly.
819
+ const childProc = spawn( 'docker', composeCommand, {
820
+ stdio: 'inherit',
821
+ } );
822
+ childProc.on( 'error', reject );
823
+ childProc.on( 'exit', ( code ) => {
824
+ // Code 130 is set if the user tries to exit with ctrl-c before using
825
+ // ctrl-d (so it is not an error which should fail the script.)
826
+ if ( code === 0 || code === 130 ) {
827
+ resolve();
828
+ } else {
829
+ reject( `Command failed with exit code ${ code }` );
830
+ }
831
+ } );
832
+ } );
833
+ }
834
+
835
+ /**
836
+ * This shows a contextual tip for the command being run. Certain commands (like
837
+ * bash) may have weird behavior (exit with ctrl-d instead of ctrl-c or ctrl-z),
838
+ * so we want the user to have that information without having to ask someone.
839
+ *
840
+ * @param {string} joinedCommand The command joined by spaces.
841
+ * @param {string} container The container the command will be run on.
842
+ * @param {Object} spinner A spinner object to show progress.
843
+ */
844
+ _showCommandTips( joinedCommand, container, spinner ) {
845
+ if ( ! joinedCommand.length ) {
846
+ return;
847
+ }
848
+
849
+ const tip = `Starting '${ joinedCommand }' on the ${ container } container. ${ ( () => {
850
+ switch ( joinedCommand ) {
851
+ case 'bash':
852
+ return 'Exit bash with ctrl-d.';
853
+ case 'wp shell':
854
+ return 'Exit the WordPress shell with ctrl-c.';
855
+ default:
856
+ return '';
857
+ }
858
+ } )() }\n`;
859
+ spinner.info( tip );
860
+ }
861
+ }
862
+
863
+ module.exports = DockerRuntime;