forked from php-censor/php-censor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuilder.php
More file actions
575 lines (492 loc) · 14.7 KB
/
Copy pathBuilder.php
File metadata and controls
575 lines (492 loc) · 14.7 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
<?php
namespace PHPCensor;
use PHPCensor\Helper\BuildInterpolator;
use PHPCensor\Helper\MailerFactory;
use PHPCensor\Logging\BuildLogger;
use PHPCensor\Model\Build;
use PHPCensor\Plugin\Util\Factory as PluginFactory;
use PHPCensor\Store\BuildErrorWriter;
use PHPCensor\Store\Factory;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* @author Dan Cryer <dan@block8.co.uk>
*/
class Builder implements LoggerAwareInterface
{
/**
* @var string
*/
public $buildPath;
/**
* @var string[]
*/
public $ignore = [];
/**
* @var string[]
*/
public $binaryPath = '';
/**
* @var string[]
*/
public $priorityPath = 'local';
/**
* @var string
*/
public $directory;
/**
* @var string|null
*/
protected $currentStage = null;
/**
* @var bool
*/
protected $verbose = true;
/**
* @var \PHPCensor\Model\Build
*/
protected $build;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @var array
*/
protected $config = [];
/**
* @var string
*/
protected $lastOutput;
/**
* @var BuildInterpolator
*/
protected $interpolator;
/**
* @var \PHPCensor\Store\BuildStore
*/
protected $store;
/**
* @var \PHPCensor\Plugin\Util\Executor
*/
protected $pluginExecutor;
/**
* @var Helper\CommandExecutorInterface
*/
protected $commandExecutor;
/**
* @var Logging\BuildLogger
*/
protected $buildLogger;
/**
* @var BuildErrorWriter
*/
private $buildErrorWriter;
/**
* Set up the builder.
*
* @param \PHPCensor\Model\Build $build
* @param LoggerInterface $logger
*/
public function __construct(Build $build, LoggerInterface $logger = null)
{
$this->build = $build;
$this->store = Factory::getStore('Build');
$this->buildLogger = new BuildLogger($logger, $build);
$pluginFactory = $this->buildPluginFactory($build);
$this->pluginExecutor = new Plugin\Util\Executor($pluginFactory, $this->buildLogger);
$executorClass = 'PHPCensor\Helper\CommandExecutor';
$this->commandExecutor = new $executorClass(
$this->buildLogger,
ROOT_DIR,
$this->verbose
);
$this->interpolator = new BuildInterpolator();
$this->buildErrorWriter = new BuildErrorWriter($this->build->getProjectId(), $this->build->getId());
}
/**
* @return BuildLogger
*/
public function getBuildLogger()
{
return $this->buildLogger;
}
/**
* @return null|string
*/
public function getCurrentStage()
{
return $this->currentStage;
}
/**
* Set the config array, as read from .php-censor.yml
*
* @param array $config
*
* @throws \Exception
*/
public function setConfig(array $config)
{
$this->config = $config;
}
/**
* Access a variable from the .php-censor.yml file.
*
* @param string $key
*
* @return mixed
*/
public function getConfig($key = null)
{
$value = null;
if (null === $key) {
$value = $this->config;
} elseif (isset($this->config[$key])) {
$value = $this->config[$key];
}
return $value;
}
/**
* Access a variable from the config.yml
*
* @param string $key
*
* @return mixed
*/
public function getSystemConfig($key)
{
return Config::getInstance()->get($key);
}
/**
* @return string The title of the project being built.
*/
public function getBuildProjectTitle()
{
return $this->build->getProject()->getTitle();
}
public function execute()
{
$this->build->setStatusRunning();
$this->build->setStartDate(new \DateTime());
$this->store->save($this->build);
$this->build->sendStatusPostback();
$success = true;
$previousBuild = $this->build->getProject()->getPreviousBuild($this->build->getBranch());
$previousState = Build::STATUS_PENDING;
if ($previousBuild) {
$previousState = $previousBuild->getStatus();
}
try {
// Set up the build:
$this->setupBuild();
// Run the core plugin stages:
foreach ([Build::STAGE_SETUP, Build::STAGE_TEST, Build::STAGE_DEPLOY] as $stage) {
$this->currentStage = $stage;
$success &= $this->pluginExecutor->executePlugins($this->config, $stage);
if (!$success) {
break;
}
}
// Set the status so this can be used by complete, success and failure
// stages.
if ($success) {
$this->build->setStatusSuccess();
} else {
$this->build->setStatusFailed();
}
} catch (\Exception $ex) {
$success = false;
$this->build->setStatusFailed();
$this->buildLogger->logFailure('Exception: ' . $ex->getMessage(), $ex);
}
try {
if ($success) {
$this->currentStage = Build::STAGE_SUCCESS;
$this->pluginExecutor->executePlugins($this->config, Build::STAGE_SUCCESS);
if (Build::STATUS_FAILED === $previousState) {
$this->currentStage = Build::STAGE_FIXED;
$this->pluginExecutor->executePlugins($this->config, Build::STAGE_FIXED);
}
} else {
$this->currentStage = Build::STAGE_FAILURE;
$this->pluginExecutor->executePlugins($this->config, Build::STAGE_FAILURE);
if (Build::STATUS_SUCCESS === $previousState || Build::STATUS_PENDING === $previousState) {
$this->currentStage = Build::STAGE_BROKEN;
$this->pluginExecutor->executePlugins($this->config, Build::STAGE_BROKEN);
}
}
} catch (\Exception $ex) {
$this->buildLogger->logFailure('Exception: ' . $ex->getMessage(), $ex);
}
$this->buildLogger->log('');
if (Build::STATUS_FAILED === $this->build->getStatus()) {
$this->buildLogger->logFailure('BUILD FAILED!');
} else {
$this->buildLogger->logSuccess('BUILD SUCCESS!');
}
try {
// Complete stage plugins are always run
$this->currentStage = Build::STAGE_COMPLETE;
$this->pluginExecutor->executePlugins($this->config, Build::STAGE_COMPLETE);
} catch (\Exception $ex) {
$this->buildLogger->logFailure('Exception: ' . $ex->getMessage());
}
// Update the build in the database, ping any external services, etc.
$this->build->sendStatusPostback();
$this->build->setFinishDate(new \DateTime());
$removeBuilds = (bool)Config::getInstance()->get('php-censor.build.remove_builds', true);
if ($removeBuilds) {
// Clean up:
$this->buildLogger->log('');
$this->buildLogger->logSuccess('REMOVING BUILD.');
$this->build->removeBuildDirectory();
}
$this->buildErrorWriter->flush();
$this->setErrorTrend();
$this->store->save($this->build);
}
protected function setErrorTrend()
{
$this->build->setErrorsTotal($this->store->getErrorsCount($this->build->getId()));
$trend = $this->store->getBuildErrorsTrend(
$this->build->getId(),
$this->build->getProjectId(),
$this->build->getBranch()
);
if (isset($trend[1])) {
$previousBuild = $this->store->getById($trend[1]['build_id']);
if (
$previousBuild &&
!in_array(
$previousBuild->getStatus(),
[Build::STATUS_PENDING, Build::STATUS_RUNNING],
true
)
) {
$this->build->setErrorsTotalPrevious((int)$trend[1]['count']);
}
}
}
/**
* Used by this class, and plugins, to execute shell commands.
*
* @param array ...$params
*
* @return boolean
*/
public function executeCommand(...$params)
{
return $this->commandExecutor->executeCommand($params);
}
/**
* Returns the output from the last command run.
*
* @return string
*/
public function getLastOutput()
{
return $this->commandExecutor->getLastOutput();
}
/**
* Specify whether exec output should be logged.
*
* @param boolean $enableLog
*/
public function logExecOutput($enableLog = true)
{
$this->commandExecutor->logExecOutput = $enableLog;
}
/**
* Find a binary required by a plugin.
*
* @param array|string $binary
* @param string $priorityPath
* @param string $binaryPath
* @param array $binaryName
* @return string
*
* @throws \Exception when no binary has been found.
*/
public function findBinary($binary, $priorityPath = 'local', $binaryPath = '', $binaryName = [])
{
return $this->commandExecutor->findBinary($binary, $priorityPath, $binaryPath, $binaryName);
}
/**
* Replace every occurrence of the interpolation vars in the given string
* Example: "This is build %PHPCI_BUILD%" => "This is build 182"
*
* @param string $input
*
* @return string
*/
public function interpolate($input)
{
return $this->interpolator->interpolate($input);
}
/**
* Set up a working copy of the project for building.
*
* @throws \Exception
*
* @return boolean
*/
protected function setupBuild()
{
$this->buildPath = $this->build->getBuildPath();
$this->commandExecutor->setBuildPath($this->buildPath);
$this->build->handleConfigBeforeClone($this);
// Create a working copy of the project:
if (!$this->build->createWorkingCopy($this, $this->buildPath)) {
throw new \Exception('Could not create a working copy.');
}
chdir($this->buildPath);
$this->interpolator->setupInterpolationVars(
$this->build,
$this->buildPath,
APP_URL
);
// Does the project's .php-censor.yml request verbose mode?
if (!isset($this->config['build_settings']['verbose']) || !$this->config['build_settings']['verbose']) {
$this->verbose = false;
}
// Does the project have any paths it wants plugins to ignore?
if (!empty($this->config['build_settings']['ignore'])) {
$this->ignore = $this->config['build_settings']['ignore'];
}
if (!empty($this->config['build_settings']['binary_path'])) {
$this->binaryPath = rtrim(
$this->interpolate($this->config['build_settings']['binary_path']),
'/\\'
) . '/';
}
if (
!empty($this->config['build_settings']['priority_path']) &&
in_array(
$this->config['build_settings']['priority_path'],
Plugin::AVAILABLE_PRIORITY_PATHS,
true
)
) {
$this->priorityPath = $this->config['build_settings']['priority_path'];
}
$directory = $this->buildPath;
// Does the project have a global directory for plugins ?
if (!empty($this->config['build_settings']['directory'])) {
$directory = $this->config['build_settings']['directory'];
}
$this->directory = rtrim(
$this->interpolate($directory),
'/\\'
) . '/';
$this->buildLogger->logSuccess(sprintf('Working copy created: %s', $this->buildPath));
return true;
}
/**
* Sets a logger instance on the object
*
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->buildLogger->setLogger($logger);
}
/**
* Write to the build log.
*
* @param string $message
* @param string $level
* @param array $context
*/
public function log($message, $level = LogLevel::INFO, $context = [])
{
$this->buildLogger->log($message, $level, $context);
}
/**
* Add a warning-coloured message to the log.
*
* @param string $message
*/
public function logWarning($message)
{
$this->buildLogger->logWarning($message);
}
/**
* Add a success-coloured message to the log.
*
* @param string $message
*/
public function logSuccess($message)
{
$this->buildLogger->logSuccess($message);
}
/**
* Add a failure-coloured message to the log.
*
* @param string $message
* @param \Exception $exception The exception that caused the error.
*/
public function logFailure($message, \Exception $exception = null)
{
$this->buildLogger->logFailure($message, $exception);
}
/**
* Add a debug-coloured message to the log.
*
* @param string $message
*/
public function logDebug($message)
{
$this->buildLogger->logDebug($message);
}
/**
* Returns a configured instance of the plugin factory.
*
* @param Build $build
*
* @return PluginFactory
*/
private function buildPluginFactory(Build $build)
{
$pluginFactory = new PluginFactory();
$self = $this;
$pluginFactory->registerResource(
function () use ($self) {
return $self;
},
null,
'PHPCensor\Builder'
);
$pluginFactory->registerResource(
function () use ($build) {
return $build;
},
null,
'PHPCensor\Model\Build'
);
$logger = $this->logger;
$pluginFactory->registerResource(
function () use ($logger) {
return $logger;
},
null,
'Psr\Log\LoggerInterface'
);
$pluginFactory->registerResource(
function () use ($self) {
$factory = new MailerFactory($self->getSystemConfig('php-censor'));
return $factory->getSwiftMailerFromConfig();
},
null,
'Swift_Mailer'
);
return $pluginFactory;
}
/**
* @return BuildErrorWriter
*/
public function getBuildErrorWriter()
{
return $this->buildErrorWriter;
}
}