forked from deployphp/deployer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sentry.php
261 lines (223 loc) · 9.23 KB
/
sentry.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
<?php
/*
### Installing
```php
// deploy.php
require 'contrib/sentry.php';
```
### Configuration options
- **organization** *(required)*: the slug of the organization the release belongs to.
- **projects** *(required)*: array of slugs of the projects to create a release for.
- **token** *(required)*: authentication token. Can be created at [https://sentry.io/settings/account/api/auth-tokens/]
- **version** *(required)* – a version identifier for this release.
Can be a version number, a commit hash etc. (Defaults is set to git log -n 1 --format="%h".)
- **version_prefix** *(optional)* - a string prefixed to version.
Releases are global per organization so indipentent projects needs to prefix version number with unique string to avoid conflicts
- **environment** *(optional)* - the environment you’re deploying to. By default framework's environment is used.
For example for symfony, *symfony_env* configuration is read otherwise defaults to 'prod'.
- **ref** *(optional)* – an optional commit reference. This is useful if a tagged version has been provided.
- **refs** *(optional)* - array to indicate the start and end commits for each repository included in a release.
Head commits must include parameters *repository* and *commit*) (the HEAD sha).
They can optionally include *previousCommit* (the sha of the HEAD of the previous release),
which should be specified if this is the first time you’ve sent commit data.
- **commits** *(optional)* - array commits data to be associated with the release.
Commits must include parameters *id* (the sha of the commit), and can optionally include *repository*,
*message*, *author_name*, *author_email* and *timestamp*. By default will send all new commits,
unless it's a first release, then only first 200 will be sent.
- **url** *(optional)* – a URL that points to the release. This can be the path to an online interface to the sourcecode for instance.
- **date_released** *(optional)* – date that indicates when the release went live. If not provided the current time is assumed.
- **sentry_server** *(optional)* – sentry server (if you host it yourself). defaults to hosted sentry service.
- **date_deploy_started** *(optional)* - date that indicates when the deploy started. Defaults to current time.
- **date_deploy_finished** *(optional)* - date that indicates when the deploy ended. If not provided, the current time is used.
- **deploy_name** *(optional)* - name of the deploy
- **git_version_command** *(optional)* - the command that retrieves the git version information (Defaults is set to git log -n 1 --format="%h", other options are git describe --tags --abbrev=0)
```php
// deploy.php
set('sentry', [
'organization' => 'exampleorg',
'projects' => [
'exampleproj'
],
'token' => 'd47828...',
'version' => '0.0.1',
]);
```
### Suggested Usage
Since you should only notify Sentry of a successful deployment, the deploy:sentry task should be executed right at the end.
```php
// deploy.php
after('deploy', 'deploy:sentry');
```
*/
namespace Deployer;
use Closure;
use DateTime;
use Deployer\Utility\Httpie;
desc('Notifying Sentry of deployment');
task(
'deploy:sentry',
static function () {
$now = date('c');
$defaultConfig = [
'version' => null,
'version_prefix' => null,
'refs' => [],
'ref' => null,
'commits' => null,
'url' => null,
'date_released' => $now,
'date_deploy_started' => $now,
'date_deploy_finished' => $now,
'sentry_server' => 'https://sentry.io',
'previous_commit' => null,
'environment' => get('symfony_env', 'prod'),
'deploy_name' => null,
];
if (releaseIsGitDirectory()) {
$defaultConfig['version'] = getReleaseGitRef();
$defaultConfig['commits'] = getGitCommitsRefs();
}
$config = array_merge($defaultConfig, (array) get('sentry'));
array_walk(
$config,
static function (&$value) use ($config) {
if (is_callable($value)) {
$value = $value($config);
}
}
);
if (
!isset($config['organization'], $config['token'], $config['version'])
|| (empty($config['projects']) || !is_array($config['projects']))
) {
throw new \RuntimeException(
<<<EXAMPLE
Required data missing. Please configure sentry:
set(
'sentry',
[
'organization' => 'exampleorg',
'projects' => [
'exampleproj',
'exampleproje2'
],
'token' => 'd47828...',
]
);"
EXAMPLE
);
}
$releaseData = array_filter(
[
'version' => ($config['version_prefix'] ?? '') . $config['version'],
'refs' => $config['refs'],
'ref' => $config['ref'],
'url' => $config['url'],
'commits' => array_slice($config['commits'] ?? [], 0), // reset keys to serialize as array in json
'dateReleased' => $config['date_released'],
'projects' => $config['projects'],
'previousCommit' => $config['previous_commit'],
]
);
$releasesApiUrl = $config['sentry_server'] . '/api/0/organizations/' . $config['organization'] . '/releases/';
$response = Httpie::post(
$releasesApiUrl
)
->header(sprintf('Authorization: Bearer %s', $config['token']))
->body($releaseData)
->getJson();
if (!isset($response['version'], $response['projects'])) {
throw new \RuntimeException(sprintf('Unable to create a release: %s', print_r($response, true)));
}
writeln(
sprintf(
'<info>Sentry:</info> Release of version <comment>%s</comment> ' .
'for projects: <comment>%s</comment> created successfully.',
$response['version'],
implode(', ', array_column($response['projects'], 'slug'))
)
);
$deployData = array_filter(
[
'environment' => $config['environment'],
'name' => $config['deploy_name'],
'url' => $config['url'],
'dateStarted' => $config['date_deploy_started'],
'dateFinished' => $config['date_deploy_finished'],
]
);
$response = Httpie::post(
$releasesApiUrl . $response['version'] . '/deploys/'
)
->header(sprintf('Authorization: Bearer %s', $config['token']))
->body($deployData)
->getJson();
if (!isset($response['id'], $response['environment'])) {
throw new \RuntimeException(sprintf('Unable to create a deployment: %s', print_r($response, true)));
}
writeln(
sprintf(
'<info>Sentry:</info> Deployment <comment>%s</comment> ' .
'for environment <comment>%s</comment> created successfully',
$response['id'],
$response['environment']
)
);
}
);
function releaseIsGitDirectory()
{
return (bool) run('cd {{release_path}} && git rev-parse --git-dir > /dev/null 2>&1 && echo 1 || echo 0');
}
function getReleaseGitRef(): Closure
{
return static function ($config = []): string {
cd('{{release_path}}');
if (isset($config['git_version_command'])) {
return trim(run($config['git_version_command']));
}
return trim(run('git log -n 1 --format="%h"'));
};
}
function getGitCommitsRefs(): Closure
{
return static function ($config = []): array {
$previousReleaseRevision = null;
if (has('previous_release')) {
cd('{{previous_release}}');
$previousReleaseRevision = trim(run('git rev-parse HEAD'));
}
if ($previousReleaseRevision === null) {
$commitRange = 'HEAD';
} else {
$commitRange = $previousReleaseRevision . '..HEAD';
}
cd('{{release_path}}');
try {
$result = run(sprintf('git rev-list --pretty="%s" %s', 'format:%H#%an#%ae#%at#%s', $commitRange));
$lines = array_filter(
// limit number of commits for first release with many commits
array_map('trim', array_slice(explode("\n", $result), 0, 200)),
static function (string $line): bool {
return !empty($line) && strpos($line, 'commit') !== 0;
}
);
return array_map(
static function (string $line): array {
list($ref, $authorName, $authorEmail, $timestamp, $message) = explode('#', $line, 5);
return [
'id' => $ref,
'author_name' => $authorName,
'author_email' => $authorEmail,
'message' => $message,
'timestamp' => date(DateTime::ATOM, (int) $timestamp),
];
},
$lines
);
} catch (\Deployer\Exception\RunException $e) {
writeln($e->getMessage());
return [];
}
};
}