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 ( 379b13...ff17e5 )
by Anton
31s
created

functions.php ➔ parse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
rs 10
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 Symfony\Component\Console\Question\ConfirmationQuestion;
20
use Symfony\Component\Console\Question\Question;
21
use Symfony\Component\Finder\Finder;
22
use Symfony\Component\Process\Process;
23
use Deployer\Cluster\ClusterFactory;
24
use Symfony\Component\Console\Input\InputArgument;
25
use Symfony\Component\Console\Input\InputInterface;
26
use Symfony\Component\Console\Input\InputOption;
27
use Symfony\Component\Console\Output\OutputInterface;
28
29
// There are two types of functions: Deployer dependent and Context dependent.
30
// Deployer dependent function uses in definition stage of recipe and may require Deployer::get() method.
31
// Context dependent function uses while task execution and must require only Context::get() method.
32
// But there is also a third type of functions: mixed. Mixed function uses in definition stage and in task
33
// execution stage. They are acts like two different function, but have same name. Example of such function
34
// is set() func. This function determine in which stage it was called by Context::get() method.
35
36
/**
37
 * @param string $name
38
 * @param string|null $host
39
 * @param int $port
40
 * @return BuilderInterface
41 2
 */
42
function server($name, $host = null, $port = 22)
43 2
{
44 2
    $deployer = Deployer::get();
45
46 2
    $env = new Environment();
47
    $config = new Configuration($name, $host, $port);
48
49 2
    if (get('ssh_type') === 'ext-ssh2') {
50
        $server = new Remote\SshExtension($config);
51
    } elseif (get('ssh_type') && get('ssh_type') === 'native') {
52 2
        $server = new Remote\NativeSsh($config);
53 2
    } else {
54
        $server = new Remote\PhpSecLib($config);
55 2
    }
56
57
    $deployer->servers->set($name, $server);
58
    $deployer->environments->set($name, $env);
59
60
    return new Builder($config, $env);
61
}
62
63
64
/**
65 15
 * @param string $name
66
 * @return BuilderInterface
67 15
 */
68 15
function localServer($name)
69 15
{
70
    $deployer = Deployer::get();
71 15
72 15
    $env = new Environment();
73
    $config = new Configuration($name, 'localhost'); // Builder requires server configuration.
74 15
    $server = new Local($config);
75
76
    $deployer->servers->set($name, $server);
77
    $deployer->environments->set($name, $env);
78
79
    return new Builder($config, $env);
80
}
81
82
/**
83
 * @param string $name Name of the cluster
84
 * @param array $nodes An array of nodes' host/ip
85
 * @param int $port Ssh port of the nodes
86
 *
87
 * Example:
88
 * You should pass a cluster name and nodes array.
89
 * Nodes array should be as following:
90
 * [ '192.168.1.1', 'example.com', '192.168.1.5' ]
91 2
 * @return BuilderInterface
92
 */
93 2
function cluster($name, $nodes, $port = 22)
94
{
95 2
    $deployer = Deployer::get();
96
97
    $cluster = ClusterFactory::create($deployer, $name, $nodes, $port);
98
99
    return $cluster->getBuilder();
100
}
101
102
103
/**
104
 * Load server list file.
105 1
 * @param string $file
106 1
 */
107 1
function serverList($file)
108 1
{
109 1
    $bootstrap = new Bootstrap\BootstrapByConfigFile();
110 1
    $bootstrap->setConfig($file);
111
    $bootstrap->parseConfig();
112
    $bootstrap->initServers();
113
    $bootstrap->initClusters();
114
}
115
116
/**
117
 * Set task description.
118
 *
119
 * @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...
120
 * @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...
121
 */
122 17
function desc($title = null)
123
{
124 17
    static $store = null;
125 17
126 17
    if ($title === null) {
127 17
        return $store;
128 3
    } else {
129
        return $store = $title;
130 3
    }
131 3
}
132 3
133 1
/**
134
 * Define a new task and save to tasks list.
135
 *
136 17
 * @param string $name Name of current task.
137 17
 * @param callable|array|string $body Callable task or array of other tasks names.
138
 * @return Task\Task
139 17
 * @throws \InvalidArgumentException
140
 */
