/
index.php
79 lines (63 loc) · 1.6 KB
/
index.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
<?php
/**
* @file
* jenbucket main file.
*
* Receives an incoming POST service request from Bitbucket (https://bitbucket.org)
* and connects this through to a jenkins build.
*
* TODO:
* - input validation.
*/
// Settings.
//
// The location of your jenkins deployment server.
$jenkins_url = 'http://localhost:8080/jenkins';
// Jenkins connection token.
$jenkins_token = '';
// Validation function
function validate($param) {
return !empty($param) && strlen($param) <= 128 && !preg_match('/[^a-zA-Z.-]/', $param);
}
// Initialization
//
// Get incoming.
$incoming = json_decode($_POST["payload"]);
// Validate build.
if (!validate($_GET['project'])) {
print 'No build found';
exit();
}
$project = $_GET['project'];
// Detect branches to build
$branches = array();
foreach ($incoming->commits as $commit) {
if (validate($commit->branch)) {
$branches[] = $commit->branch;
}
if (isset($commit->branches)) {
foreach ($commit->branches as $branch) {
if (validate($branch)) {
$branches[] = $branch;
}
}
}
}
// Start build(s)
//
foreach ($branches as $branch) {
// Construct a request to jenkins.
$url = "$jenkins_url/job/$project/buildWithParameters?GIT_BRANCH=$branch";
if (!empty($jenkins_token)) {
$url .= "&token=$jenkins_token";
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo "---- BUILD $url<br/>\n";
$response = curl_exec($ch);
curl_close($ch);
}