GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 16e9eb...57fd75 )
by Anton
02:18
created

functions.php ➔ onFailure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
ccs 2
cts 2
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/* (c) Anton Medvedev <[email protected]>
3
 *
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
namespace Deployer;
8
9
use Deployer\Builder\BuilderInterface;
10
use Deployer\Server\Local;
11
use Deployer\Server\Remote;
12
use Deployer\Server\Builder;
13
use Deployer\Server\Configuration;
14
use Deployer\Server\Environment;
15
use Deployer\Task\Task as T;
16
use Deployer\Task\Context;
17
use Deployer\Task\GroupTask;
18
use Deployer\Type\Result;
19
use Monolog\Logger;
20
use Symfony\Component\Console\Question\ConfirmationQuestion;
21
use Symfony\Component\Console\Question\Question;
22
use Symfony\Component\Finder\Finder;
23
use Symfony\Component\Process\Process;
24
use Deployer\Cluster\ClusterFactory;
25
use Symfony\Component\Console\Input\InputArgument;
26
use Symfony\Component\Console\Input\InputInterface;
27
use Symfony\Component\Console\Input\InputOption;
28
use Symfony\Component\Console\Output\OutputInterface;
29
30
// There are two types of functions: Deployer dependent and Context dependent.
31
// Deployer dependent function uses in definition stage of recipe and may require Deployer::get() method.
32
// Context dependent function uses while task execution and must require only Context::get() method.
33
// But there is also a third type of functions: mixed. Mixed function uses in definition stage and in task
34
// execution stage. They are acts like two different function, but have same name. Example of such function
35
// is set() func. This function determine in which stage it was called by Context::get() method.
36
37
/**
38
 * @param string $name
39
 * @param string|null $host
40
 * @param int $port
41 2
 * @return BuilderInterface
42
 */
43 2
function server($name, $host = null, $port = 22)
44 2
{
45
    $deployer = Deployer::get();
46 2
47
    $env = new Environment();
48
    $config = new Configuration($name, $host, $port);
49 2
50
    if (get('ssh_type') === 'ext-ssh2') {
51
        $server = new Remote\SshExtension($config);
52 2
    } elseif (get('ssh_type') && get('ssh_type') === 'native') {
53 2
        $server = new Remote\NativeSsh($config);
54
    } else {
55 2
        $server = new Remote\PhpSecLib($config);
56
    }
57
58
    $deployer->servers->set($name, $server);
59
    $deployer->environments->set($name, $env);
60
61
    return new Builder($config, $env);
62
}
63
64
65 15
/**
66
 * @param string $name
67 15
 * @return BuilderInterface
68 15
 */
69 15
function localServer($name)
70
{
71 15
    $deployer = Deployer::get();
72 15
73
    $env = new Environment();
74 15
    $config = new Configuration($name, 'localhost'); // Builder requires server configuration.
75
    $server = new Local($config);
76
77
    $deployer->servers->set($name, $server);
78
    $deployer->environments->set($name, $env);
79
80
    return new Builder($config, $env);
81
}
82
83
/**
84
 * @param string $name Name of the cluster
85
 * @param array $nodes An array of nodes' host/ip
86
 * @param int $port Ssh port of the nodes
87
 *
88
 * Example:
89
 * You should pass a cluster name and nodes array.
90
 * Nodes array should be as following:
91 2
 * [ '192.168.1.1', 'example.com', '192.168.1.5' ]
92
 * @return BuilderInterface
93 2
 */
94
function cluster($name, $nodes, $port = 22)
95 2
{
96
    $deployer = Deployer::get();
97
98
    $cluster = ClusterFactory::create($deployer, $name, $nodes, $port);
99
100
    return $cluster->getBuilder();
101
}
102
103
104
/**
105 1
 * Load server list file.
106 1
 * @param string $file
107 1
 */
108 1
function serverList($file)
109 1
{
110 1
    $bootstrap = new Bootstrap\BootstrapByConfigFile();
111
    $bootstrap->setConfig($file);
112
    $bootstrap->parseConfig();
113
    $bootstrap->initServers();
114
    $bootstrap->initClusters();
115
}
116
117
/**
118
 * Set task description.
119
 *
120
 * @param ?string $title
0 ignored issues
show
Documentation introduced by
The doc-type ?string could not be parsed: Unknown type name "?string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
121
 * @return ?string
0 ignored issues
show
Documentation introduced by
The doc-type ?string could not be parsed: Unknown type name "?string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
122 17
 */
123
function desc($title = null)
124 17
{
125 17
    static $store = null;
126 17
127 17
    if ($title === null) {
128 3
        return $store;
129
    } else {
130 3
        return $store = $title;
131 3
    }
132 3
}
133 1
134
/**
135
 * Define a new task and save to tasks list.
136 17
 *
137 17
 * @param string $name Name of current task.
138
 * @param callable|array|string $body Callable task or array of other tasks names.
139 17
 * @return Task\Task
140
 * @throws \InvalidArgumentException
141
 */
