forked from banago/PHPloy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
phploy
670 lines (564 loc) · 21.6 KB
/
phploy
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
#! /usr/bin/env php
<?php
/**
* PHPloy - A PHP Deployment Script
*
* @package PHPloy
* @author Baki Goxhaj <[email protected]>
* @author Fadion Dashi <[email protected]>
* @author Bruno De Barros <[email protected]>
* @link http://wplancer.com
* @licence MIT Licence
* @version 2.0.0-beta
*/
/**
* Run deployment
*/
try {
$phploy = new PHPloy();
} catch (Exception $e) {
// Display the error in red
echo "\r\n\033[31mOh Snap: {$e->getMessage()}\033[0m\r\n\r\n";
}
/**
* PHPloy Class
*/
class PHPloy
{
/**
* @var string $revision
*/
public $revision;
/**
* A list of files that should NOT be uploaded to the remote server
* (must match the absolute path in its entirety)
*
* @todo - implement the ability to specify entire folders (or use wildcards?) here
* @var array $filesToIgnore
*/
public $filesToIgnore = array(
'.gitignore',
'.gitmodules',
);
/**
* If you need support for sub-submodules, ensure this is set to TRUE
* Set to false when the --skip-subsubmodules command line option is used
*
* @var bool $scanForSubSubmodules
*/
public $scanForSubSubmodules = true;
/**
* @var array $servers
*/
public $servers = array();
/**
* @var array $submodules
*/
public $submodules = array();
/**
* The name of the file on remote servers that stores the current revision hash
*
* @var string $dotRevisionFilename
*/
public $dotRevisionFilename = '.revision';
/**
* The filename from which to read remote server details
*
* @var string $deplyIniFilename
*/
public $deployIniFilename = 'deploy.ini';
/**
* @var string $phployVersion
*/
protected $phployVersion = '2.0.0-beta';
/**
* List of available "short" command line options, prefixed by a single hyphen
* Colon suffix indicates that the option requires a value
* Double-colon suffix indicates that the option *may* accept a value
* See descriptions below
*
* @var string $shortops
*/
protected $shortopts = 'ls:';
/**
* List of available "long" command line options, prefixed by double-hyphen
* Colon suffix indicates that the option requires a value
* Double-colon suffix indicates that the option *may* accept a value
*
* --list or -l Lists the files that *would* be deployed if run without this option
* --rollback Deploys the previous commit/revision
* --rollback="[revision hash]" Deploys the specific commit/revision
* --server="[server name]" Deploys to the server entry listed in deploy.ini
* or -s [server name]
* --sync Updates the remote .revision file with the hash of the current HEAD
* --sync="[revision hash]" Updates the remove .revision file with the provided hash
* --skip-subsubmodules Skips the scanning of sub-submodules which is currently quite slow
*
* @var array $longopts
*/
protected $longopts = array('list', 'rollback::', 'server:', 'sync::', 'skip-subsubmodules');
/**
* @var bool|resource $connection
*/
protected $connection = false;
/**
* @var string $server
*/
protected $server = '';
/**
* @var string $repo
*/
protected $repo;
/**
* @var string $mainRepo
*/
protected $mainRepo;
/**
* @var bool|string $currentSubmoduleName
*/
protected $currentSubmoduleName = false;
/**
* Holds the path to the .revision file
* For the main repository this will be the value of $dotRevisionFilename ('.revision' by default)
* but for submodules, the submodule path will be prepended
*
* @var string $dotRevision
*/
protected $dotRevision;
/**
* @var bool $listFiles
*/
protected $listFiles = false;
/**
* @var bool $sync
*/
protected $sync = false;
/**
* Constructor
*/
public function __construct()
{
$this->parseOptions();
$this->output("\r\n-------------- phploy v{$this->phployVersion} ----------------\r\n");
if (file_exists("$this->repo/.git")) {
$this->output('Scanning repository...');
$this->checkSubmodules($this->repo);
$this->deploy($this->revision);
} else {
throw new Exception("'{$this->repo}' is not Git repository.");
}
}
/**
* Parse CLI options
* For descriptions of the various options, see the comments for $this->longopts
*/
protected function parseOptions()
{
$options = getopt($this->shortopts, $this->longopts);
if (isset($options['l']) or isset($options['list'])) {
$this->listFiles = true;
}
if (isset($options['s']) or isset($options['server'])) {
$this->server = isset($options['s']) ? $options['s'] : $options['server'];
}
if (isset($options['sync'])) {
$this->sync = empty($options['sync']) ? 'sync' : $options['sync'];
}
if (isset($options['rollback'])) {
$this->revision = ($options['rollback'] == '') ? 'HEAD^' : $options['rollback'];
} else {
$this->revision = 'HEAD';
}
if (isset($options['skip-subsubmodules'])) {
$this->scanForSubSubmodules = false;
}
$this->repo = isset($opts['repo']) ? rtrim($opts['repo'], '/') : getcwd();
$this->mainRepo = $this->repo;
}
/**
* Check for submodules
*
* @param string $repo
*/
protected function checkSubmodules($repo)
{
$command = "git --git-dir=\"$repo/.git\" --work-tree=\"$repo\" submodule status";
$output = array();
exec(escapeshellcmd($command), $output);
$this->output(' Found '.count($output).' submodules.');
if (count($output) > 0) {
foreach ($output as $line) {
$line = explode(' ', trim($line));
$this->submodules[] = array('revision' => $line[0], 'name' => $line[1], 'path' => $repo.'/'.$line[1]);
$this->filesToIgnore[] = $line[1];
$this->output(sprintf(' Found submodule %s. %s',
$line[1],
$this->scanForSubSubmodules ? 'Scanning for sub-submodules...' : null
));
// The call to checkSubSubmodules also calls a git foreach
// So perhaps it should be *outside* the loop here?
if ($this->scanForSubSubmodules)
$this->checkSubSubmodules($repo, $line[1]);
}
if (!$this->scanForSubSubmodules)
$this->output(' Skipping search for sub-submodules.');
}
}
/**
* Check for sub-submodules
*
* @todo This function is quite slow (at least on Windows it often takes several seconds for each call).
* Can it be optimized?
* It appears that this is called for EACH submodule, but then also does another `git submodule foreach`
* @param string $repo
* @param string $name
*/
protected function checkSubSubmodules($repo, $name)
{
$command = "git --git-dir=\"$repo/.git\" --work-tree=\"$repo\" submodule foreach git submodule status";
$output = array();
exec(escapeshellcmd($command), $output);
if (count($output) > 0) {
foreach ($output as $line) {
$line = explode(' ', trim($line));
if (trim($line[0]) == 'Entering') continue;
$this->submodules[] = array('revision' => $line[0], 'name' => $name.'/'.$line[1], 'path' => $repo.'/'.$name.'/'.$line[1]);
$this->filesToIgnore[] = $line[1];
$this->output(sprintf(' Found sub-submodule %s.', "$name/$line[1]"));
}
}
}
/**
* Parse Credentials
*
* @param string $deploy
*/
protected function parseCredentials($deploy)
{
if (! file_exists($deploy)) {
throw new Exception("'$deploy' does not exist.");
} else {
$servers = parse_ini_file($deploy, true);
if (! $servers) {
throw new Exception("'$deploy' is not a valid .ini file.");
} else {
$this->filesToIgnore[] = $deploy;
return $servers;
}
}
}
/**
* Reads the deploy.ini file and populates the $this->servers array
*/
protected function prepareServers()
{
$defaults = array(
'host' => '',
'user' => '',
'pass' => '',
'port' => 21,
'path' => '/',
'passive' => true,
'clean_directories' => array()
);
$servers = $this->parseCredentials($this->deployIniFilename);
foreach ($servers as $name => $options) {
if ($name == 'quickmode') {
foreach ($options as $env => $creds) {
$options = parse_url($creds);
$options = array_merge($defaults, $options);
$this->servers[$env] = $options;
}
break;
}
$options = array_merge($defaults, $options);
$this->servers[$name] = $options;
}
}
/**
* Compare revisions and return files to upload
*
* @param string $localRevision
* @return array
* @throws Exception if unknown git diff status
*/
protected function compare($localRevision)
{
$remoteRevision = null;
$tmpFile = tmpfile();
$filesToUpload = array();
$filesToDelete = array();
$output = array();
if ($this->currentSubmoduleName) {
$this->dotRevision = $this->currentSubmoduleName.'/'.$this->dotRevisionFilename;
} else {
$this->dotRevision = $this->dotRevisionFilename;
}
// Fetch the .revision file from the server and write it to $tmpFile
if (@ftp_fget($this->connection, $tmpFile, $this->dotRevision, FTP_ASCII)) {
fseek($tmpFile, 0);
$remoteRevision = trim(fread($tmpFile, 1024));
} else {
$this->output('No remote revision file present. Running a fresh deployment - grab a coffee...');
}
fclose($tmpFile);
// Use git to list the changed files between $remoteRevision and $localRevision
$gitCommand = 'git --git-dir="'.$this->repo.'/.git" --work-tree="'.$this->repo.'"';
if (empty($remoteRevision)) {
$command = $gitCommand.' ls-files';
} else if ($localRevision == 'HEAD') {
$command = $gitCommand.' diff --name-status '.$remoteRevision.'...'.$localRevision;
} else {
$command = $gitCommand.' diff --name-status '.$remoteRevision.'... '.$localRevision;
}
exec(escapeshellcmd($command), $output);
if (! empty($remoteRevision)) {
foreach ($output as $line) {
if ($line[0] == 'A' or $line[0] == 'C' or $line[0] == 'M') {
// Added (A), Modified (C), Unmerged (M)
$filesToUpload[] = trim(substr($line, 1));
} elseif ($line[0] == 'D') {
// Deleted (D)
$filesToDelete[] = trim(substr($line, 1));
} else {
throw new Exception("Unknown git-diff status: {$line[0]}");
}
}
} else {
$filesToUpload = $output;
}
$filesToUpload = array_diff($filesToUpload, $this->filesToIgnore);
return array(
'upload' => $filesToUpload,
'delete' => $filesToDelete
);
}
/**
* Deploy (or list) changed files
*
* @param string $revision
*/
public function deploy($revision = 'HEAD')
{
$this->prepareServers();
// Exit with an error if the specified server does not exist in deploy.ini
if ($this->server != '' && !array_key_exists($this->server, $this->servers))
throw new Exception("The server \"{$this->server}\" is not defined in {$this->deployIniFilename}.");
// Loop through all the servers in deploy.ini
foreach ($this->servers as $name => $server) {
// Deploys to ALL servers by default
// If a server is specified, we skip all servers that don't match the one specified
if ($this->server != '' && $this->server != $name) continue;
$this->output("\r\nConnecting to $name server ($server[host])...");
$this->connect($server);
if( $this->sync ) {
$this->dotRevision = $this->dotRevisionFilename;
// We update .revision file, but don't do any listing or deploying
$this->setRevision();
ftp_close($this->connection);
continue;
}
$files = $this->compare($revision);
$this->output("\r\nSERVER: ".$name);
if ($this->listFiles === true) {
$this->listFiles($files);
} else {
$this->push($files);
}
if (count($this->submodules) > 0) {
foreach ($this->submodules as $submodule) {
$this->repo = $submodule['path'];
$this->currentSubmoduleName = $submodule['name'];
$this->output("\r\nSUBMODULE: ".$this->currentSubmoduleName);
$files = $this->compare($revision);
if ($this->listFiles === true) {
$this->listFiles($files);
} else {
$this->push($files);
}
}
// We've finished deploying submodules, reset settings for the next server
$this->repo = $this->mainRepo;
$this->currentSubmoduleName = false;
}
if (!$this->listFiles) {
$this->output("\r\n------ Deployment complete ------");
}
ftp_close($this->connection);
}
}
/**
* Check what files will be uploaded/deleted
*
* @param array $files
*/
protected function listFiles($files)
{
if (count($files['upload']) == 0 && count($files['delete']) == 0) {
$this->output(" No files to upload.");
}
if (count($files['upload']) > 0) {
$this->output("Files to upload:");
foreach ($files['upload'] as $file_to_upload) {
$this->output(" Upload: ".$file_to_upload);
}
}
if (count($files['delete']) > 0) {
$this->output("Files to delete:");
foreach ($files['delete'] as $file_to_delete) {
$this->output(" Delete: ".$file_to_delete);
}
}
}
/**
* Connect to the Server
*
* @param string $server
* @throws Exception if it can't connect to FTP server
* @throws Exception if it can't login to FTP server
* @throws Exception if it can't change FTP directory
*/
protected function connect($server)
{
// Make sure the $path ends with a slash.
$server['path'] = rtrim($server['path'], '/').'/';
$pathsThatExist = array();
$connection = @ftp_connect($server['host'], $server['port']);
if ($connection) {
if (! ftp_login($connection, $server['user'], $server['pass'])) {
throw new Exception("Could not login to {$server['host']} (Tried to login as {$server['user']}).");
}
ftp_pasv($connection, $server['passive']);
if (@ftp_chdir($connection, $server['path'])) {
$this->connection = $connection;
$this->output("Connected.");
} else {
throw new Exception("Could not change the FTP directory to {$server['path']}.");
}
} else {
throw new Exception("Could not connect to {$server['host']}.");
}
}
/**
* Push Files one by one.
*/
protected function push($files)
{
// If revision is not HEAD, the current one, it means this is a rollback.
// So, we have to revert the files the the state they were in that revision.
if ($this->revision != 'HEAD') {
$this->output("Rolling back");
$command = 'git --git-dir="'.$this->repo.'/.git" --work-tree="'.$this->repo.'" checkout '.$this->revision;
exec(escapeshellcmd($command));
}
$filesToUpload = $files['upload'];
$filesToDelete = $files['delete'];
unset($files);
foreach ($filesToUpload as $file) {
if ($this->currentSubmoduleName) $file = $this->currentSubmoduleName.'/'.$file;
// Make sure the folder exists in the FTP server.
$dir = explode("/", dirname($file));
$path = "";
$ret = true;
for($i = 0, $count = count($dir); $i < $count; $i++) {
$path .= $dir[$i].'/';
if (! isset($pathsThatExist[$path])) {
$origin = ftp_pwd($this->connection);
if (! @ftp_chdir($this->connection, $path)) {
if (! ftp_mkdir($this->connection, $path)) {
$ret = false;
$this->output(" Failed to create '$path'.");
$this->output(" Directory could not be created. Please check if a file with the same name exists in the server and delete it.");
return;
} else {
$this->output(" Created directory '$path'.");
$pathsThatExist[$path] = true;
}
} else {
$pathsThatExist[$path] = true;
}
@ftp_chdir($this->connection, $origin);
}
}
$uploaded = false;
$attempts = 1;
while (! $uploaded) {
if ($attempts == 10) {
throw new Exception("Tried to upload $file 10 times and failed. Something is wrong...");
}
$uploaded = ftp_put($this->connection, $file, $file, FTP_BINARY);
if (! $uploaded) {
$attempts = $attempts + 1;
$this->output(" Failed to upload {$file}. Retrying (attempt $attempts/10)... ");
}
}
$this->output(" \033[0;32muploaded\033[0m \033[01;37m{$file}\033[0m");
}
foreach ($filesToDelete as $file) {
ftp_delete($this->connection, $file);
$this->output(" \033[01;31mremoved\033[0m \033[01;37m{$file}\033[0m ");
}
if (! empty($server['clean_directories'])) {
foreach ($server['clean_directories'] as $dir) {
if (! $tmpFiles = ftp_nlist($this->connection, $dir)) {
$this->output("{$dir} already empty");
continue;
}
foreach ($tmpFiles as $file) {
ftp_delete($this->connection, $file);
}
$this->output(" \033[01;31memptied\033[0m \033[01;37m{$dir}\033[0m");
}
}
if (count($filesToUpload) > 0 or count($filesToDelete) > 0) {
// Set revision on server
$this->setRevision();
} else {
$this->output(" No files to upload.");
}
// If revision is not HEAD, the current one, it means this is a rollback.
// So, we have to revert the master because we reverted to an earlier
// revision before the deploy start.
if ($this->revision != 'HEAD') {
$command = 'git --git-dir="'.$this->repo.'/.git" --work-tree="'.$this->repo.'" checkout master';
exec(escapeshellcmd($command));
}
}
/**
* Sets version hash on the server.
*/
protected function setRevision()
{
// By default we update the revision file to the HEAD commit,
// unless the sync command was called with a specific revision
$isHeadRevision = $this->sync == 'sync' || $this->sync == false;
if ( $isHeadRevision ) {
// Find the revision number of HEAD
$command = "git --git-dir=\"$this->repo/.git\" --work-tree=\"$this->repo\" rev-parse HEAD";
exec(escapeshellcmd($command), $localRevision);
} else {
$localRevision = $this->sync;
}
$temp = tempnam(sys_get_temp_dir(), 'gitRevision');
file_put_contents($temp, $localRevision);
if ( $this->sync ) {
$this->output("\r\nSYNC: Updating remote revision file to ".
($isHeadRevision ? 'current HEAD ('.$localRevision.')' : $localRevision)
);
}
if (ftp_put($this->connection, $this->dotRevision, $temp, FTP_BINARY)) {
unlink($temp);
$this->output(" Remote revision file updated.");
} else {
throw new Exception("Could not update the revision file on server.");
}
}
/**
* Helper method to display messages on the screen.
*
* @param string $message
*/
public function output($message) {
echo $message."\r\n";
}
}