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 ( 07f145...3e40fc )
by Anton
02:18
created

functions.php ➔ logger()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
ccs 0
cts 0
cp 0
crap 6
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
 * Add users arguments.
198
 *
199
 * Note what Deployer already has one argument: "stage".
200 14
 *
201 14
 * @param string $name
202 14
 * @param int $mode
203 14
 * @param string $description
204
 * @param mixed $default
205
 */
206
function argument($name, $mode = null, $description = '', $default = null)
207
{
208
    Deployer::get()->getConsole()->getUserDefinition()->addArgument(
209
        new InputArgument($name, $mode, $description, $default)
210
    );
211
}
212 2
213 2
/**
214
 * Add users options.
215
 *
216
 * @param string $name
217
 * @param string $shortcut
218
 * @param int $mode
219
 * @param string $description
220
 * @param mixed $default
221
 */
222
function option($name, $shortcut = null, $mode = null, $description = '', $default = null)
223
{
224
    Deployer::get()->getConsole()->getUserDefinition()->addOption(
225
        new InputOption($name, $shortcut, $mode, $description, $default)
226
    );
227
}
228
229
/**
230
 * Change the current working directory.
231
 *
232
 * @param string $path
233
 */
234
function cd($path)
235
{
236 12
    set('working_path', parse($path));
237
}
238
239
/**
240
 * Execute a callback within a specific directory and revert back to the initial working directory.
241
 *
242
 * @param string $path
243
 * @param callable $callback
244
 */
245
function within($path, $callback)
246
{
247 12
    $lastWorkingPath = workingPath();
248 12
    set('working_path', $path);
249 12
    $callback();
250
    set('working_path', $lastWorkingPath);
251 12
}
252 11
253 11
/**
254
 * Return the current working path.
255 12
 *
256
 * @return string
257
 */
258
function workingPath()
259 12
{
260
    return get('working_path', get(Environment::DEPLOY_PATH, ''));
261 12
}
262
263
/**
264
 * Run command on server.
265
 *
266
 * @param string $command
267 12
 * @return Result
268
 */
269
function run($command)
270
{
271
    $server = Context::get()->getServer();
272
    $serverName = $server->getConfiguration()->getName();
273
    $command = parse($command);
274
    $workingPath = workingPath();
275
276
    if (!empty($workingPath)) {
277
        $command = "cd $workingPath && ($command)";
278
    }
279 5
280
    if (isVeryVerbose()) {
281 5
        writeln("[$serverName] <fg=red>></fg=red> $command");
282
    }
283
284
    logger("[$serverName] > $command");
285 5
286 5
    if ($server instanceof Local) {
287
        $output = $server->mustRun($command, function ($type, $buffer) use ($serverName) {
288 4 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...
289
                output()->writeln(array_map(function ($line) use ($serverName) {
290
                    return output()->isDecorated()
291
                        ? "[$serverName] \033[1;30m< $line\033[0m"
292
                        : "[$serverName] < $line";
293
                }, explode("\n", rtrim($buffer))), OutputInterface::OUTPUT_RAW);
294
            }
295 5
        });
296
    } else {
297 5
        $output = $server->run($command);
298 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...
299
            output()->writeln(array_map(function ($line) use ($serverName) {
300
                return output()->isDecorated()
301 5
                    ? "[$serverName] \033[1;30m< $line\033[0m"
302
                    : "[$serverName] < $line";
303
            }, explode("\n", rtrim($output))), OutputInterface::OUTPUT_RAW);
304
        }
305
    }
306
307
    if (!empty(rtrim($output))) {
308
        logger("[$serverName] < $output");
309
    }
310
311
    return new Result($output);
312 1
}
313 1
314 1
/**
315
 * Execute commands on local machine.
316 1
 * @param string $command Command to run locally.
317 1
 * @param int $timeout (optional) Override process command timeout in seconds.
318
 * @return Result Output of command.
319 1
 * @throws \RuntimeException
320 1
 */