141
function task($name, $body)
142
{
143
    $deployer = Deployer::get();
144
145
    if ($body instanceof \Closure) {
146
        $task = new T($name, $body);
147
    } elseif (is_array($body)) {
148
        $task = new GroupTask($name, $body);
149 14
    } elseif (is_string($body)) {
150 1
        $task = new T($name, function () use ($body) {
151 2
            run($body);
152 2
        });
153
    } else {
154 1
        throw new \InvalidArgumentException('Task should be an closure or array of other tasks.');
155 1
    }
156
157
    $deployer->tasks->set($name, $task);
158
159
    if (!empty(desc())) {
160
        $task->desc(desc());
161
        desc(''); // Clear title.
162
    }
163
164
    return $task;
165 1
}
166 1
167 1
/**
168
 * Call that task before specified task runs.
169 1
 *
170 1
 * @param string $it
171
 * @param string $that
172
 */
173
function before($it, $that)
174
{
175
    $deployer = Deployer::get();
176
    $beforeTask = $deployer->tasks->get($it);
177
178
    $beforeTask->addBefore($that);
179
}
180
181
/**
182
 * Call that task after specified task runs.
183
 *
184 14
 * @param string $it
185 14
 * @param string $that
186 14
 */
187 14
function after($it, $that)
188
{
189
    $deployer = Deployer::get();
190
    $afterTask = $deployer->tasks->get($it);
191
192
    $afterTask->addAfter($that);
193
}
194
195
/**
196
 * Add users arguments.
197
 *
198
 * Note what Deployer already has one argument: "stage".
199
 *
200 14
 * @param string $name
201 14
 * @param int $mode
202 14
 * @param string $description
203 14
 * @param mixed $default
204
 */
205
function argument($name, $mode = null, $description = '', $default = null)
206
{
207
    Deployer::get()->getConsole()->getUserDefinition()->addArgument(
208
        new InputArgument($name, $mode, $description, $default)
209
    );
210
}
211
212 2
/**
213 2
 * Add users options.
214
 *
215
 * @param string $name
216
 * @param string $shortcut
217
 * @param int $mode
218
 * @param string $description
219
 * @param mixed $default
220
 */
221
function option($name, $shortcut = null, $mode = null, $description = '', $default = null)
222
{
223
    Deployer::get()->getConsole()->getUserDefinition()->addOption(
224
        new InputOption($name, $shortcut, $mode, $description, $default)
225
    );
226
}
227
228
/**
229
 * Change the current working directory.
230
 *
231
 * @param string $path
232
 */
233
function cd($path)
234
{
235
    set('working_path', parse($path));
236 12
}
237
238
/**
239
 * Execute a callback within a specific directory and revert back to the initial working directory.
240
 *
241
 * @param string $path
242
 * @param callable $callback
243
 */
244
function within($path, $callback)
245
{
246
    $lastWorkingPath = workingPath();
247 12
    set('working_path', $path);
248 12
    $callback();
249 12
    set('working_path', $lastWorkingPath);
250
}
251 12
252 11
/**
253 11
 * Return the current working path.
254
 *
255 12
 * @return string
256
 */
257
function workingPath()
258
{
259 12
    return get('working_path', get(Environment::DEPLOY_PATH, ''));
260
}
261 12
262
/**
263
 * Run command on server.
264
 *
265
 * @param string $command
266
 * @return Result
267 12
 */
268
function run($command)
269
{
270
    $server = Context::get()->getServer();
271
    $serverName = $server->getConfiguration()->getName();
272
    $command = parse($command);
273
    $workingPath = workingPath();
274
275
    if (!empty($workingPath)) {
276
        $command = "cd $workingPath && ($command)";
277
    }
278
279 5
    if (isVeryVerbose()) {
280
        writeln("[$serverName] <fg=red>></fg=red> $command");
281 5
    }
282
283
    if ($server instanceof Local) {
284
        $output = $server->mustRun($command, function ($type, $buffer) use ($serverName) {
285 5 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...
286 5
                output()->writeln(array_map(function ($line) use ($serverName) {
287
                    return output()->isDecorated()
288 4
                        ? "[$serverName] \033[1;30m< $line\033[0m"
289
                        : "[$serverName] < $line";
290
                }, explode("\n", rtrim($buffer))), OutputInterface::OUTPUT_RAW);
291
            }
292
        });
293
    } else {
294
        $output = $server->run($command);
295 5 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...
296
            output()->writeln(array_map(function ($line) use ($serverName) {
297 5
                return output()->isDecorated()
298
                    ? "[$serverName] \033[1;30m< $line\033[0m"
299
                    : "[$serverName] < $line";
300
            }, explode("\n", rtrim($output))), OutputInterface::OUTPUT_RAW);
301 5
        }
