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