php CLI上简单漂亮的打印覆盖检查器。从终端中phpunit的coverage-clover xml文件打印指标。可用于整合机智

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php CLI上简单漂亮的打印覆盖检查器。从终端中phpunit的coverage-clover xml文件打印指标。可用于整合机智相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env php
<?php
/**
 * Based on coverage-checker.php by Marco Pivetta <ocramius@gmail.com>
 * @link https://ocramius.github.io/blog/automated-code-coverage-check-for-github-pull-requests-with-travis/
 *
 *
 * ## API:
 * ```
 * php ./coverage-cli.php [path/to/clover.xml] [minimum coverage limit]
 * ```
 *
 * ## Example:
 * ```
 * php ./coverage-cli.php ./tmp/clover.xml 70
 * ```
 */

$inputFile  = $argv[1];
$percentage = min(100, max(0, (int) $argv[2]));

if (!file_exists($inputFile)) {
    throw new InvalidArgumentException('Invalid input file provided');
}

if (!$percentage) {
    throw new InvalidArgumentException('An integer checked percentage must be given as second parameter');
}

$xml             = new SimpleXMLElement(file_get_contents($inputFile));
$metrics         = $xml->xpath('//coverage/project/metrics');
$totalElements   = $metrics[0]['elements'];
$checkedElements = $metrics[0]['coveredelements'];

$coverage = round(($checkedElements / $totalElements) * 100, 2);

$stats = <<<COVERAGE_STATS
\e[0;37m
Files: ............................ %d
Classes: .......................... %d
Methods: .......................... %d
Elements: ......................... %d
Covered Elements: ................. %d

Total Coverage: ................... %.2f%%
Coverage Limit: ................... %.2f%%
\e[0m
COVERAGE_STATS;

$stats = sprintf(
    $stats,
    $metrics[0]['files'],
    $metrics[0]['classes'],
    $metrics[0]['methods'],
    $metrics[0]['elements'],
    $metrics[0]['coveredelements'],
    $coverage,
    $percentage
);


if ($coverage < $percentage) {
    fwrite(
        STDERR,
        $stats . PHP_EOL . PHP_EOL .
        sprintf(
            "\e[1mCode coverage is \e[1;31m%.2f%%\e[0m\e[1m, which is below the accepted %d%%\e[0m",
            $coverage,
            $percentage
        ) . PHP_EOL . PHP_EOL
    );
    exit(1);
}

fwrite(
    STDERR,
    $stats . PHP_EOL . PHP_EOL .
    sprintf(
        "\e[1mCode coverage is \e[1;32m%.2f%%\e[0m\e[1m - OK!\e[0m",
        $coverage
    ) . PHP_EOL . PHP_EOL
);

以上是关于php CLI上简单漂亮的打印覆盖检查器。从终端中phpunit的coverage-clover xml文件打印指标。可用于整合机智的主要内容,如果未能解决你的问题,请参考以下文章

Python colorama | 详解终端漂亮的彩色打印怎么实现的

Python colorama | 详解终端漂亮的彩色打印怎么实现的

如何为 PHP CLI 启用颜色?

漂亮地打印整个 Pandas 系列/DataFrame

漂亮地将解析树打印到标准输出?

PHP-CLI环境变量的设置和读取