142
function task($name, $body)
143
{
144
    $deployer = Deployer::get();
145
146
    if ($body instanceof \Closure) {
147
        $task = new T($name, $body);
148
    } elseif (is_array($body)) {
149 14
        $task = new GroupTask($name, $body);
150 1
    } elseif (is_string($body)) {
151 2
        $task = new T($name, function () use ($body) {
152 2
            run($body);
153
        });
154 1
    } else {
155 1
        throw new \InvalidArgumentException('Task should be an closure or array of other tasks.');
156
    }
157
158
    $deployer->tasks->set($name, $task);
159
160
    if (!empty(desc())) {
161
        $task->desc(desc());
162
        desc(''); // Clear title.
163
    }
164
165 1
    return $task;
166 1
}
167 1
168
/**
169 1
 * Call that task before specified task runs.
170 1
 *
171
 * @param string $it
172
 * @param string $that
173
 */
174
function before($it, $that)
175
{
176
    $deployer = Deployer::get();
177
    $beforeTask = $deployer->tasks->get($it);
178
179
    $beforeTask->addBefore($that);
180
}
181
182
/**
183
 * Call that task after specified task runs.
184 14
 *
185 14
 * @param string $it
186 14
 * @param string $that
187 14
 */
188
function after($it, $that)
189
{
190
    $deployer = Deployer::get();
191
    $afterTask = $deployer->tasks->get($it);
192
193
    $afterTask->addAfter($that);
194
}
195
196
/**
197
 * Setup which task run on failure of first.
198
 *
199
 * @param string $it
200 14
 * @param string $that
201 14
 */
202 14
function onFailure($it, $that)
203 14
{
204
    $deployer = Deployer::get();
205
    $deployer['onFailure']->set($it, $that);
206
}
207
208
/**
209
 * Add users arguments.
210
 *
211
 * Note what Deployer already has one argument: "stage".
212 2
 *
213 2
 * @param string $name
214
 * @param int $mode
215
 * @param string $description
216
 * @param mixed $default
217
 */
218
function argument($name, $mode = null, $description = '', $default = null)
219
{
220
    Deployer::get()->getConsole()->getUserDefinition()->addArgument(
221
        new InputArgument($name, $mode, $description, $default)
222
    );
223
}
224
225
/**
226
 * Add users options.
227
 *
228
 * @param string $name
229
 * @param string $shortcut
230
 * @param int $mode
231
 * @param string $description
232
 * @param mixed $default
233
 */
234
function option($name, $shortcut = null, $mode = null, $description = '', $default = null)
235
{
236 12
    Deployer::get()->getConsole()->getUserDefinition()->addOption(
237
        new InputOption($name, $shortcut, $mode, $description, $default)
238
    );
239
}
240
241
/**
242
 * Change the current working directory.
243
 *
244
 * @param string $path
245
 */
246
function cd($path)
247 12
{
248 12
    set('working_path', parse($path));
249 12
}
250
251 12
/**
252 11
 * Execute a callback within a specific directory and revert back to the initial working directory.
253 11
 *
254
 * @param string $path
255 12
 * @param callable $callback
256
 */
257
function within($path, $callback)
258
{
259 12
    $lastWorkingPath = workingPath();
260
    set('working_path', $path);
261 12
    $callback();
262
    set('working_path', $lastWorkingPath);
263
}
264
265
/**
266
 * Return the current working path.
267 12
 *
268
 * @return string
269
 */
270
function workingPath()
271
{
272
    return get('working_path', get(Environment::DEPLOY_PATH, ''));
273
}
274
275
/**
276
 * Run command on server.
277
 *
278
 * @param string $command
279 5
 * @return Result
280
 */
281 5
function run($command)
282
{
283
    $server = Context::get()->getServer();
284
    $serverName = $server->getConfiguration()->getName();
285 5
    $command = parse($command);
286 5
    $workingPath = workingPath();
287
288 4
    if (!empty($workingPath)) {
289
        $command = "cd $workingPath && ($command)";
290
    }
291
292
    if (isVeryVerbose()) {
293
        writeln("[$serverName] <fg=red>></fg=red> $command");
294
    }
295 5
296
    logger("[$serverName] > $command");
297 5
298
    if ($server instanceof Local) {
299
        $output = $server->mustRun($command, function ($type, $buffer) use ($serverName) {
300 View Code Duplication
            if (isDebug()) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
301 5
                output()->writeln(array_map(function ($line) use ($serverName) {
302
                    return output()->isDecorated()
303
                        ? "[$serverName] \033[1;30m< $line\033[0m"
304
                        : "[$serverName] < $line";
305
                }, explode("\n", rtrim($buffer))), OutputInterface::OUTPUT_RAW);
306
            }
307
        });
308
    } else {
309
        $output = $server->run($command);
310 View Code Duplication
        if (isDebug() && !empty($output)) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
311
            output()->writeln(array_map(function ($line) use ($serverName) {
312 1
                return output()->isDecorated()
313 1
                    ? "[$serverName] \033[1;30m< $line\033[0m"
314 1
                    : "[$serverName] < $line";
315
            }, explode("\n", rtrim($output))), OutputInterface::OUTPUT_RAW);
316 1
        }