302
    }
303
304
    return new Result($output);
305
}
306
307
/**
308
 * Execute commands on local machine.
309
 * @param string $command Command to run locally.
310
 * @param int $timeout (optional) Override process command timeout in seconds.
311
 * @return Result Output of command.
312 1
 * @throws \RuntimeException
313 1
 */
314 1
function runLocally($command, $timeout = 60)
315
{
316 1
    $command = parse($command);
317 1
318
    if (isVeryVerbose()) {
319 1
        writeln("<comment>Run locally</comment>: $command");
320 1
    }
321 1
322
    $process = new Process($command);
323 1
    $process->setTimeout($timeout);
324
    $process->run(function ($type, $buffer) {
325 1
        if (isDebug()) {
326 1
            if ('err' === $type) {
327 1
                write("<fg=red>></fg=red> $buffer");
328 1
            } else {
329 1
                write("<fg=green>></fg=green> $buffer");
330
            }
331
        }
332 1
    });
333 1
334
    if (!$process->isSuccessful()) {
335
        throw new \RuntimeException($process->getErrorOutput());
336
    }
337 1
338 1
    return new Result($process->getOutput());
339 1
}
340 1
341 1
342 1
/**
343
 * Upload file or directory to current server.
344
 * @param string $local
345 1
 * @param string $remote
346
 * @throws \RuntimeException
347
 */
348
function upload($local, $remote)
349
{
350
    $server = Context::get()->getServer();
351
    $local = parse($local);
352
    $remote = parse($remote);
353
354
    if (is_file($local)) {
355 2
        writeln("Upload file <info>$local</info> to <info>$remote</info>");
356 2
357 2
        $server->upload($local, $remote);
358
    } elseif (is_dir($local)) {
359 2
        writeln("Upload from <info>$local</info> to <info>$remote</info>");
360 2
361
        $finder = new Finder();
362
        $files = $finder
363
            ->files()
364
            ->ignoreUnreadableDirs()
365
            ->ignoreVCS(true)
366
            ->ignoreDotFiles(false)
367
            ->in($local);
368 4
369 4
        /** @var $file \Symfony\Component\Finder\SplFileInfo */
370
        foreach ($files as $file) {
371
            if (isDebug()) {
372
                writeln("Uploading <info>{$file->getRealPath()}</info>");
373
            }
374
375
            $server->upload(
376
                $file->getRealPath(),
377
                $remote . '/' . $file->getRelativePathname()
378
            );
379
        }
380
    } else {
381
        throw new \RuntimeException("Uploading path '$local' does not exist.");
382
    }
383
}
384
385
/**
386 14
 * Download file from remote server.
387 14
 *
388
 * @param string $local
389
 * @param string $remote
390
 */
391
function download($local, $remote)
392
{
393
    $server = Context::get()->getServer();
394
    $local = parse($local);
395 4
    $remote = parse($remote);
396
397
    $server->download($local, $remote);
398
}
399
400
/**
401
 * Writes a message to the output and adds a newline at the end.
402
 * @param string|array $message
403
 */
404
function writeln($message)
405
{
406
    output()->writeln($message);
407
}
408
409
/**
410
 * Writes a message to the output.
411
 * @param string $message
412
 */
413
function write($message)
414
{
415
    output()->write($message);
416
}
417
418
/**
419
 * Setup configuration option.
420
 *
421
 * @param string $name
422
 * @param mixed $value
423
 */
424
function set($name, $value)
425
{
426
    if (Context::get() === false) {
427
        Deployer::setDefault($name, $value);
428
    } else {
429
        Context::get()->getEnvironment()->set($name, $value);
430
    }
431
}
432
433
/**
434
 * Merge new config params to existing config array.
435
 *
436
 * @param string $name
437
 * @param array $array
438
 */
439
function add($name, $array)
440
{
441
    if (Context::get() === false) {
442
        Deployer::addDefault($name, $array);
443
    } else {
444
        Context::get()->getEnvironment()->add($name, $array);
445
    }
446
}
447
448
/**
449
 * Get configuration value.
450
 *
451
 * @param string $name
452
 * @param mixed|null $default
453
 * @return mixed
454
 */
