-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathBuilder.php
More file actions
456 lines (368 loc) · 13.5 KB
/
Copy pathBuilder.php
File metadata and controls
456 lines (368 loc) · 13.5 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
<?php
declare(strict_types=1);
namespace PHPCensor;
use DateTime;
use Exception;
use PHPCensor\Common\Exception\RuntimeException;
use PHPCensor\Helper\BuildInterpolator;
use PHPCensor\Helper\CommandExecutor;
use PHPCensor\Helper\CommandExecutorInterface;
use PHPCensor\Logging\BuildLogger;
use PHPCensor\Model\Build;
use PHPCensor\Plugin\Util\Executor;
use PHPCensor\Plugin\Util\Factory as PluginFactory;
use PHPCensor\Store\BuildErrorWriter;
use PHPCensor\Store\BuildStore;
use PHPCensor\Store\EnvironmentStore;
use PHPCensor\Store\SecretStore;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use PHPCensor\Common\Application\ConfigurationInterface;
/**
* @package PHP Censor
* @subpackage Application
*
* @author Dan Cryer <dan@block8.co.uk>
* @author Dmitry Khomutov <poisoncorpsee@gmail.com>
*/
class Builder
{
public string $buildPath = '';
/**
* @var string[]
*/
public array $ignore = [];
public string $binaryPath = '';
public string $priorityPath = 'local';
public string $directory = '';
protected ?string $currentStage = null;
protected bool $verbose = true;
protected Build $build;
protected LoggerInterface $logger;
protected array $config = [];
protected BuildInterpolator $interpolator;
protected BuildStore $store;
protected Executor $pluginExecutor;
protected CommandExecutorInterface $commandExecutor;
protected BuildLogger $buildLogger;
protected BuildErrorWriter $buildErrorWriter;
protected ConfigurationInterface $configuration;
protected DatabaseManager $databaseManager;
protected StoreRegistry $storeRegistry;
public function __construct(
ConfigurationInterface $configuration,
DatabaseManager $databaseManager,
StoreRegistry $storeRegistry,
Build $build,
BuildLogger $buildLogger
) {
$this->configuration = $configuration;
$this->databaseManager = $databaseManager;
$this->storeRegistry = $storeRegistry;
$this->buildLogger = $buildLogger;
$this->build = $build;
/** @var BuildStore $buildStore */
$buildStore = $this->storeRegistry->get('Build');
/** @var SecretStore $secretStore */
$secretStore = $this->storeRegistry->get('Secret');
/** @var EnvironmentStore $environmentStore */
$environmentStore = $this->storeRegistry->get('Environment');
$this->store = $buildStore;
$pluginFactory = new PluginFactory($this, $build);
$this->pluginExecutor = new Plugin\Util\Executor(
$this->storeRegistry,
$pluginFactory,
$this->buildLogger,
$buildStore
);
$executorClass = CommandExecutor::class;
$this->commandExecutor = new $executorClass(
$this->buildLogger,
ROOT_DIR,
$this->verbose
);
$this->interpolator = new BuildInterpolator($environmentStore, $secretStore);
$this->buildErrorWriter = new BuildErrorWriter(
$this->configuration,
$this->databaseManager,
$this->storeRegistry,
$this->build->getProjectId(),
$this->build->getId()
);
}
public function getBuildLogger(): BuildLogger
{
return $this->buildLogger;
}
public function getConfiguration(): ConfigurationInterface
{
return $this->configuration;
}
public function getCurrentStage(): ?string
{
return $this->currentStage;
}
/**
* Set the config array, as read from .php-censor.yml
*/
public function setConfig(array $config): void
{
$this->config = $config;
}
/**
* Access a variable from the .php-censor.yml file.
*
* @return mixed
*/
public function getConfig(?string $key = null)
{
$value = null;
if (null === $key) {
$value = $this->config;
} elseif (isset($this->config[$key])) {
$value = $this->config[$key];
}
return $value;
}
public function execute(): void
{
$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());
$previousBuildStatus = Build::STATUS_PENDING;
if ($previousBuild) {
$previousBuildStatus = $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 (\Throwable $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 === $previousBuildStatus) {
$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 === $previousBuildStatus || Build::STATUS_PENDING === $previousBuildStatus) {
$this->currentStage = Build::STAGE_BROKEN;
$this->pluginExecutor->executePlugins($this->config, Build::STAGE_BROKEN);
}
}
} catch (\Throwable $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!');
}
// Flush errors to make them available to plugins in complete stage
$this->buildErrorWriter->flush();
try {
// Complete stage plugins are always run
$this->currentStage = Build::STAGE_COMPLETE;
$this->pluginExecutor->executePlugins($this->config, Build::STAGE_COMPLETE);
} catch (\Throwable $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)$this->configuration->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->setTestCoverageTrend();
$this->store->save($this->build);
}
protected function setErrorTrend(): void
{
$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[0])) {
$this->build->setErrorsTotalPrevious((int)$trend[0]['count']);
}
}
protected function setTestCoverageTrend(): void
{
$this->build->setTestCoverage($this->store->getTestCoverage($this->build->getId()));
$trend = $this->store->getBuildTestCoverageTrend(
$this->build->getId(),
$this->build->getProjectId(),
$this->build->getBranch()
);
if (!empty($trend[0]) && !empty($trend[0]['coverage'])) {
$coverage = \json_decode($trend[0]['coverage'], true);
if (isset($coverage['lines'])) {
$this->build->setTestCoveragePrevious($coverage['lines']);
}
}
}
/**
* Used by this class, and plugins, to execute shell commands.
*
* @param ...$params
*/
public function executeCommand(...$params): bool
{
return $this->commandExecutor->executeCommand($params);
}
/**
* Returns the output from the last command run.
*/
public function getLastOutput(): string
{
return $this->commandExecutor->getLastOutput();
}
/**
* Specify whether exec output should be logged.
*/
public function logExecOutput(bool $enableLog = true): void
{
$this->commandExecutor->logExecOutput = $enableLog;
}
/**
* Find a binary required by a plugin.
*
* @param array|string $binary
*
* @throws Exception when no binary has been found.
*/
public function findBinary(
$binary,
string $priorityPath = 'local',
string $binaryPath = '',
array $binaryName = []
): string {
return $this->commandExecutor->findBinary($binary, $priorityPath, $binaryPath, $binaryName);
}
/**
* Replace every occurrence of the interpolation vars in the given string
* Example: "This is build %BUILD_ID%" => "This is build 182"
*/
public function interpolate(string $input, bool $useSecrets = false): string
{
return $this->interpolator->interpolate($input, $useSecrets);
}
/**
* Set up a working copy of the project for building.
*
* @throws Exception
*/
protected function setupBuild(): bool
{
$this->buildPath = (string)$this->build->getBuildPath();
$this->commandExecutor->setBuildPath($this->buildPath);
$this->build->handleConfigBeforeClone($this);
$workingCopySuccess = true;
// Create a working copy of the project:
if (!$this->build->createWorkingCopy($this, $this->buildPath)) {
$workingCopySuccess = false;
}
\chdir($this->buildPath);
$version = (string)\trim(\file_get_contents(ROOT_DIR . 'VERSION.md'));
$version = !empty($version) ? $version : '0.0.0 (UNKNOWN)';
$this->interpolator->setupInterpolationVars(
$this->build,
APP_URL,
$version
);
// 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'], true),
'/\\'
) . '/';
}
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, true),
'/\\'
) . '/';
$this->buildLogger->logSuccess(\sprintf('Working copy created: %s', $this->buildPath));
if (!$workingCopySuccess) {
throw new RuntimeException('Could not create a working copy.');
}
return true;
}
public function log(string $message, string $level = LogLevel::INFO, array $context = []): void
{
$this->buildLogger->log($message, $level, $context);
}
public function logWarning(string $message): void
{
$this->buildLogger->logWarning($message);
}
public function logSuccess(string $message): void
{
$this->buildLogger->logSuccess($message);
}
public function logFailure(string $message, ?\Throwable $exception = null): void
{
$this->buildLogger->logFailure($message, $exception);
}
public function logDebug(string $message): void
{
$this->buildLogger->logDebug($message);
}
public function getBuildErrorWriter(): BuildErrorWriter
{
return $this->buildErrorWriter;
}
}