321 1
function runLocally($command, $timeout = 60)
322
{
323 1
    $command = parse($command);
324
325 1
    if (isVeryVerbose()) {
326 1
        writeln("[localhost] <fg=red>></fg=red> : $command");
327 1
    }
328 1
329 1
    logger("[localhost] > $command");
330
331
    $process = new Process($command);
332 1
    $process->setTimeout($timeout);
333 1
    $process->run(function ($type, $buffer) {
334
        if (isDebug()) {
335
            if ('err' === $type) {
336
                write("<fg=red>></fg=red> $buffer");
337 1
            } else {
338 1
                write("<fg=green>></fg=green> $buffer");
339 1
            }
340 1
        }
341 1
    });
342 1
343
    if (!$process->isSuccessful()) {
344
        throw new \RuntimeException($process->getErrorOutput());
345 1
    }
346
347
    $output = $process->getOutput();
348
349
    logger("[localhost] < $output");
350
351
    return new Result($output);
352
}
353
354
355 2
/**
356 2
 * Upload file or directory to current server.
357 2
 * @param string $local
358
 * @param string $remote
359 2
 * @throws \RuntimeException
360 2
 */
361
function upload($local, $remote)
362
{
363
    $server = Context::get()->getServer();
364
    $local = parse($local);
365
    $remote = parse($remote);
366
367
    if (is_file($local)) {
368 4
        writeln("Upload file <info>$local</info> to <info>$remote</info>");
369 4
370
        $server->upload($local, $remote);
371
    } elseif (is_dir($local)) {
372
        writeln("Upload from <info>$local</info> to <info>$remote</info>");
373
374
        $finder = new Finder();
375
        $files = $finder
376
            ->files()
377
            ->ignoreUnreadableDirs()
378
            ->ignoreVCS(true)
379
            ->ignoreDotFiles(false)
380
            ->in($local);
381
382
        /** @var $file \Symfony\Component\Finder\SplFileInfo */
383
        foreach ($files as $file) {
384
            if (isDebug()) {
385
                writeln("Uploading <info>{$file->getRealPath()}</info>");
386 14
            }
387 14
388
            $server->upload(
389
                $file->getRealPath(),
390
                $remote . '/' . $file->getRelativePathname()
391
            );
392
        }
393
    } else {
394
        throw new \RuntimeException("Uploading path '$local' does not exist.");
395 4
    }
396
}
397
398
/**
399
 * Download file from remote server.
400
 *
401
 * @param string $local
402
 * @param string $remote
403
 */
404
function download($local, $remote)
405
{
406
    $server = Context::get()->getServer();
407
    $local = parse($local);
408
    $remote = parse($remote);
409
410
    $server->download($local, $remote);
411
}
412
413
/**
414
 * Writes a message to the output and adds a newline at the end.
415
 * @param string|array $message
416
 */
417
function writeln($message)
418
{
419
    output()->writeln($message);
420
}
421
422
/**
423
 * Writes a message to the output.
424
 * @param string $message
425
 */
426
function write($message)
427
{
428
    output()->write($message);
429
}
430
431
/**
432
 * @param string $message
433
 * @param int $level
434
 */
435
function logger($message, $level = Logger::DEBUG)
436
{
437
    if (is_array($message)) {
438
        $message = join("\n", $message);
439
    }
440
441
    Deployer::get()->getLogger()->log($level, $message);
442
}
443
444
/**
445
 * Setup configuration option.
446
 *
447
 * @param string $name
448
 * @param mixed $value
449
 */
450
function set($name, $value)
451
{
452
    if (Context::get() === false) {
453
        Deployer::setDefault($name, $value);
454
    } else {
455
        Context::get()->getEnvironment()->set($name, $value);
456
    }
457
}
458
459
/**
460
 * Merge new config params to existing config array.
461
 *
462
 * @param string $name
463
 * @param array $array
464
 */
465
function add($name, $array)
466
{
467
    if (Context::get() === false) {
468
        Deployer::addDefault($name, $array);
469
    } else {
470
        Context::get()->getEnvironment()->add($name, $array);
471
    }
472
}
473
474
/**
475
 * Get configuration value.
476
 *
477
 * @param string $name
478
 * @param mixed|null $default
479
 * @return mixed
480
 */
