-
Notifications
You must be signed in to change notification settings - Fork 40
/
DeploymentTrait.php
735 lines (651 loc) · 26.2 KB
/
DeploymentTrait.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
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
<?php
namespace RoboComponents;
use Symfony\Component\Yaml\Yaml;
/**
* Deployment tailored to Pantheon.io.
*/
trait DeploymentTrait {
/**
* The wait time between deployment checks in microseconds.
*
* @var int
*/
public static int $deploymentWaitTime = 500000;
/**
* The maximum number of retries when waiting after git push.
*
* @var int
*/
public static int $codeSyncWaitMaxRetries = 20;
/**
* The GitHub project slug.
*
* @var string
*/
public static string $githubProject = 'Gizra/drupal-starter';
/**
* The files / directories to exclude from deployment.
*
* @var array|string[]
*/
public static array $deploySyncExcludes = [
'.bootstrap-fast.php',
'.ddev',
'.editorconfig',
'.git',
'.idea',
'.pantheon',
'.phpunit.result.cache',
'.travis.yml',
'ci-scripts',
'pantheon.upstream.yml',
'phpstan.neon',
'phpunit.xml.dist',
'README.md',
'RoboFile.php',
'server.es.secrets.json',
'travis-key.enc',
'travis-key',
'web/.csslintrc',
'web/.eslintignore',
'web/.eslintrc.json',
'web/example.gitignore',
'web/INSTALL.txt',
'web/modules/README.txt',
'web/profiles/README.txt',
'web/README.md',
'web/README.txt',
'web/sites/default',
'web/sites/simpletest',
'web/sites/README.txt',
'web/themes/README.txt',
'web/themes/custom/server_theme/src',
'web/themes/custom/server_theme/node_modules',
'web/themes/custom/server_theme/package.json',
'web/themes/custom/server_theme/package-lock.json',
'web/themes/custom/server_theme/tailwind.config.js',
'web/themes/custom/server_theme/postcss.config.js',
'node_modules',
'mass_patch.sh',
'package.json',
'package-lock.json',
'composer.json',
'composer.lock',
];
/**
* Deploy a tag (specific release) to Pantheon.
*
* @param string $tag
* The tag name in the current repository.
* @param string $branch_name
* The branch name from Pantheon repository.
* @param string|null $commit_message
* Supply a custom commit message for the pantheon repo.
*
* @throws \Exception
*/
public function deployTagPantheon(string $tag, string $branch_name = 'master', ?string $commit_message = NULL): void {
$result = $this
->taskExec('git status -s')
->printOutput(FALSE)
->run();
if ($result->getMessage()) {
$this->say($result->getMessage());
throw new \Exception('The working directory is dirty. Please commit or stash the pending changes.');
}
$this->taskExec("git checkout $tag")->run();
// Full installation with dev dependencies as we need some of them for the
// build.
$this->taskExec("rm -rf vendor web/core web/libraries web/modules/contrib && composer install")->run();
if (empty($commit_message)) {
$commit_message = 'Release ' . $tag;
}
// Set default exit code to 0 (success).
$exit = 0;
try {
$this->deployPantheon($branch_name, $commit_message);
}
catch (\Exception $e) {
$this->yell('The deployment failed', 22, 'red');
$this->say($e->getMessage());
// Set exit code to 1 (error).
$exit = 1;
}
// Check out the original branch regardless of success or failure.
$this->taskExec("git checkout -")->run();
// Exit.
$this->taskExec("exit $exit")->run();
}
/**
* Deploy to Pantheon.
*
* @param string $branch_name
* The branch name to commit to.
* @param string|null $commit_message
* Supply a custom commit message for the pantheon repo.
* Falls back to: "Site update from [current_version]".
*
* @throws \Exception
*/
public function deployPantheon(string $branch_name = 'master', ?string $commit_message = NULL): void {
$pantheon_directory = '.pantheon';
$deployment_version_path = $pantheon_directory . '/.deployment';
if (!file_exists($pantheon_directory) || !is_dir($pantheon_directory)) {
throw new \Exception('Clone the Pantheon artifact repository first into the .pantheon directory');
}
$result = $this
->taskExec('git status -s')
->printOutput(FALSE)
->run();
if ($result->getMessage()) {
$this->say($result->getMessage());
throw new \Exception('The Pantheon directory is dirty. Please commit any pending changes.');
}
$result = $this
->taskExec("cd $pantheon_directory && git status -s")
->printOutput(FALSE)
->run();
if ($result->getMessage()) {
$this->say($result->getMessage());
throw new \Exception('The Pantheon directory is dirty. Please commit any pending changes.');
}
// Validate pantheon.yml has web_docroot: true.
if (!file_exists($pantheon_directory . '/pantheon.yml')) {
throw new \Exception("pantheon.yml is missing from the Pantheon directory ($pantheon_directory)");
}
$yaml = Yaml::parseFile($pantheon_directory . '/pantheon.yml');
if (empty($yaml['web_docroot'])) {
throw new \Exception("'web_docroot: true' is missing from pantheon.yml in Pantheon directory ($pantheon_directory)");
}
$this->_exec("cd $pantheon_directory && git checkout $branch_name");
// We deal with versions as commit hashes.
// The high-level goal is to prevent the auto-deploy process
// to overwrite the code with an older version if the Travis queue
// swaps the order of two jobs, so they are not executed in
// chronological order.
$currently_deployed_version = NULL;
if (file_exists($deployment_version_path)) {
$currently_deployed_version = trim(file_get_contents($deployment_version_path));
}
$result = $this
->taskExec('git rev-parse HEAD')
->printOutput(FALSE)
->run();
$current_version = trim($result->getMessage());
if (!empty($currently_deployed_version)) {
$result = $this
->taskExec('git cat-file -t ' . $currently_deployed_version)
->printOutput(FALSE)
->run();
if ($result->getMessage() !== 'commit') {
$this->yell(strtr('This current commit @current-commit cannot be deployed, since new commits have been created since, so we don\'t want to deploy an older version. Result was: @result', [
'@current-commit' => $current_version,
'@result' => $result->getMessage(),
]));
throw new \Exception('Aborting the process to avoid going back in time.');
}
}
// Ensure the dev dependencies are installed before compiling the theme in
// case this is a retry.
$this->taskExec('composer install')->run();
// Compile theme.
$this->themeCompile();
// Remove the dev dependencies before pushing up to Pantheon.
$this->taskExec("composer install --no-dev")->run();
$rsync_exclude_string = '--exclude=' . implode(' --exclude=', self::$deploySyncExcludes);
// Copy all files and folders.
$result = $this->_exec("rsync -az -q --delete $rsync_exclude_string . $pantheon_directory")->getExitCode();
if ($result !== 0) {
throw new \Exception('File sync failed');
}
// The settings.pantheon.php is managed by Pantheon, there can be updates,
// site-specific modifications belong to settings.php.
$this->_exec("cp web/sites/default/settings.pantheon.php $pantheon_directory/web/sites/default/settings.php");
// Flag the current version in the artifact repo.
file_put_contents($deployment_version_path, $current_version);
// We don't want to change Pantheon's git ignore, as we do want to commit
// vendor and contrib directories.
// @todo Ignore it from rsync, but './.gitignore' didn't work.
$this->_exec("cd $pantheon_directory && git checkout .gitignore");
// Also we need to clean up gitignores that are deeper in the tree,
// those can be troublemakers too, it also purges various Git helper
// files that are irrelevant here.
$this->_exec("cd $pantheon_directory && (find . | grep \"\.git\" | grep -v \"^./.git\" | xargs rm -rf || true)");
$this->_exec("cd $pantheon_directory && git status");
$commit_and_deploy_confirm = $this->confirm('Commit changes and deploy?', TRUE);
if (!$commit_and_deploy_confirm) {
$this->say('Aborted commit and deploy, you can do it manually');
// The Pantheon repo is dirty, so check if we want to clean it up before
// exit.
$cleanup_pantheon_directory_confirm = $this->confirm("Revert any changes on $pantheon_directory directory (i.e. `git checkout .`)?");
if (!$cleanup_pantheon_directory_confirm) {
// Keep folder as is.
return;
}
// We repeat "git clean" twice, as sometimes it seems that a single one
// doesn't remove all directories.
$this->_exec("cd $pantheon_directory && git checkout . && git clean -fd && git clean -fd && git status");
return;
}
if (empty($commit_message)) {
$tag = $this->taskExec("git tag --points-at HEAD")
->printOutput(FALSE)
->run()
->getMessage();
if (empty($tag)) {
$commit_message = 'Site update from ' . $current_version;
}
else {
$commit_message = "Site update from $tag ($current_version)";
}
}
$commit_message = escapeshellarg($commit_message);
$result = $this->taskExec("cd $pantheon_directory && git pull && git add . && git commit -am $commit_message && git push")
->printOutput(FALSE)
->run();
if (str_contains($result->getMessage(), 'nothing to commit, working tree clean')) {
$this->say('Nothing to commit, working tree clean');
}
print $result->getMessage();
if ($result->getExitCode() !== 0) {
throw new \Exception('Pushing to the remote repository failed');
}
// Let's wait until the code is deployed to the environment.
// This "git push" above is as async operation, so prevent invoking
// for instance drush cim before the new changes are there.
usleep(self::$deploymentWaitTime);
$pantheon_env = $branch_name == 'master' ? 'dev' : $branch_name;
$this->waitForCodeDeploy($pantheon_env);
$this->deployPantheonSync($pantheon_env, FALSE);
}
/**
* Waits until no code sync is running.
*
* @param string $env
* The environment to wait for.
*/
protected function waitForCodeDeploy(string $env) {
$pantheon_info = $this->getPantheonNameAndEnv();
$attempt = 0;
$code_sync_completed = FALSE;
do {
$attempt++;
$result = $this->taskExec("terminus workflow:list " . $pantheon_info['name'] . " --format=json --fields=env,status,workflow")->printOutput(FALSE)->run();
if ($result->getExitCode() !== 0) {
$this->yell('Getting workflow list failed');
continue;
}
$result = json_decode($result->getMessage(), TRUE);
$workflows = array_filter($result, function ($workflow) use ($env) {
// When there's a git push, there's a "Sync code" workflow that
// needs to be completed, before we can rely on the code being
// present.
return $workflow['env'] == $env && $workflow['status'] == 'running' && str_contains($workflow['workflow'], 'Sync ') !== FALSE;
});
$this->say(print_r($workflows, TRUE));
$code_sync_completed = empty($workflows);
usleep(self::$deploymentWaitTime);
} while (!$code_sync_completed && $attempt < self::$codeSyncWaitMaxRetries);
}
/**
* Get the Pantheon name and environment.
*
* @return array
* Array keyed by `name` and `env`.
*
* @throws \Exception
*/
protected function getPantheonNameAndEnv() : array {
$yaml = Yaml::parseFile('./.ddev/providers/pantheon.yaml');
if (empty($yaml['environment_variables']['project'])) {
throw new \Exception("`environment_variables.project` is missing from .ddev/providers/pantheon.yaml");
}
$project = explode('.', $yaml['environment_variables']['project'], 2);
if (count($project) !== 2) {
throw new \Exception("`environment_variables.project` should be in the format of `yourproject.dev`");
}
return [
'name' => $project[0],
'env' => $project[1],
];
}
/**
* Deploy site from one env to the other on Pantheon.
*
* @param string $env
* The environment to update.
* @param bool $do_deploy
* Determine if 'terminus env:deploy' should be run on the given env.
*
* @throws \Exception
*/
public function deployPantheonSync(string $env = 'test', bool $do_deploy = TRUE): void {
$pantheon_info = $this->getPantheonNameAndEnv();
$pantheon_terminus_environment = $pantheon_info['name'] . '.' . $env;
$task = $this->taskExecStack()
->stopOnFail();
if ($do_deploy) {
$task->exec("terminus env:deploy $pantheon_terminus_environment");
}
$result = $task
->exec("terminus remote:drush $pantheon_terminus_environment -- updb --no-interaction")
->exec("terminus remote:drush $pantheon_terminus_environment -- cr")
// A repeat config import may be required. Run it in any case.
->exec("terminus remote:drush $pantheon_terminus_environment -- cim --no-interaction")
->exec("terminus remote:drush $pantheon_terminus_environment -- cim --no-interaction")
->exec("terminus remote:drush $pantheon_terminus_environment -- cr")
->run()
->getExitCode();
if ($result !== 0) {
$message = "The site could not be fully updated at Pantheon at $env. Try fixing manually.";
$this->deployNotify($env, $message);
throw new \Exception($message);
}
$result = $this->localeImport(FALSE, $env);
if ($result->getExitCode() !== 0) {
$message = "The deployment went well to $env, but the locale import failed. Try to perform manually later.";
$this->deployNotify($env, $message);
throw new \Exception($message);
}
$result = $this->taskExecStack()
->stopOnFail()
->exec("terminus remote:drush $pantheon_terminus_environment -- sapi-r")
->exec("terminus remote:drush $pantheon_terminus_environment -- sapi-i")
->run()
->getExitCode();
if ($result !== 0) {
$message = "The deployment went well to $env, but the re-indexing to ElasticSearch failed. Try to perform manually later.";
$this->deployNotify($env, $message);
throw new \Exception($message);
}
$result = $this->taskExecStack()
->stopOnFail()
->exec("terminus remote:drush $pantheon_terminus_environment -- uli")
->run()
->getExitCode();
if ($result !== 0) {
$message = "Could not generate a login link at $env. Try again manually or check earlier errors.";
$this->deployNotify($env, $message);
throw new \Exception($message);
}
try {
$this->deployCheckRequirementErrors($env);
}
catch (\Exception $e) {
$message = "The deployment went well to $env, but there are requirement errors. Address these:" . PHP_EOL . $e->getMessage();
$this->deployNotify($env, $message);
throw new \Exception($message);
}
}
/**
* Check for requirement errors on the given environment.
*
* @param string $environment
* The environment to check.
*
* @throws \Exception
*/
public function deployCheckRequirementErrors(string $environment): void {
$pantheon_info = $this->getPantheonNameAndEnv();
$pantheon_terminus_environment = $pantheon_info['name'] . '.' . $environment;
$task = $this->taskExecStack()
->stopOnFail();
$output = $task
->exec("terminus remote:drush $pantheon_terminus_environment -- rq --format=csv")
->printOutput(FALSE)
->run()
->getMessage();
$errors = [];
$parsed_output = str_getcsv($output, "\n");
if (empty($parsed_output)) {
return;
}
foreach ($parsed_output as $row) {
$row = str_getcsv($row, ",");
if (empty($row[1])) {
continue;
}
if ($row[1] !== 'Error') {
continue;
}
$errors[] = $row[2];
}
if (empty($errors)) {
return;
}
throw new \Exception(print_r($errors, TRUE));
}
/**
* Install the site on specific env on Pantheon from scratch.
*
* Running this command via `ddev` will require terminus login inside ddev:
* `ddev auth ssh`.
*
* @param string $env
* The environment to install.
* @param string $pantheon_name
* The Pantheon site name.
*
* @throws \Exception
*/
public function deployPantheonInstallEnv(string $env = 'qa', string $pantheon_name = NULL): void {
$forbidden_envs = [
'live',
];
if (in_array($env, $forbidden_envs)) {
throw new \Exception("Reinstalling the site on `$env` environment is forbidden.");
}
if ($pantheon_name === NULL) {
$pantheon_info = $this->getPantheonNameAndEnv();
$pantheon_terminus_environment = $pantheon_info['name'] . '.' . $env;
}
else {
$pantheon_terminus_environment = $pantheon_name . '.' . $env;
}
// This set of commands should work, so expecting no failures
// (tend to invoke the same flow as DDEV's `config.local.yaml`).
$task = $this
->taskExecStack()
->stopOnFail();
$task
->exec("terminus remote:drush $pantheon_terminus_environment -- si server --no-interaction --existing-config")
->exec("terminus remote:drush $pantheon_terminus_environment -- pm-enable default_content --no-interaction")
->exec("terminus remote:drush $pantheon_terminus_environment -- pm-enable server_default_content --no-interaction")
->exec("terminus remote:drush $pantheon_terminus_environment -- pm:uninstall server_default_content default_content --no-interaction")
->exec("terminus remote:drush $pantheon_terminus_environment -- set-homepage")
->exec("terminus remote:drush $pantheon_terminus_environment -- uli");
$result = $task->run()->getExitCode();
if ($result !== 0) {
throw new \Exception("The site failed to install on Pantheon's `$env` environment.");
}
}
/**
* Prepares the repository to perform automatic deployment to Pantheon.
*
* @param string $token
* Terminus machine token: https://pantheon.io/docs/machine-tokens.
* @param string $github_token
* Personal GitHub token (Travis auth):
* https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token.
* @param string $github_deploy_branch
* The branch that should be pushed automatically to Pantheon. By default,
* it's 'main', the default GitHub branch for any new project.
* @param string $pantheon_deploy_branch
* The branch at the artifact repo that should be the target of the
* deployment. As we typically deploy to QA, the default value here is 'qa',
* that multi-dev environment should be created by hand beforehand.
*
* @throws \Exception
*/
public function deployConfigAutodeploy(string $token, string $github_token, string $github_deploy_branch = 'main', string $pantheon_deploy_branch = 'qa'): void {
$this->_exec("cp .travis.template.yml .travis.yml");
$pantheon_info = $this->getPantheonNameAndEnv();
$project_name = $pantheon_info['name'];
if (empty(shell_exec("which travis"))) {
// We do not bake it into the Docker image to save on disk space.
// We rarely need this operation, also not all the developers
// will use it.
$result = $this->taskExecStack()
->exec('sudo apt update')
->exec('sudo apt install ruby ruby-dev make g++ --yes')
->exec('sudo gem install travis --no-document')
->stopOnFail()
->run()
->getExitCode();
if ($result !== 0) {
throw new \Exception('The installation of the dependencies failed.');
}
}
$result = $this->taskExec('ssh-keygen -f travis-key -P ""')->run();
if ($result->getExitCode() !== 0) {
throw new \Exception('The key generation failed.');
}
$result = $this->taskExec('travis login --pro --github-token="' . $github_token . '"')->run();
if ($result->getExitCode() !== 0) {
throw new \Exception('The authentication with GitHub via Travis CLI failed.');
}
$result = $this->taskExec('travis encrypt-file travis-key --add --no-interactive --pro')
->run();
if ($result->getExitCode() !== 0) {
throw new \Exception('The encryption of the private key failed.');
}
$result = $this->taskExec('travis encrypt TERMINUS_TOKEN="' . $token . '" --add --no-interactive --pro')
->run();
if ($result->getExitCode() !== 0) {
throw new \Exception('The encryption of the Terminus token failed.');
}
$result = $this->taskExec("terminus connection:info $project_name.dev --fields='Git Command' --format=string | awk '{print $3}'")
->printOutput(FALSE)
->run();
$pantheon_git_url = trim($result->getMessage());
$this->taskReplaceInFile('.travis.yml')
->from('{{ PANTHEON_GIT_URL }}')
->to($pantheon_git_url)
->run();
$this->taskReplaceInFile('.travis.yml')
->from('{{ PANTHEON_DEPLOY_BRANCH }}')
->to($pantheon_deploy_branch)
->run();
$this->taskReplaceInFile('.travis.yml')
->from('{{ GITHUB_DEPLOY_BRANCH }}')
->to($github_deploy_branch)
->run();
$result = $this->taskExec('git add .travis.yml travis-key.enc')->run();
if ($result->getExitCode() !== 0) {
throw new \Exception("git add failed.");
}
$this->say("The project was prepared for the automatic deployment to Pantheon");
$this->say("Review the changes and make a commit from the added files.");
$this->say("Add the SSH key to the Pantheon account: https://pantheon.io/docs/ssh-keys .");
$this->say("Add the SSH key to the GitHub project as a deploy key: https://docs.github.com/en/developers/overview/managing-deploy-keys .");
$this->say("Convert the project to nested docroot: https://pantheon.io/docs/nested-docroot .");
}
/**
* Posts a comment on the GitHub issue that the code got deployed to Pantheon.
*
* @param string $pantheon_environment
* The Pantheon environment where the code was deployed.
* @param string $issue_comment
* The comment to post on the issue.
*/
public function deployNotify(string $pantheon_environment = 'qa', string $issue_comment = '') {
if (!empty($issue_comment)) {
$data = ['body' => $issue_comment];
$issue_comment = json_encode($data);
}
$github_token = getenv('GITHUB_TOKEN');
$git_commit_message = getenv('TRAVIS_COMMIT_MESSAGE');
if (strstr($git_commit_message, 'Merge pull request') === FALSE && strstr($git_commit_message, ' (#') === FALSE) {
$this->say($git_commit_message);
return;
}
$issue_matches = [];
$issue_numbers = [];
// If the PR was simply merged, then we have this:
preg_match_all('!from [a-zA-Z-_0-9]+/([0-9]+)!', $git_commit_message, $issue_matches);
if (!isset($issue_matches[1][0])) {
$this->say("Could not determine the issue number from the commit message name: $git_commit_message");
// If the PR was merged with a squash, then we have this:
// blah blah (#1234)
// Where 1234 is the PR number.
$pr_matches = [];
preg_match_all('!\(#([0-9]+)\)!', $git_commit_message, $pr_matches);
if (!isset($pr_matches[0][0])) {
$this->say("Could not determine the PR number from the commit message: $git_commit_message");
return;
}
// Retrieve the issue number from the PR description via GitHub API.
$pr_number = $pr_matches[1][0];
$pr = $this->taskExec("curl -H \"Authorization: token $github_token\" https://api.github.com/repos/" . self::$githubProject . "/pulls/$pr_number")
->printOutput(FALSE)
->run()
->getMessage();
$pr = json_decode($pr);
if (!isset($pr->body)) {
$this->say("Could not determine the issue number from the PR: $git_commit_message");
return;
}
// The issue number should be the "#1234"-like reference in the PR body.
preg_match_all('!#([0-9]+)\s+!', $pr->body, $issue_matches);
if (!isset($issue_matches[1][0])) {
$this->say("Could not determine the issue number from the PR description: $pr->body");
return;
}
foreach ($issue_matches[1] as $issue_match) {
if (!is_numeric($issue_match)) {
continue;
}
$issue_numbers[] = $issue_match;
}
}
else {
$issue_numbers[] = $issue_matches[1][0];
if (!is_numeric($issue_numbers[0])) {
throw new \Exception("Could not determine the issue number from the branch name in the commit message: $git_commit_message");
}
}
if (empty($issue_numbers)) {
$this->say("Giving up, no notification sent to GitHub");
return;
}
$pantheon_info = $this->getPantheonNameAndEnv();
// Let's figure out if the repository is public or not via GitHub API.
$repo = $this->taskExec("curl -H \"Authorization: token $github_token\" https://api.github.com/repos/" . self::$githubProject)
->printOutput(FALSE)
->run()
->getMessage();
$repo = json_decode($repo);
if (!isset($repo->private)) {
$this->yell("Could not determine if the repository is private or not.");
return;
}
if ($repo->private) {
// If the repository is private, we can put a login link into the comment.
$quick_link = $this->taskExec("terminus remote:drush " . $pantheon_info['name'] . "." . $pantheon_environment . " uli")
->printOutput(FALSE)
->run()
->getMessage();
}
else {
// Otherwise, just link the environment.
$quick_link = "https://" . $pantheon_info['name'] . "-" . $pantheon_environment . ".pantheonsite.io";
}
if (empty($issue_comment)) {
if (empty($pr_number)) {
$issue_comment = "{\"body\": \"The latest merged PR just got deployed successfully to Pantheon [`$pantheon_environment`]($quick_link) environment\"}";
}
else {
$issue_comment = "{\"body\": \"The latest merged PR #$pr_number just got deployed successfully to Pantheon [`$pantheon_environment`]($quick_link) environment\"}";
}
}
foreach ($issue_numbers as $issue_number) {
$result = $this->taskExec("curl -X POST -H 'Authorization: token $github_token' -d '$issue_comment' https://api.github.com/repos/" . self::$githubProject . "/issues/$issue_number/comments")
->printOutput(FALSE)
->run();
$exit_code = $result->getExitCode();
if ($exit_code) {
throw new \Exception("Could not notify GitHub of the deployment, GitHub API error: " . $result->getMessage());
}
}
}
}