317 1
    }
318
319 1
    if (!empty(rtrim($output))) {
320 1
        logger("[$serverName] < $output");
321 1
    }
322
323 1
    return new Result($output);
324
}
325 1
326 1
/**
327 1
 * Execute commands on local machine.
328 1
 * @param string $command Command to run locally.
329 1
 * @param int $timeout (optional) Override process command timeout in seconds.
330
 * @return Result Output of command.
331
 * @throws \RuntimeException
332 1
 */
333 1
function runLocally($command, $timeout = 60)
334
{
335
    $command = parse($command);
336
337 1
    if (isVeryVerbose()) {
338 1
        writeln("[localhost] <fg=red>></fg=red> : $command");
339 1
    }
340 1
341 1
    logger("[localhost] > $command");
342 1
343
    $process = new Process($command);
344
    $process->setTimeout($timeout);
345 1
    $process->run(function ($type, $buffer) {
346
        if (isDebug()) {
347
            if ('err' === $type) {
348
                write("<fg=red>></fg=red> $buffer");
349
            } else {
350
                write("<fg=green>></fg=green> $buffer");
351
            }
352
        }
353
    });
354
355 2
    if (!$process->isSuccessful()) {
356 2
        throw new \RuntimeException($process->getErrorOutput());
357 2
    }
358
359 2
    $output = $process->getOutput();
360 2
361
    logger("[localhost] < $output");
362
363
    return new Result($output);
364
}
365
366
367
/**
368 4
 * Upload file or directory to current server.
369 4
 * @param string $local
370
 * @param string $remote
371
 * @throws \RuntimeException
372
 */
373
function upload($local, $remote)
374
{
375
    $server = Context::get()->getServer();
376
    $local = parse($local);
377
    $remote = parse($remote);
378
379
    if (is_file($local)) {
380
        writeln("Upload file <info>$local</info> to <info>$remote</info>");
381
382
        $server->upload($local, $remote);
383
    } elseif (is_dir($local)) {
384
        writeln("Upload from <info>$local</info> to <info>$remote</info>");
385
386 14
        $finder = new Finder();
387 14
        $files = $finder
388
            ->files()
389
            ->ignoreUnreadableDirs()
390
            ->ignoreVCS(true)
391
            ->ignoreDotFiles(false)
392
            ->in($local);
393
394
        /** @var $file \Symfony\Component\Finder\SplFileInfo */
395 4
        foreach ($files as $file) {
396
            if (isDebug()) {
397
                writeln("Uploading <info>{$file->getRealPath()}</info>");
398
            }
399
400
            $server->upload(
401
                $file->getRealPath(),
402
                $remote . '/' . $file->getRelativePathname()
403
            );
404
        }
405
    } else {
406
        throw new \RuntimeException("Uploading path '$local' does not exist.");
407
    }
408
}
409
410
/**
411
 * Download file from remote server.
412
 *
413
 * @param string $local
414
 * @param string $remote
415
 */
416
function download($local, $remote)
417
{
418
    $server = Context::get()->getServer();
419
    $local = parse($local);
420
    $remote = parse($remote);
421
422
    $server->download($local, $remote);
423
}
424
425
/**
426
 * Writes a message to the output and adds a newline at the end.
427
 * @param string|array $message
428
 */
429
function writeln($message)
430
{
431
    output()->writeln($message);
432
}
433
434
/**
435
 * Writes a message to the output.
436
 * @param string $message
437
 */
438
function write($message)
439
{
440
    output()->write($message);
441
}
442
443
/**
444
 * @param string $message
445
 * @param int $level
446
 */
447
function logger($message, $level = Logger::DEBUG)
448
{
449
    if (is_array($message)) {
450
        $message = join("\n", $message);
451
    }
452
453
    Deployer::get()->getLogger()->log($level, $message);
454
}
455
456
/**
457
 * Setup configuration option.
458
 *
459
 * @param string $name
460
 * @param mixed $value
461
 */
