forked from pocketarc/git-deploy-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit-deploy
386 lines (311 loc) · 12.6 KB
/
git-deploy
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
#!/usr/bin/php
<?php
/*
* @todo log all output in file
* @todo command to set file
* @todo command to set whether to print or not
* @todo command to ignore arbitrary files
* @todo command to update to specific revision (including previous, see issue #8)
* @todo see if it ends in .ini, and if it does, don't append .ini
*/
$commands = array('-l', '-r', '--revert');
if (isset($argv[1])) {
if (!in_array($argv[1], $commands)) {
$deploy = $argv[1] . '.ini';
} else {
$deploy = 'deploy.ini';
}
} else {
$deploy = 'deploy.ini';
}
$opts = getopt("lr:", array("revert"));
$list = isset($opts['l']);
$revision = isset($opts['r']) ? $opts['r'] : 'HEAD';
$revert = isset($opts['revert']);
try {
$git = new Terra_Git();
if (!$list) {
$git->setDeployFile($deploy);
if ($revert) {
$git->revert();
} else {
$git->deploy($revision);
}
} else {
$files = $git->getFilesToUpload();
if (count($files['upload']) > 0) {
$git->output("Files to upload:");
foreach ($files['upload'] as $fileToUpload) {
$git->output($fileToUpload);
}
}
if (count($files['delete']) > 0) {
$git->output("Files to delete:");
foreach ($files['delete'] as $fileToDelete) {
$git->output($fileToDelete);
}
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
class Terra_Git {
protected $filesToIgnore = array(
'git-deploy',
'.gitignore',
);
protected $print = true;
protected $logBuffer = '';
protected $logFile = 'git-deploy.log.txt';
protected $submodules = array();
protected $servers = array();
function __construct() {
# Check if there are any submodules in the git repository.
$command = "git submodule status";
$output = array();
exec($command, $output);
foreach ($output as $line) {
$line = explode(' ', $line);
$this->submodules[] = $line[1];
}
}
function setDeployFile($deploy) {
if (!@file_exists($deploy)) {
throw new Exception("File '$deploy' does not exist.");
} else {
$servers = parse_ini_file($deploy, true);
if (!$servers) {
throw new Exception("File '$deploy' is not a valid .ini file.");
} else {
$this->addServers($servers);
}
}
$this->ignoreFile($deploy);
}
function addServers($servers) {
foreach ($servers as $uri => $options) {
if (substr($uri, 0, 6) === 'ftp://') {
$options = array_merge($options, parse_url($uri));
}
# Throw in some default values, in case they're not set.
$options = array_merge(array(
'skip' => false,
'host' => '',
'user' => '',
'pass' => '',
'port' => 21,
'path' => '/',
'passive' => true,
'clean_directories' => array()
), $options);
if ($options['skip']) {
continue;
} else {
$this->servers[$uri] = $options;
}
}
}
function ignoreFile($file) {
$this->filesToIgnore[] = $file;
}
function getFilesToUpload($oldRevision = null, $newRevision = 'HEAD') {
# Get the list of files to update.
if (!empty($oldRevision)) {
$command = "git diff --name-status {$oldRevision} {$newRevision}";
} else {
$command = "git ls-files";
}
$output = array();
exec($command, $output);
$filesToUpload = array();
$filesToDelete = array();
if (!empty($oldRevision)) {
foreach ($output as $line) {
if ($line[0] == 'A' or $line[0] == 'C' or $line[0] == 'M') {
$path = trim(substr($line, 1, strlen($line)));
$filesToUpload[] = $path;
} elseif ($line[0] == 'D') {
$filesToDelete[] = trim(substr($line, 1, strlen($line)));
} else {
throw new Exception("Unknown git-diff status: {$line[0]}");
}
}
} else {
$filesToUpload = $output;
}
foreach ($filesToUpload as $key => $file) {
if (in_array($file, $this->filesToIgnore)) {
unset($filesToUpload[$key]);
}
}
return array(
'upload' => $filesToUpload,
'delete' => $filesToDelete
);
}
function output($message) {
if ($this->print) {
echo $message . "\r\n";
} else {
$this->logBuffer .= $message . "\r\n";
}
}
function __destruct() {
}
function revert() {
foreach ($this->servers as $server) {
$this->deployGitOverFtp($server, 'HEAD', true);
}
}
function deploy($revision = 'HEAD') {
foreach ($this->servers as $server) {
$this->deployGitOverFtp($server, $revision);
}
}
function deployGitOverFtp($server, $revision = 'HEAD', $revert = false) {
if ($revision == 'HEAD') {
$revision = exec('git rev-parse HEAD');
}
# Let's make sure the $path ends with a slash.
if (substr($server['path'], strlen($server['path']) - 1, strlen($server['path'])) !== '/') {
$server['path'] = $server['path'] . '/';
}
$pathsThatExist = array();
# Okay, let's connect to the server.
$connection = @ftp_connect($server['host'], $server['port']);
if (!$connection) {
throw new Exception("Could not connect to {$server['host']}.");
} else {
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'])) {
} else {
throw new Exception("Could not change the FTP directory to {$server['path']}.");
}
$this->output(("----------------------------"));
$this->output("Connected to {$server['host']}{$server['path']}");
$this->output("----------------------------");
# Now that we're logged in to the server, let's get the remote revision.
$remoteRevision = '';
$tmpFile = tmpfile();
if (@ftp_fget($connection, $tmpFile, 'REVISION', FTP_ASCII)) {
fseek($tmpFile, 0);
$remoteRevision = trim(fread($tmpFile, 1024));
fclose($tmpFile);
} else {
# Couldn't get the file. I assume it's because the file didn't exist.
}
$tmpFile = tmpfile();
if (@ftp_fget($connection, $tmpFile, 'PREVIOUS_REVISION', FTP_ASCII)) {
fseek($tmpFile, 0);
$previousRevision = trim(fread($tmpFile, 1024));
fclose($tmpFile);
} else {
# Couldn't get the file. I assume it's because the file didn't exist.
}
if ($revert) {
if (!isset($previousRevision)) {
throw new Exception("Could not find previous revision in {$server['host']}, which means that reverting is not possible.");
}
# Set revision to PREVIOUS_REVISION, for reverting.
$revision = $previousRevision;
if ($remoteRevision != $revision) {
$this->output("Reverting from " . substr($remoteRevision, 0, 6) . " to " . substr($revision, 0, 6) . ".");
$this->output("----------------------------");
}
} else {
if ($remoteRevision != $revision) {
$this->output("Deploying update from " . substr($remoteRevision, 0, 6) . " to " . substr($revision, 0, 6) . ".");
$this->output("----------------------------");
}
}
$files = $this->getFilesToUpload($remoteRevision, $revision);
$filesToUpload = $files['upload'];
$filesToDelete = $files['delete'];
unset($files);
foreach ($filesToUpload as $file) {
# Make sure the folder exists in the FTP server.
$dir = explode("/", dirname($file));
$path = "";
$ret = true;
for ($i = 0; $i < count($dir); $i++) {
$path.= $dir[$i] . '/';
if (!isset($pathsThatExist[$path])) {
$origin = ftp_pwd($connection);
if (!@ftp_chdir($connection, $path)) {
if (!@ftp_mkdir($connection, $path)) {
$ret = false;
$this->output("Failed to create '$path'.");
$this->output("A problem occurred while attempting to create a folder. Upload to this server cannot continue.");
return;
} else {
$this->output("Created directory '$path'.");
$pathsThatExist[$path] = true;
}
} else {
$pathsThatExist[$path] = true;
}
ftp_chdir($connection, $origin);
}
}
$uploaded = false;
$attempts = 1;
while (!$uploaded) {
if ($attempts == 10) {
$this->output("Tried to upload $file 10 times, and failed 10 times. Something is wrong, so I'm going to stop executing now.");
exit;
}
# This makes sure to repeat the upload until it finally succeeds.
# Hopefully helps fix a problem where some files aren't transferred.
$uploaded = @ftp_put($connection, $file, $file, FTP_BINARY);
if (!$uploaded) {
$attempts = $attempts + 1;
$this->output("Failed to upload {$file}. Retrying (attempt $attempts/10)... ");
}
}
$this->output("Uploaded {$file}");
}
foreach ($filesToDelete as $file) {
@ftp_delete($connection, $file);
$this->output("Deleted {$file}");
}
if (!empty($server['clean_directories'])) {
foreach ($server['clean_directories'] as $dir) {
if (!$tmp_files = ftp_nlist($connection, $dir)) {
$this->output("{$dir} already empty");
continue;
}
foreach ($tmp_files as $file) {
ftp_delete($connection, $file);
}
$this->output("Emptied {$dir}");
}
}
if (count($filesToUpload) > 0 or count($filesToDelete) > 0) {
$this->output("----------------------------");
$temp = tempnam(sys_get_temp_dir(), 'gitRevision');
file_put_contents($temp, $revision);
ftp_put($connection, 'REVISION', $temp, FTP_BINARY);
unlink($temp);
$this->output("Uploaded REVISION file.");
# Upload file containing the current revision, for reverting when necessary.
# But, only if the revision we're deploying is different from the one currently deployed.
if ($remoteRevision != $revision) {
$temp = tempnam(sys_get_temp_dir(), 'gitRevision');
file_put_contents($temp, $remoteRevision);
ftp_put($connection, 'PREVIOUS_REVISION', $temp, FTP_BINARY);
unlink($temp);
$this->output("Uploaded PREVIOUS_REVISION file.");
}
} else {
$this->output("No files to upload.");
}
$this->output( "----------------------------");
$this->output("Finished working on {$server['host']}{$server['path']}");
$this->output( "----------------------------");
ftp_close($connection);
}
}
}