forked from universityofadelaide/shepherd-drupal-scaffold
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RoboFileBase.php
673 lines (592 loc) · 20.1 KB
/
RoboFileBase.php
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
<?php
/**
* @file
* Contains \Robo\RoboFileBase.
*
* Implementation of class for Robo - http://robo.li/
*/
/**
* Class RoboFileBase.
*/
abstract class RoboFileBase extends \Robo\Tasks {
protected $drush_cmd;
protected $drush_bin = "bin/drush";
protected $composer_bin = "composer";
/**
* The path to the phpcs command.
*
* @var string
*/
protected $phpcsCmd = 'bin/phpcs';
/**
* The path to the phpcbf command.
*
* @var string
*/
protected $phpcbfCmd = 'bin/phpcbf';
/**
* The phpstan command.
*
* @var string
*/
protected $phpstanCmd = 'php ./bin/phpstan analyze --no-progress';
protected $php_enable_module_command = 'phpenmod -v ALL';
protected $php_disable_module_command = 'phpdismod -v ALL';
protected $application_root = "/code/web";
protected $file_public_path = '/shared/public';
protected $file_private_path = '/shared/private';
protected $file_temp_path = '/shared/tmp';
protected $services_yml = "web/sites/default/services.yml";
protected $config = [];
protected $config_new_directory = 'config_new';
protected $config_old_directory = 'config_old';
/**
* The path to the config dir.
*
* @var string
*/
protected $configDir = '/code/config-export';
/**
* The path to the config install dir.
*
* @var string
*/
protected $configInstallDir = '/code/config-install';
/**
* The path to the config delete list.
*
* @var string
*/
protected $configDeleteList = '/code/drush/config-delete.yml';
/**
* The path to the config delete list.
*
* @var string
*/
protected $configIgnoreList = '/code/drush/config-ignore.yml';
/**
* Initialize config variables and apply overrides.
*/
public function __construct() {
$this->drush_cmd = $this->drush_bin;
// Read config from env vars.
$environment_config = $this->readConfigFromEnv();
$this->config = array_merge($this->config, $environment_config);
}
/**
* Force projects to declare which install profile to use.
*
* I.e. return 'some_profile'.
*/
protected function getDrupalProfile() {
$profile = getenv('SHEPHERD_INSTALL_PROFILE');
if (empty($profile)) {
$this->say("Install profile environment variable is not set.\n");
exit(1);
}
return $profile;
}
/**
* Returns known configuration from environment variables.
*
* Runs during the constructor; be careful not to use Robo methods.
*/
protected function readConfigFromEnv() {
$config = [];
// Site.
$config['site']['title'] = getenv('SITE_TITLE');
$config['site']['mail'] = getenv('SITE_MAIL');
$config['site']['admin_email'] = getenv('SITE_ADMIN_EMAIL');
$config['site']['admin_user'] = getenv('SITE_ADMIN_USERNAME');
$config['site']['admin_password'] = getenv('SITE_ADMIN_PASSWORD');
// Environment.
$config['environment']['hash_salt'] = getenv('HASH_SALT');
// Clean up NULL values and empty arrays.
$array_clean = function (&$item) use (&$array_clean) {
foreach ($item as $key => $value) {
if (is_array($value)) {
$array_clean($item[$key]);
}
if (empty($item[$key]) && $value !== '0') {
unset($item[$key]);
}
}
};
$array_clean($config);
return $config;
}
/**
* Perform a full build on the project.
*/
public function build() {
$start = new DateTime();
$this->devXdebugDisable();
$this->devComposerValidate();
$this->buildMake();
$this->ensureDirectories();
$this->buildInstall();
$this->configImportPlus();
$this->devCacheRebuild();
$this->ensureDirectories();
$this->devXdebugEnable();
$this->say('Total build duration: ' . date_diff(new DateTime(), $start)->format('%im %Ss'));
}
/**
* Perform a build for automated deployments.
*
* Don't install anything, just build the code base.
*/
public function distributionBuild() {
$this->devComposerValidate();
$this->buildMake('--prefer-dist --no-suggest --no-dev --optimize-autoloader');
$this->setSitePath();
}
/**
* Validate composer files and installed dependencies with strict mode off.
*/
public function devComposerValidate() {
$this->taskComposerValidate()
->noCheckPublish()
->run()
->stopOnFail(TRUE);
}
/**
* Run composer install to fetch the application code from dependencies.
*
* @param string $flags
* Additional flags to pass to the composer install command.
*/
public function buildMake($flags = '') {
$successful = $this->_exec("$this->composer_bin --no-progress --no-interaction $flags install")->wasSuccessful();
$this->checkFail($successful, "Composer install failed.");
}
/**
* Set the owner and group of all files in the files dir to the web user.
*/
public function ensureDirectories() {
$publicDir = getenv('PUBLIC_DIR') ?: $this->file_public_path;
$privateDir = getenv('PRIVATE_DIR') ?: $this->file_private_path;
$tmpDir = getenv('TMP_DIR') ?: $this->file_temp_path;
foreach ([$publicDir, $privateDir, $tmpDir] as $path) {
$this->say("Ensuring all directories exist.");
$this->_exec("mkdir -p $path");
$this->say("Setting directory permissions.");
$this->setPermissions($path, '0775');
}
}
/**
* Set the owner and group of all files in the files dir to the web user.
*
* @deprecated Use ::ensureDirectories instead.
*/
public function buildSetFilesOwner() {
$this->ensureDirectories();
}
/**
* Clean config and files, then install Drupal and module dependencies.
*/
public function buildInstall() {
$this->devConfigWriteable();
// @TODO: When is this really used? Automated builds - can be random values.
$successful = $this->_exec("$this->drush_cmd site-install " .
$this->getDrupalProfile() .
" install_configure_form.enable_update_status_module=NULL" .
" install_configure_form.enable_update_status_emails=NULL" .
" -y" .
" --account-mail=\"" . $this->config['site']['admin_email'] . "\"" .
" --account-name=\"" . $this->config['site']['admin_user'] . "\"" .
" --account-pass=\"" . $this->config['site']['admin_password'] . "\"" .
" --site-name=\"" . $this->config['site']['title'] . "\"" .
" --site-mail=\"" . $this->config['site']['mail'] . "\"")
->wasSuccessful();
// Re-set settings.php permissions.
$this->devConfigReadOnly();
$this->checkFail($successful, 'drush site-install failed.');
$this->devCacheRebuild();
}
/**
* Set the RewriteBase value in .htaccess appropriate for the site.
*
* @TODO: Will OpenShift router deal with this for us?
*/
public function setSitePath() {
if (strlen($this->config['site']['path']) > 0) {
$this->say("Setting site path.");
$successful = $this->taskReplaceInFile("$this->application_root/.htaccess")
->from('# RewriteBase /drupal')
->to("\n RewriteBase /" . ltrim($this->config['site']['path'], '/') . "\n")
->run();
$this->checkFail($successful, "Couldn't update .htaccess file with path.");
}
}
/**
* Clean the application root in preparation for a new build.
*/
public function buildClean() {
$this->setPermissions("$this->application_root/sites/default", '0755');
$this->_exec("rm -fR $this->application_root/core");
$this->_exec("rm -fR $this->application_root/modules/contrib");
$this->_exec("rm -fR $this->application_root/profiles/contrib");
$this->_exec("rm -fR $this->application_root/themes/contrib");
$this->_exec("rm -fR $this->application_root/sites/all");
$this->_exec("rm -fR bin");
$this->_exec("rm -fR vendor");
}
/**
* Run all the drupal updates against a build.
*/
public function buildApplyUpdates() {
// Run the module updates.
$successful = $this->_exec("$this->drush_cmd -y updatedb")->wasSuccessful();
$this->checkFail($successful, 'running drupal updates failed.');
}
/**
* Perform cache clear in the app directory.
*/
public function devCacheRebuild() {
$successful = $this->_exec("$this->drush_cmd cr")->wasSuccessful();
$this->checkFail($successful, 'drush cache-rebuild failed.');
}
/**
* Ask a couple of questions and then configure git.
*/
public function devInit() {
$this->say("Initial project setup. Adds user details to gitconfig.");
$git_name = $this->ask("Enter your Git name (e.g. Bob Rocks):");
$git_email = $this->ask("Enter your Git email (e.g. [email protected]):");
$this->_exec("git config --global user.name \"$git_name\"");
$this->_exec("git config --global user.email \"$git_email\"");
// Automatically initialise git flow.
$git_config = file_get_contents('.git/config');
if (!strpos($git_config, '[gitflow')) {
$this->taskWriteToFile(".git/config")
->append()
->text("\n[gitflow \"branch\"]\n" .
" master = master\n" .
" develop = develop\n" .
"[gitflow \"prefix\"]\n" .
" feature = feature/\n" .
" release = release/\n" .
" hotfix = hotfix/\n" .
" support = support/\n" .
" versiontag = \n")
->run();
}
}
/**
* Install Adminer for database administration.
*/
public function devInstallAdminer() {
$this->taskFilesystemStack()
->remove("$this->application_root/adminer.php")
->run();
$this->taskExec("wget -q -O adminer.php http://www.adminer.org/latest-mysql-en.php")
->dir($this->application_root)
->run();
}
/**
* CLI debug enable.
*/
public function devXdebugEnable() {
// Only run this on environments configured with xdebug.
if (getenv('XDEBUG_CONFIG')) {
$this->_exec("sudo $this->php_enable_module_command -s cli xdebug");
}
}
/**
* CLI debug disable.
*/
public function devXdebugDisable() {
// Only run this on environments configured with xdebug.
if (getenv('XDEBUG_CONFIG')) {
$this->_exec("sudo $this->php_disable_module_command -s cli xdebug");
}
}
/**
* Export the current configuration to an 'old' directory.
*/
public function configExportOld() {
$this->configExport($this->config_old_directory);
}
/**
* Export the current configuration to a 'new' directory.
*/
public function configExportNew() {
$this->configExport($this->config_new_directory);
}
/**
* Export config to a supplied directory.
*
* @param string $destination
* The folder within the application root.
*/
protected function configExport($destination = NULL) {
$this->yell('This command is deprecated, you should use config:export-plus instead', 40, 'red');
if ($destination) {
$this->_exec("$this->drush_cmd -y cex --destination=" . $destination);
$this->_exec("sed -i '/^uuid:.*$/d; /^_core:$/, /^.*default_config_hash:.*$/d' $this->application_root/$destination/*.yml");
}
}
/**
* Display files changed between 'config_old' and 'config_new' directories.
*
* @param array $opts
* Specify whether to show the diff output or just list them.
*
* @return array
* Diff output as an array of strings.
*/
public function configChanges($opts = ['show|s' => FALSE]) {
$this->yell('This command is deprecated, you should use config:export-plus and config:import-plus instead', 40, 'red');
$output_style = '-qbr';
$config_old_path = $this->application_root . '/' . $this->config_old_directory;
$config_new_path = $this->application_root . '/' . $this->config_new_directory;
if (isset($opts['show']) && $opts['show']) {
$output_style = '-ubr';
}
$results = $this->taskExec("diff -N -I \" - 'file:.*\" $output_style $config_old_path $config_new_path")
->run()
->getMessage();
$results_array = explode("\n", $results);
return $results_array;
}
/**
* Synchronise active config to the install profile or specified path.
*
* Synchronise the differences from the configured 'config_new' and
* 'config_old' directories into the install profile or a specific path.
*
* @param array $path
* If the sync is to update an entity instead of a profile, supple a path.
*/
public function configSync($path = NULL) {
$this->yell('This command is deprecated, you should use config:export-plus and config:import-plus instead', 40, 'red');
$config_sync_already_run = FALSE;
$output_path = $this->application_root . '/profiles/' . $this->getDrupalProfile() . '/config/install';
$config_new_path = $this->application_root . '/' . $this->config_new_directory;
// If a path is passed in, use it to override the destination.
if (!empty($path) && is_dir($path)) {
$output_path = $path;
}
$results_array = $this->configChanges();
$tasks = $this->taskFilesystemStack();
foreach ($results_array as $line) {
// Handle/remove blank lines.
$line = trim($line);
if (empty($line)) {
continue;
}
// Never sync the extension file, it breaks things.
if (stristr($line, 'core.extension.yml')) {
continue;
}
// Break up the line into fields and put the parts in their place.
$parts = explode(' ', $line);
$config_new_file = $parts[3];
$output_file_path = $output_path .
preg_replace("/^" . str_replace('/', '\/', $config_new_path) ."/", '', $config_new_file);
// If the source doesn't exist, we're removing it from the
// destination in the profile.
if (!file_exists($config_new_file)) {
if (file_exists($output_file_path)) {
$tasks->remove($output_file_path);
}
else {
$config_sync_already_run = TRUE;
}
}
else {
$tasks->copy($config_new_file, $output_file_path);
}
}
if ($config_sync_already_run) {
$this->say("Config sync already run?");
}
$tasks->run();
}
/**
* Imports configuration using advanced drush commands.
*
* Commands provided by previousnext/drush_cmi_tools.
*
* @see https://github.com/previousnext/drush_cmi_tools
*/
public function configImportPlus() {
$successful = $this->_exec("$this->drush_cmd cimy -y \
--source=$this->configDir \
--install=$this->configInstallDir \
--delete-list=$this->configDeleteList")
->wasSuccessful();
$this->checkFail($successful, 'Config import failed.');
}
/**
* Exports configuration using advanced drush commands.
*
* Commands provided by previousnext/drush_cmi_tools.
*
* @see https://github.com/previousnext/drush_cmi_tools
*/
public function configExportPlus() {
$this->_exec("$this->drush_cmd cexy -y --destination=$this->configDir --ignore-list=$this->configIgnoreList");
}
/**
* Turns on twig debug mode, autoreload on and caching off.
*/
public function devTwigDebugEnable() {
$this->devConfigWriteable();
$this->taskReplaceInFile($this->services_yml)
->from('debug: false')
->to('debug: true')
->run();
$this->taskReplaceInFile($this->services_yml)
->from('auto_reload: null')
->to('auto_reload: true')
->run();
$this->taskReplaceInFile($this->services_yml)
->from('cache: true')
->to('cache: false')
->run();
$this->devAggregateAssetsDisable();
$this->devConfigReadOnly();
$this->say('Clearing Drupal cache...');
$this->devCacheRebuild();
$this->say('Done. Twig debugging has been enabled');
}
/**
* Turn off twig debug mode, autoreload off and caching on.
*/
public function devTwigDebugDisable() {
$this->devConfigWriteable();
$this->taskReplaceInFile($this->services_yml)
->from('debug: true')
->to('debug: false')
->run();
$this->taskReplaceInFile($this->services_yml)
->from('auto_reload: true')
->to('auto_reload: null')
->run();
$this->taskReplaceInFile($this->services_yml)
->from('c: false')
->to('cache: true')
->run();
$this->devConfigReadOnly();
$this->say('Clearing Drupal cache...');
$this->devCacheRebuild();
$this->say('Done. Twig debugging has been disabled');
}
/**
* Disable asset aggregation.
*/
public function devAggregateAssetsDisable() {
$this->taskExecStack()
->exec($this->drush_cmd . ' cset system.performance js.preprocess 0 -y')
->exec($this->drush_cmd . ' cset system.performance css.preprocess 0 -y')
->run();
$this->devCacheRebuild();
$this->say('Asset Aggregation is now disabled.');
}
/**
* Enable asset aggregation.
*/
public function devAggregateAssetsEnable() {
$this->taskExecStack()
->exec($this->drush_cmd . ' cset system.performance js.preprocess 1 -y')
->exec($this->drush_cmd . ' cset system.performance css.preprocess 1 -y')
->run();
$this->devCacheRebuild();
$this->say('Asset Aggregation is now enabled.');
}
/**
* Make config files write-able.
*/
public function devConfigWriteable() {
$this->setPermissions("$this->application_root/sites/default/services.yml", '0664');
$this->setPermissions("$this->application_root/sites/default/settings.php", '0664');
$this->setPermissions("$this->application_root/sites/default/settings.local.php", '0664');
$this->setPermissions("$this->application_root/sites/default", '0775');
}
/**
* Make config files read only.
*/
public function devConfigReadOnly() {
$this->setPermissions("$this->application_root/sites/default/services.yml", '0444');
$this->setPermissions("$this->application_root/sites/default/settings.php", '0444');
$this->setPermissions("$this->application_root/sites/default/settings.local.php", '0444');
$this->setPermissions("$this->application_root/sites/default", '0555');
}
/**
* Imports a database, updates the admin user password and applies updates.
*
* @param string $sql_file
* Path to sql file to import.
*/
public function devImportDb($sql_file) {
$start = new DateTime();
$this->_exec("$this->drush_cmd -y sql-drop");
$this->_exec("$this->drush_cmd sqlq --file=$sql_file");
$this->_exec("$this->drush_cmd cr");
$this->_exec("$this->drush_cmd updb --entity-updates -y");
$this->say('Duration: ' . date_diff(new DateTime(), $start)->format('%im %Ss'));
$this->_exec("$this->drush_cmd upwd admin password");
$this->say('Database imported, admin user password is : password');
}
/**
* Exports a database and gzips the sql file.
*
* @param string $name
* Name of sql file to be exported.
*/
public function devExportDb($name = 'dump') {
$start = new DateTime();
$this->_exec("$this->drush_cmd sql-dump --gzip --result-file=$name.sql");
$this->say("Duration: " . date_diff(new DateTime(), $start)->format('%im %Ss'));
$this->say("Database $name.sql.gz exported");
}
/**
* Run coding standards checks for PHP files on the project.
*
* @param string $path
* An optional path to lint.
*/
public function lintPhp($path = '') {
$this->checkFail($this->_exec("$this->phpcsCmd $path")->wasSuccessful(), 'Code linting failed');
$this->checkFail($this->_exec($this->phpstanCmd)->wasSuccessful(), 'Code analyzing failed');
}
/**
* Fix coding standards violations for PHP files on the project.
*
* @param string $path
* An optional path to fix.
*/
public function lintFix($path = '') {
$this->_exec("$this->phpcbfCmd $path");
}
/**
* Check if file exists and set permissions.
*
* @param string $file
* File to modify.
* @param string $permission
* Permissions. E.g. '0644'.
*/
protected function setPermissions($file, $permission) {
if (file_exists($file)) {
$this->_exec("chmod $permission $file");
}
}
/**
* Helper function to check whether a task has completed successfully.
*
* @param bool $successful
* Task ran successfully or not.
* @param string $message
* Optional: A helpful message to print.
*/
protected function checkFail($successful, $message = '') {
if (!$successful) {
$this->say('APP_ERROR: ' . $message);
// Prevent any other tasks from executing.
exit(1);
}
}
}