Files
shields/services/codacy/codacy-coverage.service.js
chris48s c73072deed Remove requestOptions2GotOptions compatibility layer (#7270)
* gzip --> decompress

* strictSSL --> https.rejectUnauthorized

* auth --> username/password

* qs --> searchParams

* fix base service auth docs

* completely remove requestOptions2GotOptions layer

* update the docs

Co-authored-by: repo-ranger[bot] <39074581+repo-ranger[bot]@users.noreply.github.com>
2021-11-15 19:56:08 +00:00

74 lines
2.1 KiB
JavaScript

import Joi from 'joi'
import { coveragePercentage as coveragePercentageColor } from '../color-formatters.js'
import { BaseSvgScrapingService, NotFound } from '../index.js'
const schema = Joi.object({
message: Joi.alternatives()
.try(Joi.string().regex(/^[0-9]+%$/), Joi.equal('!'))
.required(),
}).required()
export default class CodacyCoverage extends BaseSvgScrapingService {
static category = 'coverage'
static route = { base: 'codacy/coverage', pattern: ':projectId/:branch*' }
static examples = [
{
title: 'Codacy coverage',
pattern: ':projectId',
namedParams: { projectId: 'e02de8d738bb4701b6345624ea2de66c' },
staticPreview: this.render({ percentage: 90 }),
},
{
title: 'Codacy branch coverage',
pattern: ':projectId/:branch',
namedParams: {
projectId: 'e02de8d738bb4701b6345624ea2de66c',
branch: 'master',
},
staticPreview: this.render({ percentage: 90 }),
},
]
static defaultBadgeData = { label: 'coverage' }
static render({ percentage }) {
return {
message: `${percentage}%`,
color: coveragePercentageColor(percentage),
}
}
static transform({ coverageString }) {
return {
percentage: parseFloat(coverageString.replace(/%$/, '')),
}
}
async handle({ projectId, branch }) {
const { message: coverageString } = await this._requestSvg({
schema,
url: `https://api.codacy.com/project/badge/coverage/${encodeURIComponent(
projectId
)}`,
options: { searchParams: { branch } },
valueMatcher: /text-anchor="middle">([^<>]+)<\/text>/,
errorMessages: {
404: 'project not found',
},
})
// When sending an invalid branch, Codacy ignores the branch, failing
// silently, so we can't provide an error message for this case.
if (coverageString === '!') {
throw new NotFound({
prettyMessage: 'not enabled for this project',
})
}
const { percentage } = this.constructor.transform({ coverageString })
return this.constructor.render({ percentage })
}
}