Devel-Cover-Report-Coveralls

 view release on metacpan or  search on metacpan

lib/Devel/Cover/Report/Coveralls.pm  view on Meta::CPAN

# file when it exists: the build may change the copy (the #! line of a script).
sub get_source {
    my ($file, $callback) = @_;

    my $source = '';
    my @coverage;
    my $digest = Digest::MD5->new;

    open my $fh, '<:raw', $file or warn("Unable to open $file: $!\n"), return;

    while (defined(my $l = <$fh>)) {
        $digest->add($l);
        $l =~ s/(?:\r?\n|\r)\z//;
        my $n = $.;

        $source .= "$l\n";
        push @coverage, $callback->($n);
    }

    close($fh);

    if ($source =~ /[^\x00-\x7f]/) {
        local $@;
        my $text = eval { Encode::decode('UTF-8', $source, Encode::FB_CROAK | Encode::LEAVE_SRC) };
        if (defined $text) {
            $text =~ s/\A\x{FEFF}//;    # a byte order mark is not part of line 1
            $source = $text;
        }
    }

    if ($file =~ s!^blib/!!) {
        if (open my $orig, '<:raw', $file) {
            $digest = Digest::MD5->new->addfile($orig);
        }
    }

    return +{
        name => $file,
        source => $source,
        source_digest => $digest->hexdigest,
        coverage => \@coverage,
    };
}

# The encoder of the job's JSON: the first of @JSON_ENCODERS that is installed, else JSON::PP. On a
# large distribution most of the time of report goes into the encoding, which Cpanel::JSON::XS
# (recommended in cpanfile) does in a fraction of the time of JSON::PP. With ascii it gives the
# same JSON as JSON::PP, which t/01_basic.t checks: a character out of ASCII as \uXXXX, one out of
# the BMP as a surrogate pair.
sub json_encoder {
    for my $class (@JSON_ENCODERS) {
        (my $file = "$class.pm") =~ s!::!/!g;
        return $class->new->ascii if eval { require $file; 1 };
        # Installed but not loadable, e.g. built for another version of Perl.
        warn "$class is not used: $@" if $@ !~ /^Can't locate \Q$file\E in \@INC/;
    }
    return JSON::PP->new->ascii;
}

# The body of a request to the jobs API: the job as a JSON file in the multipart field json_file,
# the form the API documents (https://docs.coveralls.io/api-jobs-endpoint). Returns the content
# type and the body. The boundary is not quoted in the content type, as the official
# coverage-reporter does for the nginx of coveralls.io, and is made so that it does not occur in
# the JSON (which holds the source files, this module's own among them).
sub json_file_request {
    my $json = shift;

    my $boundary;
    do {
        $boundary = 'CoverallsPerl' . join '', map { sprintf '%04x', int rand 0x10000 } 1 .. 8;
    } while index($json, $boundary) >= 0;

    my $body = join "\r\n",
        "--$boundary",
        'Content-Disposition: form-data; name="json_file"; filename="json_file"',
        'Content-Type: application/json',
        '',
        $json,
        "--$boundary--",
        '';

    return ("multipart/form-data; boundary=$boundary", $body);
}

sub git_log {
    my $format = shift;

    my $text = '';

    # No quotes around the format: cmd.exe on Windows does not take single quotes as quotes, so git
    # would print them. A format given here has no spaces and one % at most: cmd.exe expands
    # %name% when a variable of that name is set.
    my $command = "git log -1 --encoding=UTF-8 --pretty=format:$format";
    if (open(my $fh, '-|:encoding(UTF-8)', $command)) {
        $text = do { local $/; <$fh> };
        close $fh;
    }

    return $text;
}

