-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdeploy.php
More file actions
344 lines (275 loc) · 10.6 KB
/
deploy.php
File metadata and controls
344 lines (275 loc) · 10.6 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
<?php
/*
BitBucket Sync (c) Alex Lixandru
https://bitbucket.org/alixandru/bitbucket-sync
File: deploy.php
Version: 2.0.0
Description: Local file sync script for BitBucket projects
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
/*
This script has two modes of operation detailed below.
The two modes of operation are complementary and are designed to be used
with projects that are configured to be kept in sync through this script.
The usual way of getting the project prepared is to make an initial full
sync of the project files (through operation mode 2) and then to configure
the POST service hook in BitBucket and let the script synchronize changes
as they happen (through operation mode 1).
1. Commit synchronization
This is the default mode which is used when the script is accessed with
no parameters in the URL. In this mode, the script updates only the files
which have been modified by a commit that was pushed to the repository.
The script reads commit information saved locally by the gateway script
and attempts to synchronize the local file system with the updates that
have been made in the BitBucket project. The list of files which have
been changed (added, updated or deleted) will be taken from the commit
files. This script tries to optimize the synchronization by not processing
files more than once.
2. Full synchronization
This mode can be enabled by specifying the "setup" GET parameter in the URL
in which case, the script will get the full repository from BitBucket and
deploy it locally. This is done by getting a zip archive of the project,
extracting it locally and copying its contents over to the specified
project location, on the local file-system.
This operation mode does not necessarily need a POST service hook to be
defined in BitBucket for the project and is generally suited for initial
set-up of projects that will be kept in sync with this script.
*/
ini_set('display_errors','On');
ini_set('error_reporting', E_ALL);
require_once( 'config.php' );
if(isset($_GET['setup']) && !empty($_GET['setup'])) {
$repo = strip_tags(stripslashes(urldecode($_GET['setup'])));
syncFull($repo);
} else {
syncChanges();
}
/**
* Gets the full content of the repository and stores it locally.
* See explanation at the top of the file for details.
*/
function syncFull($repository) {
global $CONFIG, $DEPLOY, $DEPLOY_BRANCH;
echo "<pre>\nBitBucket Sync - Full Deploy\n=============================\n";
// determine the destination of the deployment
if( array_key_exists($repository, $DEPLOY) ) {
$deployLocation = $DEPLOY[ $repository ] . (substr($DEPLOY[ $repository ], -1) == '/' ? '' : '/');
} else {
echo " # Unknown repository: $repository!";
return false;
}
// determine from which branch to get the data
if( array_key_exists($repository, $DEPLOY_BRANCH) ) {
$deployBranch = $DEPLOY_BRANCH[ $repository ];
} else {
// use the default branch
$deployBranch = $CONFIG['deployBranch'];
}
// build URL to get the full archive
$baseUrl = 'https://bitbucket.org/';
$repoUrl = (!empty($_GET['team']) ? $_GET['team'] : $CONFIG['apiUser']) . "/$repository/";
$branchUrl = 'get/' . $deployBranch . '.zip';
// get the archive
loginfo(" * Fetching archive from $baseUrl$repoUrl$branchUrl\n");
$contents = getFileContents($baseUrl . $repoUrl . $branchUrl);
// store the zip file temporary
$zipFile = 'full-' . time() . '-' . rand(0, 100);
$zipLocation = $CONFIG['commitsFolder'] . (substr($CONFIG['commitsFolder'], -1) == '/' ? '' : '/');
file_put_contents($zipLocation . $zipFile, $contents);
// extract contents
loginfo(" * Extracting archive to $zipLocation\n");
$zip = new ZipArchive;
if( $zip->open($zipLocation . $zipFile) === true ) {
$zip->extractTo($zipLocation);
$stat = $zip->statIndex(0);
$folder = $stat['name'];
$zip->close();
} else {
echo " # Unable to extract files. Is the repository name correct?";
unlink($zipLocation . $zipFile);
return false;
}
// validate extracted content
if( empty($folder) || !is_dir( $zipLocation . $folder ) ) {
echo " # Unable to find the extracted files in $zipLocation\n";
unlink($zipLocation . $zipFile);
return false;
}
// delete the old files
loginfo(" * Deleting old content from $deployLocation\n");
if( deltree($deployLocation) === false ) {
echo " # Unable to completely remove the old files from $deployLocation. Process will be continue anyway!\n";
}
// copy the contents over
loginfo(" * Copying new content to $deployLocation\n");
if( rename($zipLocation . $folder, $deployLocation) === false ) {
echo " # Unable to deploy the extracted files to $deployLocation. Deployment is incomplete!\n";
deltree($zipLocation . $folder);
unlink($zipLocation . $zipFile);
return false;
}
// clean up
loginfo(" * Cleaning up temporary files and folders\n");
deltree($zipLocation . $folder);
unlink($zipLocation . $zipFile);
echo "\nFinished deploying $repository.\n</pre>";
}
/**
* Synchronizes changes from the commit files.
* See explanation at the top of the file for details.
*/
function syncChanges() {
global $CONFIG;
global $processed;
echo "<pre>\nBitBucket Sync\n===============\n";
$processed = array();
$location = $CONFIG['commitsFolder'] . (substr($CONFIG['commitsFolder'], -1) == '/' ? '' : '/');
$commits = @scandir($location, 0);
if($commits)
foreach($commits as $file) {
if( $file != '.' && $file != '..' && is_file($location . $file)
&& stristr($file, $CONFIG['commitsFilenamePrefix']) !== false ) {
// get file contents and parse it
$json = @file_get_contents($location . $file);
if(!$json || !deployChangeSet( $json )) {
echo " # Could not process changeset!\n$json\n\n";
} else {
echo " * Processed commit file $file\n";
}
flush();
// delete file afterwards
unlink( $location . $file );
}
}
echo "\nFinished processing commits.\n</pre>";
}
/**
* Deploys commits to the file-system
*/
function deployChangeSet( $postData ) {
global $CONFIG, $DEPLOY, $DEPLOY_BRANCH;
global $processed;
$o = json_decode($postData);
if( !$o ) {
// could not parse ?
return false;
}
// determine the destination of the deployment
if( array_key_exists($o->repository->slug, $DEPLOY) ) {
$deployLocation = $DEPLOY[ $o->repository->slug ] . (substr($DEPLOY[ $o->repository->slug ], -1) == '/' ? '' : '/');
} else {
// unknown repository ?
return false;
}
// determine from which branch to get the data
if( array_key_exists($o->repository->slug, $DEPLOY_BRANCH) ) {
$deployBranch = $DEPLOY_BRANCH[ $o->repository->slug ];
} else {
// use the default branch
$deployBranch = $CONFIG['deployBranch'];
}
// build URL to get the updated files
$baseUrl = $o->canon_url; # https://bitbucket.org
$apiUrl = '/api/1.0/repositories'; # /api/1.0/repositories
$repoUrl = $o->repository->absolute_url; # /user/repo/
$rawUrl = 'raw/'; # raw/
$branchUrl = $deployBranch . '/'; # branch/
// prepare to get the files
$pending = array();
// loop through commits
foreach($o->commits as $commit) {
// if commit was on the branch we're watching, deploy changes
if( $commit->branch == $deployBranch ) {
// if there are any pending files, merge them in
$files = array_merge($pending, $commit->files);
// clean pending, if any
$pending = array();
// get a list of files
foreach($files as $file) {
if( $file->type == 'modified' || $file->type == 'added' ) {
if( empty($processed[$file->file]) ) {
$processed[$file->file] = 1; // mark as processed
$contents = getFileContents($baseUrl . $apiUrl . $repoUrl . $rawUrl . $branchUrl . $file->file);
if( $contents == 'Not Found' ) {
// try one more time, BitBucket gets weirdo sometimes
$contents = getFileContents($baseUrl . $apiUrl . $repoUrl . $rawUrl . $branchUrl . $file->file);
}
if( $contents != 'Not Found' ) {
if( !is_dir( dirname($deployLocation . $file->file) ) ) {
// attempt to create the directory structure first
mkdir( dirname($deployLocation . $file->file), 0755, true );
}
file_put_contents( $deployLocation . $file->file, $contents );
loginfo(" - Synchronized $file->file\n");
} else {
echo " ! Could not get file contents for $file->file\n";
flush();
}
}
} else if( $file->type == 'removed' ) {
unlink( $deployLocation . $file->file );
$processed[$file->file] = 0; // to allow for subsequent re-creating of this file
loginfo(" - Removed $file->file\n");
}
}
} else if(empty($commit->branch) && empty($commit->branches)) {
// unknown branch for now, keep these files
$pending = array_merge($pending, $commit->files);
}
}
return true;
}
/**
* Gets a remote file contents using CURL
*/
function getFileContents($url) {
global $CONFIG;
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
if(!empty($CONFIG['apiUser'])) {
curl_setopt($ch, CURLOPT_USERPWD, $CONFIG['apiUser'] . ':' . $CONFIG['apiPassword']);
}
curl_setopt($ch, CURLOPT_SSLVERSION,3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// grab URL
$data = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
return $data;
}
/**
* Deletes a directory recursively, no matter whether it is empty or not
*/
function deltree($dir) {
if (!file_exists($dir)) return false;
if (!is_dir($dir) || is_link($dir)) return unlink($dir);
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? deltree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
/**
* Outputs some information to the screen if verbose mode is enabled
*/
function loginfo($message) {
global $CONFIG;
if( $CONFIG['verbose'] ) {
echo $message;
flush();
}
}