~cypheon/dronecov

dronecov/reporter/index.js -rw-r--r-- 2.0 KiB
562cf37f — Johann Rudloff Update npm dependencies. 4 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import fetch from 'node-fetch';
import fs from 'fs';
import lcovParse from 'lcov-parse';
import process from 'process';

const log = console;

function getPercentage(cov, key) {
  const hit = cov.map(x => x[key]).reduce((acc, entry) => acc + entry.hit, 0);
  const found = cov.map(x => x[key]).reduce((acc, entry) => acc + entry.found, 0);
  return hit / found;
}

function parsePromise(filename) {
  return new Promise((resolve, reject) => {
    lcovParse(filename, (error, result) => {
      if (error !== null) {
        reject(error);
      }
      resolve(result);
    });
  });
}

function main(config) {
  const target = new URL(`${config.repo}/${config.branch}/coverage`, config.server);

  log.info(`reading LCOV info from ${config.info_filename}`);

  return parsePromise(config.info_filename).then(data => {
    const summary = {
      lines: getPercentage(data, "lines"),
      functions: getPercentage(data, "functions"),
    };
    log.info("info file parsed", {summary});

    log.info(`upload summary to ${target} using access token ${config.token.substr(0, 5)}...`);
    return fetch(target, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${config.token}`,
      },
      body: JSON.stringify({
        coverage_total: 100 * summary.lines,
        build_number: config.build_number,
      }),
    }).then((response) => {
      if (response.ok && response.status === 201) {
        log.info('upload complete');
      } else {
        log.error(
          'upload failed',
          {response,
            resBody: response.body}
        );
        throw new Error(`upload failed: ${response.status} ${response.statusText}`);
      }
    });
  });
}

main({
  server: process.env.PLUGIN_SERVER,
  repo: process.env.DRONE_REPO,
  branch: process.env.DRONE_COMMIT_BRANCH,
  token: process.env.DRONECOV_ACCESS_TOKEN,
  build_number: process.env.DRONE_BUILD_NUMBER,
  info_filename: process.env.PLUGIN_LCOV_INFO,
}).catch((error) => {
  log.error('Failed to upload coverage info', {error});
  process.exit(1);
});