Skip to content

Commit

Permalink
chore: run the linter and write formatting fixes too
Browse files Browse the repository at this point in the history
  • Loading branch information
zimeg committed Dec 2, 2024
1 parent ca248a1 commit ead05e0
Show file tree
Hide file tree
Showing 11 changed files with 359 additions and 120 deletions.
8 changes: 6 additions & 2 deletions src/get-sha.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
module.exports = function getCommitSHA(core, github) {
// Get GitHub-event-relevant contextual details, like commit SHA
const ctx = github.context;
core.debug(`event is ${ctx.eventName} with payload ${JSON.stringify(ctx.payload, null, 2)}`);
core.debug(
`event is ${ctx.eventName} with payload ${JSON.stringify(ctx.payload, null, 2)}`,
);
let sha;
// Depending on the exact GitHub event that triggers the action, we need to report the status on different payload
// fields representing the correct SHA
Expand All @@ -21,7 +23,9 @@ module.exports = function getCommitSHA(core, github) {
sha = ctx.sha;
}
if (!sha) {
throw new Error(`Could not determine SHA from GitHub context payload: ${JSON.stringify(ctx, null, 2)}`);
throw new Error(
`Could not determine SHA from GitHub context payload: ${JSON.stringify(ctx, null, 2)}`,
);

Check warning on line 28 in src/get-sha.js

View check run for this annotation

Codecov / codecov/patch

src/get-sha.js#L26-L28

Added lines #L26 - L28 were not covered by tests
}
core.info(`Using SHA: ${sha}`);
return sha;
Expand Down
6 changes: 4 additions & 2 deletions src/health-score.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@ module.exports = {
if (extensions.length === 0) {
core.error('Extensions not specified');
} else {
if (includes.length === 0) core.warning('Directories to be included not specified');
if (includes.length === 0)
core.warning('Directories to be included not specified');
com = module.exports.grep(core, extensions, includes, excludes); // to-do et al comments
}
return {
comments: com, coverageMisses: misses,
comments: com,
coverageMisses: misses,
};
},
grep: findProblematicComments,
Expand Down
9 changes: 7 additions & 2 deletions src/helpers/helper-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ module.exports = {
.map((item) => item.trim().replace(/^- */, ''))
.filter(Boolean)
.map((item) => {
if ((item.startsWith('"') && item.endsWith('"')) || (item.startsWith("'") && item.endsWith("'"))) {
if (
(item.startsWith('"') && item.endsWith('"')) ||
(item.startsWith("'") && item.endsWith("'"))
) {
return item.slice(1, -1);
}
return item;
Expand All @@ -32,7 +35,9 @@ module.exports = {
start_line: c.line_no ? c.line_no : 1,
end_line: c.line_no ? c.line_no : 1,
annotation_level: 'warning',
message: c.commentType ? (`Problematic comment ("${c.commentType}") identified`) : ('Problematic comment ("TODO", "HACK", "FIXME") identified'),
message: c.commentType
? `Problematic comment ("${c.commentType}") identified`
: 'Problematic comment ("TODO", "HACK", "FIXME") identified',
}));
},
};
14 changes: 8 additions & 6 deletions src/report.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,25 @@ const PROBLEMATIC_COMMENT_PENALTY = 100;
module.exports = async function reportStatus(startTime, core, github, score) {
const gh = core.getInput('github_token');
if (!gh) {
core.warning('No GitHub token found; will not report score on commit status.');
core.warning(
'No GitHub token found; will not report score on commit status.',
);
return 0;
}

core.info(JSON.stringify(score, null, 2));
// Calculate score
const points = (
(score.comments.length * PROBLEMATIC_COMMENT_PENALTY)
+ (score.coverageMisses * UNCOVERED_LINE_PENALTY)
) * -1;
const points =
(score.comments.length * PROBLEMATIC_COMMENT_PENALTY +
score.coverageMisses * UNCOVERED_LINE_PENALTY) *
-1;

// Report the thing
const ctx = github.context;
const octokit = github.getOctokit(gh);
let details = `# Score Breakdown
`;
if (score.comments && score.comments.length) {
if (score.comments?.length) {
details += `
## Problematic Comments
Expand Down
30 changes: 19 additions & 11 deletions src/score_components/coverage.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@ const getSHA = require('../get-sha');
module.exports = async function retrieveCodeCoverage(core, github) {
// See if we can get a coverage overview for this commit from codecov
const codecovToken = core.getInput('codecov_token');
const maxAttempts = parseInt(core.getInput('codecov_max_attempts'), 10) > 0 ? parseInt(core.getInput('codecov_max_attempts'), 10) : 10;
const retryDelay = parseInt(core.getInput('codecov_retry_delay'), 10) || 10000;
const treatTimeoutAsError = core.getInput('codecov_treat_timeout_as_error') === 'true';
const maxAttempts =
Number.parseInt(core.getInput('codecov_max_attempts'), 10) > 0
? Number.parseInt(core.getInput('codecov_max_attempts'), 10)
: 10;
const retryDelay =
Number.parseInt(core.getInput('codecov_retry_delay'), 10) || 10000;
const treatTimeoutAsError =
core.getInput('codecov_treat_timeout_as_error') === 'true';

let misses = 0;
let attempts = 1;
Expand All @@ -30,18 +35,21 @@ module.exports = async function retrieveCodeCoverage(core, github) {
repo_name: ctx.repo.repo,
commitid: sha,
});
core.debug(`codecov api response: ${JSON.stringify(coverage, null, 2)}`);
if (coverage && coverage.data) {
if (coverage.data.totals && coverage.data.totals.misses) {
core.debug(
`codecov api response: ${JSON.stringify(coverage, null, 2)}`,
);
if (coverage?.data) {
if (coverage.data.totals?.misses) {
misses = coverage.data.totals.misses;
core.info(`${misses} uncovered lines according to codecov`);
break;
} else {
core.info('codecov response data present but missing totals, delaying');
// if totals are missing, probably codecov has not compiled the coverage info yet; delay and try again.
attempts += 1;
await sleep(retryDelay);
}
core.info(
'codecov response data present but missing totals, delaying',
);
// if totals are missing, probably codecov has not compiled the coverage info yet; delay and try again.
attempts += 1;
await sleep(retryDelay);
} else {
core.info('codecov response data missing, delaying');
// if totals are missing, probably codecov has not compiled the coverage info yet; delay and try again.
Expand Down
54 changes: 35 additions & 19 deletions src/score_components/find-problematic-comments.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
const fs = require('fs');
const child_process = require('child_process');
const fs = require('node:fs');
const child_process = require('node:child_process');

const CommentType = Object.freeze({
TODO: 'TODO',
FIXME: 'FIXME',
HACK: 'HACK',
});

module.exports = function grepForProblematicComments(core, ext, include, exclude) {
module.exports = function grepForProblematicComments(
core,
ext,
include,
exclude,
) {
let find = 'find';
if (include && include.length) {
include.forEach((i) => {
if (include?.length) {
for (const i of include) {
find += ` ${i}`;
});
}
} else {
find += ' .';
}
Expand All @@ -21,22 +26,25 @@ module.exports = function grepForProblematicComments(core, ext, include, exclude
if (conditions) find += ` \\( ${conditions} \\) `;

let ignores = [];
if (exclude && exclude.length) {
if (exclude?.length) {
ignores = exclude;
} else if (fs.existsSync('.gitignore')) {
ignores = fs.readFileSync('.gitignore').toString().split('\n')
ignores = fs
.readFileSync('.gitignore')
.toString()
.split('\n')

Check warning on line 35 in src/score_components/find-problematic-comments.js

View check run for this annotation

Codecov / codecov/patch

src/score_components/find-problematic-comments.js#L32-L35

Added lines #L32 - L35 were not covered by tests
.filter(Boolean)
.map((entry) => entry.trim());
}
ignores.forEach((ex) => {
for (const ex of ignores) {
const isDirectory = ex.endsWith('/');
if (isDirectory) {
const dirPath = ex.slice(0, -1);
find += ` -not -path "*/${dirPath}/*" -not -path "*/${dirPath}"`;
} else {
find += ` -not -path "*/${ex}"`;
}
});
}
const commentPattern = `\\s*(//|/\\*|\\*).*\\b(${CommentType.TODO}|${CommentType.HACK}|${CommentType.FIXME})\\b`;

Check warning on line 48 in src/score_components/find-problematic-comments.js

View workflow job for this annotation

GitHub Actions / Health Score

src/score_components/find-problematic-comments.js#L48

Problematic comment ("TODO", "HACK", "FIXME") identified

// Modify the grep command to search within comments only
Expand All @@ -48,18 +56,26 @@ module.exports = function grepForProblematicComments(core, ext, include, exclude
core.error(e);
core.error('child_process execSync failed to execute');
}
const result = output.split('\n').filter(Boolean).map((line) => {
// example line output = "./src/report.js:47: // TODO: handle API call erroring out"
const [path, lineNo, ...data] = line.split(':');
const result = output
.split('\n')
.filter(Boolean)
.map((line) => {
// example line output = "./src/report.js:47: // TODO: handle API call erroring out"

Check warning on line 63 in src/score_components/find-problematic-comments.js

View workflow job for this annotation

GitHub Actions / Health Score

src/score_components/find-problematic-comments.js#L63

Problematic comment ("TODO", "HACK", "FIXME") identified
const [path, lineNo, ...data] = line.split(':');

const lineData = data.join(':');
const [_code, ...rawCommentData] = lineData.split('//');
const lineData = data.join(':');
const [_code, ...rawCommentData] = lineData.split('//');

const commentData = rawCommentData.join('//');
const commentType = getCommentType(commentData);
const commentData = rawCommentData.join('//');
const commentType = getCommentType(commentData);

return { path: path.trim(), line_no: parseInt(lineNo, 10), comment: `//${commentData}`.trim(), commentType };
});
return {
path: path.trim(),
line_no: Number.parseInt(lineNo, 10),
comment: `//${commentData}`.trim(),
commentType,
};
});
return result;
};

Expand Down
64 changes: 53 additions & 11 deletions test/health-score-test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
const { assert } = require('chai');
const sinon = require('sinon');
const { fakeCore, fakeGithub, fakeComments, fakeCoverage } = require('./stubs/stubs');
const {
fakeCore,
fakeGithub,
fakeComments,
fakeCoverage,
} = require('./stubs/stubs');
const hs = require('../src/health-score');

const contextValue = {
Expand Down Expand Up @@ -31,15 +36,21 @@ describe('health-score', () => {
fakeCore.getInput.withArgs('exclude').returns('test');
fakeGithub.context = contextValue;
await hs.compile(fakeCore, fakeGithub);
assert(fakeCore.warning.calledWith(sinon.match('Directories to be included not specified')));
assert(
fakeCore.warning.calledWith(
sinon.match('Directories to be included not specified'),
),
);
});
it('should check for invalid extensions', async () => {
fakeCore.getInput.withArgs('extension').returns('');
fakeCore.getInput.withArgs('include').returns('src');
fakeCore.getInput.withArgs('exclude').returns(null);
fakeGithub.context = contextValue;
await hs.compile(fakeCore, fakeGithub);
assert(fakeCore.error.calledWith(sinon.match('Extensions not specified')));
assert(
fakeCore.error.calledWith(sinon.match('Extensions not specified')),
);
});
});
it('should take single input', async () => {
Expand All @@ -66,21 +77,35 @@ describe('health-score', () => {

await hs.compile(fakeCore, fakeGithub);

assert(fakeComments.calledWith(fakeCore, ['js', 'ts'], ['src', 'lib'], ['test', 'dist']));
assert(
fakeComments.calledWith(
fakeCore,
['js', 'ts'],
['src', 'lib'],
['test', 'dist'],
),
);
assert(fakeCoverage.calledWith(fakeCore, fakeGithub));
});

it('should handle inputs in flow format', async () => {
fakeCore.getInput.withArgs('extension').returns('[\'js\', \'ts\']');
fakeCore.getInput.withArgs('include').returns('[\'src\', \'lib\']');
fakeCore.getInput.withArgs('exclude').returns('[\'test\', \'dist\']');
fakeCore.getInput.withArgs('extension').returns("['js', 'ts']");
fakeCore.getInput.withArgs('include').returns("['src', 'lib']");
fakeCore.getInput.withArgs('exclude').returns("['test', 'dist']");
fakeGithub.context = contextValue;
fakeComments.onCall().returns(['']);
fakeCoverage.onCall().returns(0);

await hs.compile(fakeCore, fakeGithub);

assert(fakeComments.calledWith(fakeCore, ['js', 'ts'], ['src', 'lib'], ['test', 'dist']));
assert(
fakeComments.calledWith(
fakeCore,
['js', 'ts'],
['src', 'lib'],
['test', 'dist'],
),
);
assert(fakeCoverage.calledWith(fakeCore, fakeGithub));
});
it('should handle combined and unformatted inputs', async () => {
Expand All @@ -93,7 +118,14 @@ describe('health-score', () => {

await hs.compile(fakeCore, fakeGithub);

assert(fakeComments.calledWith(fakeCore, ['js', 'ts'], ['src', 'lib'], ['test', 'dist']));
assert(
fakeComments.calledWith(
fakeCore,
['js', 'ts'],
['src', 'lib'],
['test', 'dist'],
),
);
assert(fakeCoverage.calledWith(fakeCore, fakeGithub));
});
});
Expand All @@ -108,14 +140,24 @@ describe('health-score', () => {
const startTime = new Date();
const points = await hs.report(startTime, fakeCore, fakeGithub, score);
assert(
fakeCore.warning.calledWith(sinon.match('No GitHub token found; will not report score on commit status.')),
fakeCore.warning.calledWith(
sinon.match(
'No GitHub token found; will not report score on commit status.',
),
),
);
assert.deepEqual(points, 0);
});
it('should calculate points accurately', async () => {
fakeCore.getInput.withArgs('github_token').returns('test');
fakeGithub.context = contextValue;
const score = { comments: [{ path: 'path', line_no: 10, comment: '// TODO: random stuff' }, { path: 'path2', line_no: 15, comment: '// FIXME: random stuff' }], coverageMisses: 5 };
const score = {
comments: [
{ path: 'path', line_no: 10, comment: '// TODO: random stuff' },
{ path: 'path2', line_no: 15, comment: '// FIXME: random stuff' },
],
coverageMisses: 5,
};
const startTime = new Date();
const points = await hs.report(startTime, fakeCore, fakeGithub, score);
assert.deepEqual(points, -205);
Expand Down
Loading

0 comments on commit ead05e0

Please sign in to comment.