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
<?php
namespace Codeception\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Codeception\Codecept;
/**
* Auto-updates phar archive from official site: 'http://codeception.com/codecept.phar' .
*
* * `php codecept.phar self-update`
*
* @author Franck Cassedanne <franck@cassedanne.com>
*/
class SelfUpdate extends Command
{
/**
* Class constants
*/
const NAME = 'Codeception';
const GITHUB_REPO = 'Codeception/Codeception';
const PHAR_URL = 'http://codeception.com/releases/%s/codecept.phar';
const PHAR_URL_PHP54 = 'http://codeception.com/releases/%s/php54/codecept.phar';
/**
* Holds the current script filename.
* @var string
*/
protected $filename;
/**
* Holds the live version string.
* @var string
*/
protected $liveVersion;
/**
* {@inheritdoc}
*/
protected function configure()
{
if (isset($_SERVER['argv'], $_SERVER['argv'][0])) {
$this->filename = $_SERVER['argv'][0];
} else {
$this->filename = \Phar::running(false);
}
$this
// ->setAliases(array('selfupdate'))
->setDescription(
sprintf(
'Upgrade <comment>%s</comment> to the latest version',
$this->filename
)
);
parent::configure();
}
/**
* @return string
*/
protected function getCurrentVersion()
{
return Codecept::VERSION;
}
/**
* {@inheritdoc}
*/
public function execute(InputInterface $input, OutputInterface $output)
{
$version = $this->getCurrentVersion();
$output->writeln(
sprintf(
'<info>%s</info> version <comment>%s</comment>',
self::NAME,
$version
)
);
$output->writeln("\n<info>Checking for a new version...</info>\n");
try {
$latestVersion = $this->getLatestStableVersion();
if ($this->isOutOfDate($version, $latestVersion)) {
$output->writeln(
sprintf(
'A newer version is available: <comment>%s</comment>',
$latestVersion
)
);
if (!$input->getOption('no-interaction')) {
$dialog = $this->getHelperSet()->get('question');
$question = new ConfirmationQuestion("\n<question>Do you want to update?</question> ", false);
if (!$dialog->ask($input, $output, $question)) {
$output->writeln("\n<info>Bye-bye!</info>\n");
return;
}
}
$output->writeln("\n<info>Updating...</info>");
$this->retrievePharFile($latestVersion, $output);
} else {
$output->writeln('You are already using the latest version.');
}
} catch (\Exception $e) {
$output->writeln(
sprintf(
"<error>\n%s\n</error>",
$e->getMessage()
)
);
}
}
/**
* Checks whether the provided version is current.
*
* @param string $version The version number to check.
* @param string $latestVersion Latest stable version
* @return boolean Returns True if a new version is available.
*/
private function isOutOfDate($version, $latestVersion)
{
return -1 != version_compare($version, $latestVersion, '>=');
}
/**
* @return string
*/
private function getLatestStableVersion()
{
$stableVersions = $this->filterStableVersions(
$this->getGithubTags(self::GITHUB_REPO)
);
return array_reduce(
$stableVersions,
function ($a, $b) {
return version_compare($a, $b, '>') ? $a : $b;
}
);
}
/**
* @param array $tags
* @return array
*/
private function filterStableVersions($tags)
{
return array_filter($tags, function ($tag) {
return preg_match('/^[0-9]+\.[0-9]+\.[0-9]+$/', $tag);
});
}
/**
* Returns an array of tags from a github repo.
*
* @param string $repo The repository name to check upon.
* @return array
*/
protected function getGithubTags($repo)
{
$jsonTags = $this->retrieveContentFromUrl(
'https://api.github.com/repos/' . $repo . '/tags'
);
return array_map(
function ($tag) {
return $tag['name'];
},
json_decode($jsonTags, true)
);
}
/**
* Retrieves the body-content from the provided URL.
*
* @param string $url
* @return string
* @throws \Exception if status code is above 300
*/
private function retrieveContentFromUrl($url)
{
$ctx = $this->prepareContext($url);
$body = file_get_contents($url, 0, $ctx);
if (isset($http_response_header)) {
$code = substr($http_response_header[0], 9, 3);
if (floor($code / 100) > 3) {
throw new \Exception($http_response_header[0]);
}
} else {
throw new \Exception('Request failed.');
}
return $body;
}
/**
* Add proxy support to context if environment variable was set up
*
* @param array $opt context options
* @param string $url
*/
private function prepareProxy(&$opt, $url)
{
$scheme = parse_url($url)['scheme'];
if ($scheme === 'http' && (!empty($_SERVER['HTTP_PROXY']) || !empty($_SERVER['http_proxy']))) {
$proxy = !empty($_SERVER['http_proxy']) ? $_SERVER['http_proxy'] : $_SERVER['HTTP_PROXY'];
}
if ($scheme === 'https' && (!empty($_SERVER['HTTPS_PROXY']) || !empty($_SERVER['https_proxy']))) {
$proxy = !empty($_SERVER['https_proxy']) ? $_SERVER['https_proxy'] : $_SERVER['HTTPS_PROXY'];
}
if (!empty($proxy)) {
$proxy = str_replace(['http://', 'https://'], ['tcp://', 'ssl://'], $proxy);
$opt['http']['proxy'] = $proxy;
}
}
/**
* Preparing context for request
* @param $url
*
* @return resource
*/
private function prepareContext($url)
{
$opts = [
'http' => [
'follow_location' => 1,
'max_redirects' => 20,
'timeout' => 10,
'user_agent' => self::NAME
]
];
$this->prepareProxy($opts, $url);
return stream_context_create($opts);
}
/**
* Retrieves the latest phar file.
*
* @param string $version
* @param OutputInterface $output
* @throws \Exception
*/
protected function retrievePharFile($version, OutputInterface $output)
{
$temp = basename($this->filename, '.phar') . '-temp.phar';
try {
$sourceUrl = $this->getPharUrl($version);
if (@copy($sourceUrl, $temp)) {
chmod($temp, 0777 & ~umask());
// test the phar validity
$phar = new \Phar($temp);
// free the variable to unlock the file
unset($phar);
rename($temp, $this->filename);
} else {
throw new \Exception('Request failed.');
}
} catch (\Exception $e) {
if (!$e instanceof \UnexpectedValueException
&& !$e instanceof \PharException
) {
throw $e;
}
unlink($temp);
$output->writeln(
sprintf(
"<error>\nSomething went wrong (%s).\nPlease re-run this again.</error>\n",
$e->getMessage()
)
);
}
$output->writeln(
sprintf(
"\n<comment>%s</comment> has been updated.\n",
$this->filename
)
);
}
/**
* Returns Phar file URL for specified version
*
* @param string $version
* @return string
*/
protected function getPharUrl($version)
{
$sourceUrl = self::PHAR_URL;
if (version_compare(PHP_VERSION, '7.0.0', '<')) {
$sourceUrl = self::PHAR_URL_PHP54;
}
return sprintf($sourceUrl, $version);
}
}