# The values of the git log formats, from one git log. The formats are joined by NUL and git is
# run without a shell, so that cmd.exe on Windows does not expand the %...% between them. Perl
# before 5.22 on Windows has no list form of a piped open; there each format gets a git log of
# its own (git_log).
sub git_log_fields {
    my @formats = @_;

    my $fh;
    my $opened = eval {
        open $fh, '-|:encoding(UTF-8)',
            'git', 'log', '-1', '--encoding=UTF-8', '--pretty=format:' . join('%x00', @formats);
    };
    return map { git_log($_) } @formats if !defined $opened && $@;
    return ('') x @formats if !$opened;

    my $text = do { local $/; <$fh> };
    close $fh;
    # A NUL in the last field (the subject) only cuts it short.
    my @values = split /\0/, $text // '', -1;
    return map { $values[$_] // '' } 0 .. $#formats;

lib/Devel/Cover/Report/Coveralls.pm  view on Meta::CPAN

    return $git;
}

# A switch in an environment variable (COVERALLS_PARALLEL, COVERALLS_NO_FAIL) is on unless it is
# unset, empty, "false" or "0", as COVERALLS_PARALLEL is in the official coverage-reporter.
sub is_enabled {
    my $value = shift;
    return defined $value && $value ne '' && $value ne 'false' && $value ne '0';
}

# Reads the response of the jobs API (an HTTP::Tiny response). Returns the URL of the job, or
# undef and the error to show.
sub parse_response {
    my $response = shift;
    my $content = $response->{content} // '';
    my $res = eval { decode_json $content };
    my $status = "$response->{status} $response->{reason}";
    if (!$res || ref $res ne 'HASH') {
        # HTTP::Tiny puts its own error (e.g. a failed connection) into the content, with status 599.
        # An error page from a proxy can be long, so only its start is shown.
        $content =~ s/\s+\z//;
        $content = substr($content, 0, 200) . '...' if length $content > 200;
        return (undef, "$status: $content");
    }
    # A job that was registered always has its URL.
    return ($res->{url}, undef) if $response->{success} && $res->{url};
    return (undef, $res->{message} || $status);
}

# The number of the pull request in the event payload of GitHub Actions, or undef.
sub github_event_pull_request {
    my $path = shift;
    return undef unless $path;
    open my $fh, '<:raw', $path or return undef;
    my $event = eval { local $/; decode_json scalar <$fh> } or return undef;
    my $number = ref $event->{pull_request} eq 'HASH' && $event->{pull_request}{number};
    return $number && $number =~ /^\d+$/ ? $number : undef;
}

# Put the branch and the commit that the CI service gave (get_config) into the
# git information, over what git itself says.
sub apply_ci_git_info {
    my ($json, $git) = @_;
    $git->{branch} = $json->{service_branch} if defined $json->{service_branch};
    $git->{head}{id} = $json->{commit_sha} if defined $json->{commit_sha};
    return $git;
}

sub get_config {
    my $config = {};
    if (-f $CONFIG_FILE) {
        $config = YAML::LoadFile($CONFIG_FILE);
    }

    my $json = {};
    $json->{repo_token} = $config->{repo_token} if $config->{repo_token};
    $json->{repo_token} = $ENV{COVERALLS_REPO_TOKEN} if $ENV{COVERALLS_REPO_TOKEN};
    $json->{flag_name} = $ENV{COVERALLS_FLAG_NAME} if $ENV{COVERALLS_FLAG_NAME};
    $json->{parallel} = \1 if is_enabled($ENV{COVERALLS_PARALLEL});

    my $endpoint = ($ENV{COVERALLS_ENDPOINT} || $API_ENDPOINT) . $API_ENDPOINT_STEM;
    if ($ENV{TRAVIS}) {
        $json->{service_name} = $config->{service_name} || 'travis-ci';
        $json->{service_job_id} = $ENV{TRAVIS_JOB_ID};
        if($ENV{TRAVIS_PULL_REQUEST} && $ENV{TRAVIS_PULL_REQUEST} ne 'false'){
            $json->{service_pull_request} = $ENV{TRAVIS_PULL_REQUEST};
        }
    } elsif ($ENV{CIRCLECI}) {
        $json->{service_name} = 'circleci';
        $json->{service_number} = $ENV{CIRCLE_WORKFLOW_ID};
        # The URL of the pull request; its number is at the end. CI_PULL_REQUEST is the older name.
        if (($ENV{CIRCLE_PULL_REQUEST} || $ENV{CI_PULL_REQUEST} // '') =~ /(\d+)$/) {
            $json->{service_pull_request} = $1;
        }
        $json->{service_branch} = $ENV{CIRCLE_BRANCH} if $ENV{CIRCLE_BRANCH};
        $json->{commit_sha} = $ENV{CIRCLE_SHA1} if $ENV{CIRCLE_SHA1};
    } elsif($ENV{DRONE}) {
        $json->{service_name} = 'drone';
        $json->{service_number} = $ENV{DRONE_BUILD_NUMBER};
        $json->{service_pull_request} = $ENV{DRONE_PULL_REQUEST} if $ENV{DRONE_PULL_REQUEST};
    } elsif ($ENV{SEMAPHORE}) {
        $json->{service_name} = 'semaphore';
        $json->{service_number} = $ENV{SEMAPHORE_BUILD_NUMBER} if $ENV{SEMAPHORE_BUILD_NUMBER};
        # Also support semaphore 2.x
        $json->{service_number} = $ENV{SEMAPHORE_WORKFLOW_ID} if $ENV{SEMAPHORE_WORKFLOW_ID};
        $json->{service_pull_request} = $ENV{SEMAPHORE_GIT_PR_NUMBER} if $ENV{SEMAPHORE_GIT_PR_NUMBER};
    } elsif ($ENV{JENKINS_URL}) {
        $json->{service_name} = 'jenkins';
        $json->{service_number} = $ENV{BUILD_NUMBER} if $ENV{BUILD_NUMBER};
        $json->{service_job_id} = $ENV{BUILD_ID} if $ENV{BUILD_ID};
        # Set by multibranch pipelines. In a pull request build, BRANCH_NAME is "PR-<number>" and
        # CHANGE_BRANCH is the source branch, so CHANGE_BRANCH comes first.
        my $branch = $ENV{CHANGE_BRANCH} || $ENV{BRANCH_NAME};
        $json->{service_branch} = $branch if $branch;
        $json->{service_pull_request} = $ENV{CHANGE_ID} if $ENV{CHANGE_ID};
    } elsif ($ENV{GITLAB_CI}) {
        $json->{service_name} = 'gitlab-ci';
        $json->{service_number} = $ENV{CI_PIPELINE_IID} if $ENV{CI_PIPELINE_IID};
        $json->{service_job_id} = $ENV{CI_JOB_NAME} if $ENV{CI_JOB_NAME};
        $json->{service_pull_request} = $ENV{CI_MERGE_REQUEST_IID} if $ENV{CI_MERGE_REQUEST_IID};
        $json->{service_branch} = $ENV{CI_COMMIT_REF_NAME} if $ENV{CI_COMMIT_REF_NAME};
        $json->{commit_sha} = $ENV{CI_COMMIT_SHA} if $ENV{CI_COMMIT_SHA};
    } elsif ($ENV{TF_BUILD} || $ENV{SYSTEM_TEAMFOUNDATIONSERVERURI}) {
        $json->{service_name}   = 'azure-pipelines';
        $json->{service_number} = $ENV{BUILD_BUILDID};
        $json->{service_pull_request} = $ENV{SYSTEM_PULLREQUEST_PULLREQUESTNUMBER}
            if $ENV{SYSTEM_PULLREQUEST_PULLREQUESTNUMBER};
        $json->{service_branch} = $ENV{BUILD_SOURCEBRANCHNAME} if $ENV{BUILD_SOURCEBRANCHNAME};
        $json->{commit_sha} = $ENV{BUILD_SOURCEVERSION} if $ENV{BUILD_SOURCEVERSION};
    } elsif ($ENV{GITHUB_ACTIONS}) {
        # The values of the official coverage-reporter (src/coverage_reporter/ci/github.cr).
        $json->{service_name} = 'github';
        # Coveralls accepts the GITHUB_TOKEN of the workflow in place of the repo token.
        $json->{repo_token} ||= $ENV{GITHUB_TOKEN};
        # The run groups the jobs of a parallel build, and the "done" webhook names it.
        $json->{service_number} = $ENV{GITHUB_RUN_ID} if $ENV{GITHUB_RUN_ID};
        $json->{service_attempt} = $ENV{GITHUB_RUN_ATTEMPT} if $ENV{GITHUB_RUN_ATTEMPT};
        if ($ENV{GITHUB_JOB}) {
            # Every leg of a matrix has the same GITHUB_JOB; the flag name tells them apart.
            $json->{service_job_id} = $ENV{COVERALLS_FLAG_NAME}
                ? "$ENV{GITHUB_JOB}-$ENV{COVERALLS_FLAG_NAME}" : $ENV{GITHUB_JOB};
        }
        my $ref = $ENV{GITHUB_REF} // '';
        if ($ref =~ m!^refs/pull/(\d+)/!) {
            $json->{service_pull_request} = $1;
        } elsif (my $number = github_event_pull_request($ENV{GITHUB_EVENT_PATH})) {
            # pull_request_target runs on the base branch, so GITHUB_REF is not refs/pull/.
            $json->{service_pull_request} = $number;
        }
        # GITHUB_HEAD_REF is the source branch of a pull request; GITHUB_REF_NAME is "<number>/merge"
        # there. Older runners do not set GITHUB_REF_NAME.
        my ($from_ref) = $ref =~ m!^refs/(?:heads|tags)/(.+)$!;
        my $branch = $ENV{GITHUB_HEAD_REF} || $ENV{GITHUB_REF_NAME} || $from_ref;
        $json->{service_branch} = $branch if $branch;
        $json->{commit_sha} = $ENV{GITHUB_SHA} if $ENV{GITHUB_SHA};
    } else {
        $json->{service_name} = $config->{service_name} || $SERVICE_NAME;
        # A build that the environment gives the values of a CI service (the overrides below) is
        # one of a CI service that is not detected, not an upload by hand. The official
        # coverage-reporter sends manual only when COVERALLS_RUN_LOCALLY is set.
        $json->{service_event_type} = 'manual'
            unless grep { defined env_value($_) } qw(
                COVERALLS_SERVICE_NAME COVERALLS_PERL_SERVICE_NAME COVERALLS_SERVICE_NUMBER
                COVERALLS_SERVICE_JOB_ID COVERALLS_SERVICE_JOB_NUMBER
            );
    }

    # Coveralls requires the token on every CI service, Travis CI included.
    die "required repo_token in $CONFIG_FILE, make sure the environment var \"COVERALLS_REPO_TOKEN\" is set" if !$json->{repo_token};

    # Overrides over what the CI service gives, under the names of the official coverage-reporter
    # (src/coverage_reporter/config.cr). They also let a build that no CI service is detected for
    # send these values.
    my @overrides = (
        [ service_name         => 'COVERALLS_SERVICE_NAME' ],
        [ service_number       => 'COVERALLS_SERVICE_NUMBER' ],
        [ service_job_id       => 'COVERALLS_SERVICE_JOB_ID' ],
        [ service_job_number   => 'COVERALLS_SERVICE_JOB_NUMBER' ],
        [ service_pull_request => 'COVERALLS_PULL_REQUEST' ],
        [ service_branch       => 'COVERALLS_GIT_BRANCH' ],
        [ commit_sha           => 'COVERALLS_GIT_COMMIT' ],
        # The older name of COVERALLS_SERVICE_NAME. It comes after it, so it wins when both are set.
        [ service_name         => 'COVERALLS_PERL_SERVICE_NAME' ],
        [ service_event_type   => 'COVERALLS_EVENT_TYPE' ],
    );
    for my $override (@overrides) {
        my ($key, $name) = @$override;
        my $value = env_value($name);
        $json->{$key} = $value if defined $value;
    }
    # "false" is what Travis CI gives on a push, which a CI template may pass on as it is.
    delete $json->{service_pull_request}
        if defined $ENV{COVERALLS_PULL_REQUEST} && $ENV{COVERALLS_PULL_REQUEST} eq 'false';

    return ($json, $endpoint);
}

sub _parse_line ($) {
    my $c = shift;

    return sub {
        my $l = $c->location(shift);

        return $l unless $l;

        if ($l->[0]->uncoverable) {
            return undef;
        } else {
            return $l->[0]->covered;
        }
    };
}

# The branch coverage of a file, in the form of the jobs API: a flat list of four numbers for each
# branch, its line, its block (the decision on that line, from 0), its branch (0 for the true side
# of the decision, 1 for the false side) and the times it was taken, as the official
# coverage-reporter sends LCOV's BRDA. Branches marked uncoverable are left out. $criterion is
# undef when the branch coverage was not collected (cover -coverage statement).
sub get_branches {
    my ($criterion, $lines) = @_;

    my @branches;
    return \@branches unless $criterion;
    for my $line (1 .. $lines) {
        my $decisions = $criterion->location($line) or next;
        for my $block (0 .. $#$decisions) {
            my $decision = $decisions->[$block];
            for my $branch (0 .. $decision->total - 1) {
                next if $decision->uncoverable($branch);
                push @branches, $line, $block, $branch, $decision->value($branch) // 0;
            }
        }
    }

    return \@branches;
}

sub report {
    my ($pkg, $db, $options) = @_;

    my $cover = $db->cover;

    my @sfs;

    for my $file (@{$options->{file}}) {
        my $f = $cover->file($file);
        my $c = $f->statement();

        my $sf = get_source( $file, _parse_line $c ) or next;
        my $branches = get_branches($f->branch, scalar @{ $sf->{coverage} });
        $sf->{branches} = $branches if @$branches;
        push @sfs, $sf;
    }

    my ($json, $endpoint) = eval { get_config() };
    if (!$json) {
        # No repo token, which happens on pull requests from forks: they get no secrets.
        die $@ unless is_enabled($ENV{COVERALLS_NO_FAIL});
        print "- Report::Coveralls --------\nerror: $@----------------------------\n";
        return;
    }
    $json->{git} = apply_ci_git_info($json, eval { get_git_info() } || {});
    $json->{source_files} = \@sfs;

    my $coder = json_encoder();

    my ($content_type, $body) = json_file_request($coder->encode($json));
    my $response = HTTP::Tiny->new( verify_SSL => 1 )->request('POST', $endpoint, {
        headers => { 'Content-Type' => $content_type },
        content => $body,
    });

    my ($url, $error) = parse_response($response);

    print("- Report::Coveralls --------\n");
    if(exists($json->{service_number})){
        print "My build number: ". $json->{service_number} ."\n";
    }
    if (defined $error) {
        print "error: $error\n";
    } else {
        print "register: $url\n";
    }
    if($json->{parallel}){
        print "Parallel mode: True". "\n"
    }
    print("----------------------------\n");

    # cover does not catch this, so it exits with a non-zero status and the CI job fails.
    die "The upload to Coveralls failed. Set COVERALLS_NO_FAIL=1 to exit 0 instead.\n"
        if defined $error && !is_enabled($ENV{COVERALLS_NO_FAIL});
}


1;
__END__

=encoding utf-8

=head1 NAME

Devel::Cover::Report::Coveralls - Coveralls backend for Devel::Cover

=head1 USAGE

=head2 GitHub Actions

1. Add your repo to Coveralls. L<https://coveralls.io/repos/new>

2. Add a workflow, e.g. F<.github/workflows/test.yml>. The C<GITHUB_TOKEN> of the workflow is
enough to send the report; you do not need the repo token of Coveralls.

  name: test
  on: [push, pull_request]
  jobs:
    test:
      runs-on: ubuntu-latest
      steps:
        - uses: actions/checkout@v7
        - uses: shogo82148/actions-setup-perl@v1
          with:
            perl-version: '5.42'
        - run: cpanm -n --installdeps .
        - run: cpanm -n Devel::Cover::Report::Coveralls
        - run: cover -test -report coveralls
          env:
            GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}



( run in 0.428 second using v1.01-cache-2.11-cpan-eb134014566 )