462
function set($name, $value)
463
{
464
    if (Context::get() === false) {
465
        Deployer::setDefault($name, $value);
466
    } else {
467
        Context::get()->getEnvironment()->set($name, $value);
468
    }
469
}
470
471
/**
472
 * Merge new config params to existing config array.
473
 *
474
 * @param string $name
475
 * @param array $array
476
 */
477
function add($name, $array)
478
{
479
    if (Context::get() === false) {
480
        Deployer::addDefault($name, $array);
481
    } else {
482
        Context::get()->getEnvironment()->add($name, $array);
483
    }
484
}
485
486 17
/**
487
 * Get configuration value.
488
 *
489
 * @param string $name
490
 * @param mixed|null $default
491
 * @return mixed
492
 */
493
function get($name, $default = null)
494
{
495
    if (Context::get() === false) {
496
        return Deployer::getDefault($name, $default);
497
    } else {
498
        return Context::get()->getEnvironment()->get($name, $default);
499
    }
500
}
501
502
/**
503 1
 * Check if there is such configuration option.
504
 *
505
 * @param string $name
506
 * @return boolean
507
 */
508
function has($name)
509
{
510
    if (Context::get() === false) {
511
        return Deployer::hasDefault($name);
512 16
    } else {
513
        return Context::get()->getEnvironment()->has($name);
514
    }
515
}
516
517
/**
518
 * @param string $message
519
 * @param string|null $default
520
 * @return string
521 17
 * @codeCoverageIgnore
522
 */
523
function ask($message, $default = null)
524
{
525
    if (isQuiet()) {
526
        return $default;
527
    }
528
529
    $helper = Deployer::get()->getHelper('question');
530
531
    $message = "<question>$message" . (($default === null) ? "" : " [$default]") . "</question> ";
532
533
    $question = new Question($message, $default);
534 19
535 14
    return $helper->ask(input(), output(), $question);
536 14
}
537 19
538 19
/**
539 8
 * @param string $message
540 6
 * @param bool $default
541
 * @return bool
542 2
 * @codeCoverageIgnore
543
 */
544 2
function askConfirmation($message, $default = false)
545
{
546 14
    if (isQuiet()) {
547
        return $default;
548
    }
549
550
    $helper = Deployer::get()->getHelper('question');
551
552
    $yesOrNo = $default ? 'Y/n' : 'y/N';
553
    $message = "<question>$message [$yesOrNo]</question> ";
554
555
    $question = new ConfirmationQuestion($message, $default);
556 2
557
    return $helper->ask(input(), output(), $question);
558
}
559
560
/**
561
 * @param string $message
562
 * @return string
563
 * @codeCoverageIgnore
564
 */
565
function askHiddenResponse($message)
566
{
567
    if (isQuiet()) {
568
        return '';
569
    }
570
571
    $helper = Deployer::get()->getHelper('question');
572
573
    $message = "<question>$message</question> ";
574
575
    $question = new Question($message);
576
    $question->setHidden(true);
577
    $question->setHiddenFallback(false);
578
579
    return $helper->ask(input(), output(), $question);
580
}
581
582
/**
583
 * @return InputInterface
584
 */
585
function input()
586
{
587
    return Context::get()->getInput();
588
}
589
590
591
/**
592
 * @return OutputInterface
593
 */
594
function output()
595
{
596
    return Context::get()->getOutput();
597
}
598
599
/**
600
 * @return bool
601
 */
602
function isQuiet()
603
{
604
    return OutputInterface::VERBOSITY_QUIET === output()->getVerbosity();
605
}
606
607
608
/**
609
 * @return bool
610
 */
611
function isVerbose()
612
{
613
    return OutputInterface::VERBOSITY_VERBOSE <= output()->getVerbosity();
614
}
615
616
617
/**
618
 * @return bool
619
 */
620
function isVeryVerbose()
621
{
622
    return OutputInterface::VERBOSITY_VERY_VERBOSE <= output()->getVerbosity();
623
}
624
625
626
/**
627
 * @return bool
628
 */
629
function isDebug()
630
{
631
    return OutputInterface::VERBOSITY_DEBUG <= output()->getVerbosity();
632
}
633
634
/**
635
 * Deprecated, use set()/get().
636
 * @deprecated
637
 */
638
function env()
639
{
640
    throw new \RuntimeException('env() function deprecated. Please, use set() or get() instead of.');
641
}
642
643
/**
644
 * Check if command exist in bash.
645
 *
646
 * @param string $command
647
 * @return bool
648
 */
649
function commandExist($command)
650
{
651
    return run("if hash $command 2>/dev/null; then echo 'true'; fi")->toBool();
652
}
653
654
/**
655
 * Parse set values.
656
 *
657
 * @param string $value
658
 * @return string
659
 */
660
function parse($value)
661
{
662
    return Context::get()->getEnvironment()->parse($value);
663
}
664