Skip to content

Commit

Permalink
feat: implement outputs selection of code coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
zivaja committed Nov 24, 2023
1 parent 723894d commit 13c6618
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 45 deletions.
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ uses: EkoCommunications/[email protected]
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# To avoid reporting code coverage, set this variable to false
# code coverage will be reported, when this parameter or coverage-artifact-save is true
coverage-comment: false
```

Expand All @@ -79,6 +79,28 @@ with:
working-directory: "frontend"
```

### Saving code coverage results

For saving tests, supply a coverage-artifact-save
```yaml
uses: EkoCommunications/[email protected]
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# code coverage will be reported, when this parameter or coverage-comment is true
coverage-artifact-save: true
```

### Enabling multiple outputs support

For enabling multiple outputs/file types, supply multiple-outputs
```yaml
uses: EkoCommunications/[email protected]
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
multiple-outputs: false
```

See the [actions tab](https://github.com/EkoCommunications/jest-github-action/actions) for runs of this action! :stars:

6 changes: 3 additions & 3 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ inputs:
description: "Save code coverage to files"
required: false
default: "false"
coverage-results-file:
description: "Code coverage to file path"
output-type:
description: "Results output type (json, lcov, text, clover)"
required: false
default: "coverage-results.json"
default: "json"
changes-only:
description: "Only run tests on changed files (over base branch)"
required: false
Expand Down
2 changes: 1 addition & 1 deletion dist/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jest-github-action",
"version": "1.0.0",
"version": "1.2.0",
"description": "Jest action adding checks to your pull requests",
"main": "lib/run.js",
"scripts": {
Expand Down
88 changes: 49 additions & 39 deletions src/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { exec } from "@actions/exec"
import filter from "lodash/filter"
import flatMap from "lodash/flatMap"
import map from "lodash/map"
import { readFileSync, writeFileSync } from "fs"
import { readFileSync, mkdirSync } from "fs"
import strip from "strip-ansi"
import table from "markdown-table"

Expand All @@ -21,7 +21,8 @@ export async function run() {
let workingDirectory = core.getInput("working-directory", { required: false })
let cwd = workingDirectory ? resolve(workingDirectory) : process.cwd()
const CWD = cwd + sep
const RESULTS_FILE = join(CWD, "jest.results.json")
const outputType = core.getInput("output-type", { required: false })
const RESULTS_FILE = join(CWD, 'coverage',`coverage-final.json`)

try {
const token = process.env.GITHUB_TOKEN
Expand All @@ -33,44 +34,49 @@ export async function run() {

const cmd = getJestCommand(RESULTS_FILE)

await execJest(cmd, CWD)
// Run jest
const JestOutput = await execJest(cmd, CWD)

const lsCMDOutput = await exec("ls", ["-lR"], { silent: false, cwd: join(CWD, 'coverage') })
console.debug("List files in ./coverage: %j", lsCMDOutput)

// octokit
const octokit = new GitHub(token)

// Parse results
const results = parseResults(RESULTS_FILE)

// Write results to file
if(shouldSummitCoveragetoArtifact()){
const resultsFile = core.getInput("coverage-results-file", { required: false })
if (resultsFile) {
const resultsFilePath = join(CWD, resultsFile)
console.debug("Writing results to file: %s", resultsFilePath)
writeFileSync(resultsFilePath, JSON.stringify(results))
}
}

// Checks
const checkPayload = getCheckPayload(results, CWD)
await octokit.checks.create(checkPayload)

// Coverage comments
if (getPullId() && shouldCommentCoverage()) {
const comment = getCoverageTable(results, CWD)
if (comment) {
try {
await deletePreviousComments(octokit)
} catch (error) {
console.warn("Fail to remove some comment. skip to next stage.", error);

if(outputType == 'json'){
// Parse results
const results = parseResults(RESULTS_FILE)

// Checks
const checkPayload = getCheckPayload(results, CWD)
await octokit.checks.create(checkPayload)

// Coverage comments
if (getPullId() && shouldCommentCoverage()) {
const comment = getCoverageTable(results, CWD)
if (comment) {
try {
await deletePreviousComments(octokit)
} catch (error) {
console.warn("Fail to remove some comment. skip to next stage.", error);
}
const commentPayload = getCommentPayload(comment)
await octokit.issues.createComment(commentPayload)
}
const commentPayload = getCommentPayload(comment)
await octokit.issues.createComment(commentPayload)
}
}

if (!results.success) {
core.setFailed("Some jest tests failed.")
if (!results.success) {
core.setFailed("Some jest tests failed.")
}
} else if(outputType == 'lcov'){
console.debug("lcov output")
} else if (outputType == 'clover'){
console.debug("clover output")
} else if(outputType == 'text'){
console.debug("text output")
console.debug("Jest output: %j", JestOutput)
} else{
core.setFailed("Invalid output type.")
}
} catch (error) {
console.error(error)
Expand Down Expand Up @@ -102,7 +108,7 @@ function shouldRunOnlyChangedFiles(): boolean {
return Boolean(JSON.parse(core.getInput("changes-only", { required: false })))
}

function shouldSummitCoveragetoArtifact(): boolean {
function shouldWriteCoverageArtifact(): boolean {
return Boolean(JSON.parse(core.getInput("coverage-artifact-save", { required: false })))
}

Expand Down Expand Up @@ -169,13 +175,16 @@ function getCheckPayload(results: FormattedTestResults, cwd: string) {

function getJestCommand(resultsFile: string) {
let cmd = core.getInput("test-command", { required: false })
const jestOptions = `--testLocationInResults --json ${
shouldCommentCoverage() || shouldSummitCoveragetoArtifact() ? "--coverage" : ""
let outputType = core.getInput("output-type", { required: false })
const jestOptions = `${outputType=='json'?'--testLocationInResults --json '
:'--coverageReporters="'+outputType+'" '
} ${
shouldCommentCoverage() || shouldWriteCoverageArtifact() ? "--coverage" : ""
} ${
shouldRunOnlyChangedFiles() && context.payload.pull_request?.base.ref
? "--changedSince=" + context.payload.pull_request?.base.ref
: ""
} --outputFile=${resultsFile}`
} ${outputType == 'json'?"--outputFile=" + resultsFile:""}`
const shouldAddHyphen =
cmd.startsWith("npm") ||
cmd.startsWith("npx") ||
Expand All @@ -194,8 +203,9 @@ function parseResults(resultsFile: string): FormattedTestResults {

async function execJest(cmd: string, cwd?: string) {
try {
await exec(cmd, [], { silent: true, cwd })
const output = await exec(cmd, [], { silent: true, cwd })
console.debug("Jest command executed")
return output
} catch (e) {
console.error("Jest execution failed. Tests have likely failed.", e)
}
Expand Down

0 comments on commit 13c6618

Please sign in to comment.