-
Notifications
You must be signed in to change notification settings - Fork 195
/
RoboFile.php
355 lines (317 loc) · 11.1 KB
/
RoboFile.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
<?php
use CzProject\GitPhp\Git;
use CzProject\GitPhp\GitException;
use Pantheon\Terminus\Config\ConfigAwareTrait;
use Pantheon\Terminus\Helpers\CommandCoverageReport;
use Pantheon\Terminus\Terminus;
use Robo\Tasks;
use Twig\Environment;
use Twig\Extension\EscaperExtension;
use Twig\Loader\FilesystemLoader;
use wdm\debian\control\StandardFile;
use wdm\debian\Packager;
/**
* Housekeeping tasks for Terminus.
*
* Class RoboFile
*/
class RoboFile extends Tasks
{
use ConfigAwareTrait;
/**
* @var Terminus
*/
protected Terminus $terminus;
/**
* RoboFile constructor.
*/
public function __construct()
{
$this->setTerminus(Terminus::factory());
$this->setConfig($this->terminus->getConfig());
}
/**
* @param string|null $file
*/
public function doc($file = null)
{
//TODO: change this to real documentation building from phpdoc
$readme = (string) CommandCoverageReport::factory();
if ($file) {
file_put_contents($file, $readme);
$readme = './README.md regenerated.';
}
$this->output()->writeln($readme);
}
/**
* @param string|null $file
*/
public function coverage($file = null)
{
$readme = CommandCoverageReport::factory();
if ($file) {
file_put_contents($file, $readme);
$readme = './README.md regenerated.';
}
$this->output()->writeln($readme);
}
/**
* Updates $terminusPluginsDependenciesVersion variable in bin/terminus.
*/
public function updateDependenciesversion()
{
$this->say('Checking Terminus plugins dependencies version...');
$hash = substr(sha1_file($this->getProjectPath() . DIRECTORY_SEPARATOR . 'composer.lock'), 0, 10);
$binFileContents = file_get_contents(
$this->getProjectPath() . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . 'terminus'
);
$newBinFileContents = preg_replace(
'/(terminusPluginsDependenciesVersion\s=\s\')(.+)(\';)/',
"\${1}$hash\${3}",
$binFileContents
);
if ($newBinFileContents && $newBinFileContents !== $binFileContents) {
file_put_contents('bin' . DIRECTORY_SEPARATOR . 'terminus', $newBinFileContents);
$this->say('Terminus plugins dependencies version has been updated.');
return;
}
$this->say('Terminus plugins dependencies version remains unchanged.');
}
/**
* @return mixed|null
*
* @throws \Exception
*/
public function bundleLinux()
{
$this->say('Building DEBIAN/UBUNTU package.');
$terminus_binary = $this->getProjectPath() . DIRECTORY_SEPARATOR . 'terminus';
$dpkg_installed_size = ceil(filesize($terminus_binary) / 1024);
$outputPath = $this->getProjectPath() . DIRECTORY_SEPARATOR . 'package';
// We need the output path empty.
if (is_dir($outputPath)) {
exec(sprintf('rm -Rf %s', $outputPath));
mkdir($outputPath);
}
$composerJson = json_decode(
file_get_contents($this->getProjectPath() . DIRECTORY_SEPARATOR . 'composer.json'),
true
);
[$vendor, $package] = explode('/', $composerJson['name']);
// Create a config object.
$config = $this->getConfig();
$control = new StandardFile();
$control
->setPackageName($package)
->setVersion($config->get('version'))
->setDepends(['php7.4', 'php7.4-cli', 'php7.4-xml'])
->setInstalledSize($dpkg_installed_size)
->setArchitecture('all')
->setMaintainer('Terminus', '[email protected]')
->setProvides($package)
->setDescription($composerJson['description']);
$packager = new Packager();
$packager->setOutputPath($outputPath);
$packager->setControl($control);
$packager->addMount(
$terminus_binary,
DIRECTORY_SEPARATOR . 'usr' . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . 'terminus'
);
// Creates folders using mount points.
$packager->run();
// Get the Debian package command.
// Expectation is that this is a command line invocation for dpkg.
$packageCommand = $packager->build();
$this->say($packageCommand);
// OS Check... if running on OS that is not linux,
// run the build in Docker.
$status = null;
exec($packageCommand, $result, $status);
if ($status !== 0) {
throw new Exception(join(PHP_EOL, $result));
}
if (!is_array($result)) {
$result = [$result];
}
// Package should be last line of output from command
$packageFile = array_shift($result);
$this->say('Package created: ' . $packageFile);
return $packageFile;
}
/**
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function bundleMac()
{
$context = [];
// Create a config object.
$config = $this->getConfig();
$context['version'] = $config->get('version');
$context['download_url'] = '***TBD***';
$context['sha256'] = '***TBD***';
$loader = new FilesystemLoader($config->get('root') . DIRECTORY_SEPARATOR . 'templates');
$twig = new Environment($loader, [
'cache' => false
]);
$twig->getExtension(EscaperExtension::class)
->setDefaultStrategy('url');
$formulaFolder = $config->get('root') . DIRECTORY_SEPARATOR . 'Formula';
if (is_dir($formulaFolder)) {
exec("rm -rf $formulaFolder");
}
mkdir($formulaFolder);
file_put_contents(
$formulaFolder . DIRECTORY_SEPARATOR . 'terminus.rb',
$twig->render('homebrew-receipt.twig', $context)
);
$this->say('Mac Formula Created');
}
/**
* @return Terminus
*/
public function getTerminus(): Terminus
{
return $this->terminus;
}
/**
* @param Terminus $terminus
*/
public function setTerminus(Terminus $terminus): void
{
$this->terminus = $terminus;
}
/**
* Generates a test commit.
*
* @throws \Pantheon\Terminus\Exceptions\TerminusException
* @throws GitException
*/
public function generateTestCommit()
{
$this->output()->writeln('Getting the Site Repo');
// get the git host and port from terminus
$commandResponse = $this->getTerminus()->execute(
'%s connection:info %s.dev --fields=git_host,git_port --format=json',
[
$this->getProjectPath() . "/terminus.phar",
$this->getSiteName(),
]
);
// check if the command was successful
if ($commandResponse[1] !== 0) {
$this->output()->writeln('Failed to retrieve git host and port');
exit(1);
}
// decode the json response
$gitInfo = json_decode($commandResponse[0], true);
$this->output()->writeln('Retrieved git host and port' . print_r($gitInfo, true));
// check if the git host and port were retrieved
if (!isset($gitInfo['git_host']) || !isset($gitInfo['git_port'])) {
$this->output()->writeln('Failed to retrieve git host and port');
exit(1);
}
// Does the known_hosts file exist?
if (!file_exists(sprintf("%s/.ssh/known_hosts", getenv("HOME")))) {
// if not, create one
touch(sprintf("%s/.ssh/known_hosts", getenv("HOME")));
}
// get the contents of the known_hosts file
$knownHosts = file_get_contents(sprintf("%s/.ssh/known_hosts", getenv("HOME")));
// check if the git host is already in the known_hosts file
if (!str_contains($knownHosts, $gitInfo['git_host'])) {
// if not, add it
$this->output()->writeln('Adding the git host to known hosts file');
$addGitHostToKnownHostsCommand = sprintf(
'ssh-keyscan -p %d %s >> ~/.ssh/known_hosts',
$gitInfo['git_port'],
$gitInfo['git_host']
);
$this->output()->writeln($addGitHostToKnownHostsCommand);
exec($addGitHostToKnownHostsCommand);
}
// checkout the branch related to this test run
$clonedPath = sprintf(
"%s/pantheon-local-copies/%s",
getenv("HOME"),
$this->getSiteName()
);
if (is_dir($clonedPath)) {
// make sure you're working with a clean copy of the repo
exec("rm -rf {$clonedPath}");
}
$this->output()->writeln(sprintf('Cloning the site repository to %s', $clonedPath));
// get the git host and port from terminus
$commandResponse = $this->getTerminus()->execute(
'%s local:clone %s',
[
$this->getProjectPath() . "/terminus.phar",
$this->getSiteName(),
]
);
$response = "";
try {
$git = new Git();
$repo = $git->open($clonedPath);
chdir($clonedPath);
$branches = $repo->getBranches();
if (!in_array($this->getSiteEnv(), $branches)) {
$this->output()->writeln(sprintf('Creating the %s branch', $this->getSiteEnv()));
// Create the branch
$repo->createBranch($this->getSiteEnv());
}
// Check out the branch in question
$repo->checkout($this->getSiteEnv());
// create a text file
$testFilePath = sprintf('%s/test.txt', $clonedPath);
file_put_contents($testFilePath, 'test');
// add the file to the repository
$repo->addFile("test.txt");
// commit the file
$repo->commit('Test commit');
// push the commit
$response = $repo->execute(
'push',
'origin',
$this->getSiteEnv(),
);
} catch (GitException $e) {
$this->output()->writeln(["Git Exception:", $e->getMessage()]);
$this->output()->writeln(print_r($response, true));
exit(1);
} catch (Exception $e) {
$this->output()->writeln($e->getMessage());
$this->output()->writeln(print_r($response, true));
exit(1);
}
// get the last commit
$commit = $repo->getLastCommit();
// output the commit id
$this->output()->writeln($commit->getId());
return $commit->getId();
}
/**
* Returns the absolute path to the project.
*
* @return string
*/
private function getProjectPath(): string
{
return dirname(__FILE__);
}
/**
* @return string
*/
private function getSiteName(): string
{
return getenv('TERMINUS_SITE') ?? 'ci-terminus-composer';
}
/**
* @return string
*/
private function getSiteEnv(): string
{
return getenv('TERMINUS_ENV') ?? 'dev';
}
}