481
function get($name, $default = null)
482
{
483
    if (Context::get() === false) {
484
        return Deployer::getDefault($name, $default);
485
    } else {
486 17
        return Context::get()->getEnvironment()->get($name, $default);
487
    }
488
}
489
490
/**
491
 * Check if there is such configuration option.
492
 *
493
 * @param string $name
494
 * @return boolean
495
 */
496
function has($name)
497
{
498
    if (Context::get() === false) {
499
        return Deployer::hasDefault($name);
500
    } else {
501
        return Context::get()->getEnvironment()->has($name);
502
    }
503 1
}
504
505
/**
506
 * @param string $message
507
 * @param string|null $default
508
 * @return string
509
 * @codeCoverageIgnore
510
 */
511
function ask($message, $default = null)
512 16
{
513
    if (isQuiet()) {
514
        return $default;
515
    }
516
517
    $helper = Deployer::get()->getHelper('question');
518
519
    $message = "<question>$message" . (($default === null) ? "" : " [$default]") . "</question> ";
520
521 17
    $question = new Question($message, $default);
522
523
    return $helper->ask(input(), output(), $question);
524
}
525
526
/**
527
 * @param string $message
528
 * @param bool $default
529
 * @return bool
530
 * @codeCoverageIgnore
531
 */
532
function askConfirmation($message, $default = false)
533
{
534 19
    if (isQuiet()) {
535 14
        return $default;
536 14
    }
537 19
538 19
    $helper = Deployer::get()->getHelper('question');
539 8
540 6
    $yesOrNo = $default ? 'Y/n' : 'y/N';
541
    $message = "<question>$message [$yesOrNo]</question> ";
542 2
543
    $question = new ConfirmationQuestion($message, $default);
544 2
545
    return $helper->ask(input(), output(), $question);
546 14
}
547
548
/**
549
 * @param string $message
550
 * @return string
551
 * @codeCoverageIgnore
552
 */
553
function askHiddenResponse($message)
554
{
555
    if (isQuiet()) {
556 2
        return '';
557
    }
558
559
    $helper = Deployer::get()->getHelper('question');
560
561
    $message = "<question>$message</question> ";
562
563
    $question = new Question($message);
564
    $question->setHidden(true);
565
    $question->setHiddenFallback(false);
566
567
    return $helper->ask(input(), output(), $question);
568
}
569
570
/**
571
 * @return InputInterface
572
 */
573
function input()
574
{
575
    return Context::get()->getInput();
576
}
577
578
579
/**
580
 * @return OutputInterface
581
 */
582
function output()
583
{
584
    return Context::get()->getOutput();
585
}
586
587
/**
588
 * @return bool
589
 */
590
function isQuiet()
591
{
592
    return OutputInterface::VERBOSITY_QUIET === output()->getVerbosity();
593
}
594
595
596
/**
597
 * @return bool
598
 */
599
function isVerbose()
600
{
601
    return OutputInterface::VERBOSITY_VERBOSE <= output()->getVerbosity();
602
}
603
604
605
/**
606
 * @return bool
607
 */
608
function isVeryVerbose()
609
{
610
    return OutputInterface::VERBOSITY_VERY_VERBOSE <= output()->getVerbosity();
611
}
612
613
614
/**
615
 * @return bool
616
 */
617
function isDebug()
618
{
619
    return OutputInterface::VERBOSITY_DEBUG <= output()->getVerbosity();
620
}
621
622
/**
623
 * Deprecated, use set()/get().
624
 * @deprecated
625
 */
626
function env()
627
{
628
    throw new \RuntimeException('env() function deprecated. Please, use set() or get() instead of.');
629
}
630
631
/**
632
 * Check if command exist in bash.
633
 *
634
 * @param string $command
635
 * @return bool
636
 */
637
function commandExist($command)
638
{
639
    return run("if hash $command 2>/dev/null; then echo 'true'; fi")->toBool();
640
}
641
642
/**
643
 * Parse set values.
644
 *
645
 * @param string $value
646
 * @return string
647
 */
648
function parse($value)
649
{
650
    return Context::get()->getEnvironment()->parse($value);
651
}
652