forked from tlvince/make-coverage-badge
-
Notifications
You must be signed in to change notification settings - Fork 174
/
cli.js
executable file
·103 lines (85 loc) · 2.44 KB
/
cli.js
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env node
/* eslint-disable semi */
const mkdirp = require('mkdirp');
const { get } = require('https');
const { readFile, writeFile } = require('fs');
/**
* Will lookup the argument in the cli arguments list and will return a
* value passed as CLI arg (if found)
* Otherwise will return default value passed
* @param argName - name of hte argument to look for
* @param defaultOutput - default value to return if could not find argument in cli command
* @private
*/
const findArgument = (argName, defaultOutput) => {
if (!argName) {
return defaultOutput;
}
const index = process.argv.findIndex(a => a.match(argName))
if (index < 0) {
return defaultOutput;
}
try {
return process.argv[index + 1];
} catch (e) {
return defaultOutput;
}
}
const outputPath = findArgument('output', './coverage');
const inputPath = findArgument('input', './coverage/coverage-summary.json');
const getColour = (coverage) => {
if (coverage < 80) {
return 'red';
}
if (coverage < 90) {
return 'yellow';
}
return 'brightgreen';
};
const reportKeys = ['lines', 'statements', 'functions', 'branches'];
const getBadge = (report, key) => {
if (!(report && report.total && report.total[key])) {
throw new Error('malformed coverage report');
}
const coverage = (!report.total[key] || typeof report.total[key].pct !== 'number') ? 0 : report.total[key].pct;
const colour = getColour(coverage);
return `https://img.shields.io/badge/Coverage${encodeURI(':')}${key}-${coverage}${encodeURI('%')}-${colour}.svg`;
}
const download = (url, cb) => {
get(url, (res) => {
let file = '';
res.on('data', (chunk) => {
file += chunk;
});
res.on('end', () => cb(null, file));
}).on('error', err => cb(err));
}
const writeBadgeInFolder = (key, res) => {
writeFile(`${outputPath}/badge-${key}.svg`, res, 'utf8', (writeError) => {
if (writeError) {
throw writeError;
}
});
}
const getBadgeByKey = report => (key) => {
const url = getBadge(report, key);
download(url, (err, res) => {
if (err) {
throw err;
}
mkdirp(outputPath, (folderError) => {
if (folderError) {
console.error(`Could not create output directory ${folderError}`);
} else {
writeBadgeInFolder(key, res);
}
})
})
}
readFile(`${inputPath}`, 'utf8', (err, res) => {
if (err) {
throw err;
}
const report = JSON.parse(res);
reportKeys.forEach(getBadgeByKey(report));
});