455
function get($name, $default = null)
456
{
457
    if (Context::get() === false) {
458
        return Deployer::getDefault($name, $default);
459
    } else {
460
        return Context::get()->getEnvironment()->get($name, $default);
461
    }
462
}
463
464
/**
465
 * Check if there is such configuration option.
466
 *
467
 * @param string $name
468
 * @return boolean
469
 */
470
function has($name)
471
{
472
    if (Context::get() === false) {
473
        return Deployer::hasDefault($name);
474
    } else {
475
        return Context::get()->getEnvironment()->has($name);
476
    }
477
}
478
479
/**
480
 * @param string $message
481
 * @param string|null $default
482
 * @return string
483
 * @codeCoverageIgnore
484
 */
485
function ask($message, $default = null)
486 17
{
487
    if (isQuiet()) {
488
        return $default;
489
    }
490
491
    $helper = Deployer::get()->getHelper('question');
492
493
    $message = "<question>$message" . (($default === null) ? "" : " [$default]") . "</question> ";
494
495
    $question = new Question($message, $default);
496
497
    return $helper->ask(input(), output(), $question);
498
}
499
500
/**
501
 * @param string $message
502
 * @param bool $default
503 1
 * @return bool
504
 * @codeCoverageIgnore
505
 */
506
function askConfirmation($message, $default = false)
507
{
508
    if (isQuiet()) {
509
        return $default;
510
    }
511
512 16
    $helper = Deployer::get()->getHelper('question');
513
514
    $yesOrNo = $default ? 'Y/n' : 'y/N';
515
    $message = "<question>$message [$yesOrNo]</question> ";
516
517
    $question = new ConfirmationQuestion($message, $default);
518
519
    return $helper->ask(input(), output(), $question);
520
}
521 17
522
/**
523
 * @param string $message
524
 * @return string
525
 * @codeCoverageIgnore
526
 */
527
function askHiddenResponse($message)
528
{
529
    if (isQuiet()) {
530
        return '';
531
    }
532
533
    $helper = Deployer::get()->getHelper('question');
534 19
535 14
    $message = "<question>$message</question> ";
536 14
537 19
    $question = new Question($message);
538 19
    $question->setHidden(true);
539 8
    $question->setHiddenFallback(false);
540 6
541
    return $helper->ask(input(), output(), $question);
542 2
}
543
544 2
/**
545
 * @return InputInterface
546 14
 */
547
function input()
548
{
549
    return Context::get()->getInput();
550
}
551
552
553
/**
554
 * @return OutputInterface
555
 */
556 2
function output()
557
{
558
    return Context::get()->getOutput();
559
}
560
561
/**
562
 * @return bool
563
 */
564
function isQuiet()
565
{
566
    return OutputInterface::VERBOSITY_QUIET === output()->getVerbosity();
567
}
568
569
570
/**
571
 * @return bool
572
 */
573
function isVerbose()
574
{
575
    return OutputInterface::VERBOSITY_VERBOSE <= output()->getVerbosity();
576
}
577
578
579
/**
580
 * @return bool
581
 */
582
function isVeryVerbose()
583
{
584
    return OutputInterface::VERBOSITY_VERY_VERBOSE <= output()->getVerbosity();
585
}
586
587
588
/**
589
 * @return bool
590
 */
591
function isDebug()
592
{
593
    return OutputInterface::VERBOSITY_DEBUG <= output()->getVerbosity();
594
}
595
596
/**
597
 * Deprecated, use set()/get().
598
 * @deprecated
599
 */
600
function env()
601
{
602
    throw new \RuntimeException('env() function deprecated. Please, use set() or get() instead of.');
603
}
604
605
/**
606
 * Check if command exist in bash.
607
 *
608
 * @param string $command
609
 * @return bool
610
 */
611
function commandExist($command)
612
{
613
    return run("if hash $command 2>/dev/null; then echo 'true'; fi")->toBool();
614
}
615
616
/**
617
 * Parse set values.
618
 *
619
 * @param string $value
620
 * @return string
621
 */
622
function parse($value)
623
{
624
    return Context::get()->getEnvironment()->parse($value);
625
}
626