Skip to content

Commit

Permalink
Use @actions/github
Browse files Browse the repository at this point in the history
  • Loading branch information
ataylorme committed Feb 22, 2024
1 parent 24edfa0 commit 4e64470
Show file tree
Hide file tree
Showing 11 changed files with 52,876 additions and 19,190 deletions.
70,474 changes: 52,641 additions & 17,833 deletions dist/index.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const config: Config = {
},
transformIgnorePatterns: ['^.+\\.js$'],
verbose: true,
setupFilesAfterEnv: ['./jest.setup.ts'],
}

export default config
12 changes: 12 additions & 0 deletions jest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
let originalEnv: NodeJS.ProcessEnv

beforeAll(() => {
// Store the original environment
originalEnv = {...process.env}
})

// beforeEach(() => {})

afterAll(() => {
process.env = originalEnv
})
1,460 changes: 157 additions & 1,303 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"build": "ncc build src/index.ts",
"prestart": "npm run build",
"start": "node dist/index.js",
"test": "jest",
"test": "GITHUB_ACTION=1 INPUT_GITHUB_TOKEN='secret123' jest",
"lint": "eslint --ext .ts src",
"lint:fix": "eslint --fix --ext .ts src",
"lint:report": "eslint --ext .ts --output-file eslint_report.json --format json src"
Expand All @@ -18,20 +18,21 @@
"url": "git+https://github.com/ataylorme/eslint-annotate-action.git"
},
"keywords": [],
"author": "Andrew Taylor <[email protected]>",
"author": "Andrew Taylor <[email protected]>",
"bugs": {
"url": "https://github.com/ataylorme/eslint-annotate-action/issues"
},
"homepage": "https://github.com/ataylorme/eslint-annotate-action#readme",
"dependencies": {
"@actions/core": "^1.10.0",
"@actions/github": "^6.0.0",
"@actions/glob": "^0.4.0",
"@octokit/action": "^6.0.7",
"actions-toolkit": "^6.0.1",
"dotenv": "^16.0.3"
},
"devDependencies": {
"@octokit/webhooks-definitions": "^3.67.0",
"@types/eslint": "^8.56.2",
"@types/jest": "^29.5.0",
"@types/node": "^18.15.5",
"@typescript-eslint/eslint-plugin": "^5.56.0",
Expand Down
8 changes: 4 additions & 4 deletions src/addAnnotationsToStatusCheck.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import updateStatusCheck from './updateStatusCheck'
import type {ChecksUpdateParamsOutputAnnotations, createCheckRunResponseDataType} from './types'
import constants from './constants'
const {OWNER, REPO, toolkit: tools, checkName} = constants
const {OWNER, REPO, core, checkName} = constants

/**
* Add annotations to an existing GitHub check run
Expand All @@ -28,7 +28,7 @@ export default async function addAnnotationsToStatusCheck(
const checkUpdatePromises = []
for (let batch = 1; batch <= numBatches; batch++) {
const batchMessage = `Found ${numberOfAnnotations} ESLint errors and warnings, processing batch ${batch} of ${numBatches}...`
tools.log.info(batchMessage)
core.info(batchMessage)
const annotationBatch = annotations.splice(0, batchSize)
try {
const currentCheckPromise = updateStatusCheck({
Expand All @@ -54,9 +54,9 @@ export default async function addAnnotationsToStatusCheck(
const errorMessage = `Error adding anotations to the GitHub status check with ID: ${checkId}`
// err only has an error message if it is an instance of Error
if (err instanceof Error) {
tools.exit.failure(err.message ? err.message : errorMessage)
core.setFailed(err.message ? err.message : errorMessage)
} else {
tools.exit.failure(errorMessage)
core.setFailed(errorMessage)
}
}
}
Expand Down
74 changes: 40 additions & 34 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,26 @@
import * as core from '@actions/core'
import {config as dotEnvConfig} from 'dotenv'
dotEnvConfig()
import {Octokit} from '@octokit/rest'
import {Toolkit} from 'actions-toolkit'
import {context} from '@actions/github'
import {Octokit} from '@octokit/action'
import type {pullRequestWebhook} from './types'
import type {OctokitOptions} from '@octokit/core'

export const cwd = process.cwd()

const areTesting = process.env.NODE_ENV === 'test'

const isGitHubActions = process.env.GITHUB_ACTIONS

const githubToken =
isGitHubActions && !areTesting ? core.getInput('repo-token', {required: true}) : process.env.GITHUB_TOKEN

const octokit = new Octokit({
previews: ['antiope'],
auth: githubToken,
})

const tools = new Toolkit({
token: githubToken,
})
const octokitParams: OctokitOptions = areTesting ? {authStrategy: undefined} : {}
const octokit = new Octokit(octokitParams)

// If this is a pull request, store the context
// Otherwise, set to false
const isPullRequest = Object.prototype.hasOwnProperty.call(tools.context.payload, 'pull_request')
const pullRequest: pullRequestWebhook | false = isPullRequest ? tools.context.payload.pull_request : false
const isPullRequest = Object.prototype.hasOwnProperty.call(context.payload, 'pull_request')
const pullRequest: pullRequestWebhook | false = isPullRequest ? context.payload.pull_request : false

let sha = tools.context.sha
let sha = context.sha

if (isPullRequest) {
sha = pullRequest.head.sha
Expand All @@ -38,39 +30,53 @@ if (areTesting) {
sha = '8e80ec28fec6ef9763aacbabb452bcb5d92315ca'
}

const onlyChangedFiles = core.getInput('only-pr-files') || 'true'
const failOnWarningInput = core.getInput('fail-on-warning') || 'false'
const failOnErrorInput = core.getInput('fail-on-error') || 'true'
const markdownReportOnStepSummaryInput = core.getInput('markdown-report-on-step-summary') || 'false'
const checkName = core.getInput('check-name') || 'ESLint Report Analysis'
const failOnWarning = failOnWarningInput === 'true'
const failOnError = failOnErrorInput === 'true'
const markdownReportOnStepSummary = markdownReportOnStepSummaryInput === 'true'
function getBooleanInput(inputName: string, defaultValue: string): boolean {
const inputValue = core.getInput(inputName) || defaultValue
return inputValue === 'true'
}

function getInputs() {
const onlyChangedFiles = getBooleanInput('only-pr-files', 'true')
const failOnWarning = getBooleanInput('fail-on-warning', 'false')
const failOnError = getBooleanInput('fail-on-error', 'true')
const markdownReportOnStepSummary = getBooleanInput('markdown-report-on-step-summary', 'false')
const checkName = core.getInput('check-name') || 'ESLint Report Analysis'
const reportFile = areTesting
? 'src/__tests__/eslintReport-3-errors.json'
: core.getInput('report-json', {required: true})

return {
onlyChangedFiles,
failOnWarning,
failOnError,
markdownReportOnStepSummary,
checkName,
reportFile,
}
}

const {onlyChangedFiles, failOnWarning, failOnError, markdownReportOnStepSummary, checkName, reportFile} = getInputs()

// https://github.com/eslint/eslint/blob/a59a4e6e9217b3cc503c0a702b9e3b02b20b980d/lib/linter/apply-disable-directives.js#L253
const unusedDirectiveMessagePrefix = 'Unused eslint-disable directive'

const reportFile = areTesting
? 'src/__tests__/eslintReport-3-errors.json'
: core.getInput('report-json', {required: true})

const getTimestamp = (): string => {
return new Date().toISOString()
}

export default {
token: githubToken,
core,
octokit,
cwd,
toolkit: tools,
context,
pullRequest,
GITHUB_WORKSPACE: process.env.GITHUB_WORKSPACE as string,
SHA: sha,
CONTEXT: tools.context,
OWNER: areTesting ? 'ataylorme' : tools.context.repo.owner,
REPO: areTesting ? 'eslint-annotate-github-action' : tools.context.repo.repo,
CONTEXT: context,
OWNER: areTesting ? 'ataylorme' : context.repo.owner,
REPO: areTesting ? 'eslint-annotate-github-action' : context.repo.repo,
checkName,
onlyChangedFiles: isPullRequest && onlyChangedFiles === 'true',
onlyChangedFiles: isPullRequest && onlyChangedFiles,
reportFile,
isPullRequest,
isGitHubActions,
Expand Down
4 changes: 2 additions & 2 deletions src/getAnalyzedReport.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type {ESLintReport, ChecksUpdateParamsOutputAnnotations, AnalyzedESLintReport} from './types'
import constants from './constants'
const {toolkit, GITHUB_WORKSPACE, OWNER, REPO, SHA, failOnWarning, unusedDirectiveMessagePrefix} = constants
const {core, GITHUB_WORKSPACE, OWNER, REPO, SHA, failOnWarning, unusedDirectiveMessagePrefix} = constants

/**
* Analyzes an ESLint report JS object and returns a report
Expand All @@ -26,7 +26,7 @@ export default function getAnalyzedReport(files: ESLintReport): AnalyzedESLintRe
// Get the file path and any warning/error messages
const {filePath, messages} = file

toolkit.log.info(`Analyzing ${filePath}`)
core.info(`Analyzing ${filePath}`)

// Skip files with no error or warning messages
if (!messages.length) {
Expand Down
3 changes: 1 addition & 2 deletions src/getPullRequestFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ export default async function getPullRequestFiles(options: prFilesParametersType
'GET /repos/:owner/:repo/pulls/:pull_number/files',
options,
)
const prFilesNames = prFiles.map((prFiles: prFilesResponseType['data']) => prFiles.filename)
return Promise.resolve(prFilesNames)
return prFiles.map((prFiles: prFilesResponseType['data']) => prFiles.filename)
} catch (error) {
return Promise.reject(error)
}
Expand Down
20 changes: 11 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import {Toolkit} from 'actions-toolkit'
import * as core from '@actions/core'
import eslintJsonReportToJs from './eslintJsonReportToJs'
import getAnalyzedReport from './getAnalyzedReport'
Expand All @@ -10,16 +9,16 @@ import addSummary from './addSummary'
import constants from './constants'
const {reportFile, onlyChangedFiles, failOnError, failOnWarning, markdownReportOnStepSummary} = constants

Toolkit.run(async (tools) => {
tools.log.info(`Starting analysis of the ESLint report ${reportFile.replace(/\n/g, ', ')}. Standby...`)
async function run(): Promise<void> {
core.info(`Starting analysis of the ESLint report ${reportFile.replace(/\n/g, ', ')}. Standby...`)
const reportJS = await eslintJsonReportToJs(reportFile)
const analyzedReport = onlyChangedFiles
? await getPullRequestChangedAnalyzedReport(reportJS)
: getAnalyzedReport(reportJS)
const annotations = analyzedReport.annotations
const conclusion = analyzedReport.success ? 'success' : 'failure'

tools.log.info(analyzedReport.summary)
core.info(analyzedReport.summary)

core.setOutput('summary', analyzedReport.summary)
core.setOutput('errorCount', analyzedReport.errorCount)
Expand Down Expand Up @@ -47,18 +46,21 @@ Toolkit.run(async (tools) => {

// Fail the Action if the report analysis conclusions is failure
if ((failOnWarning || failOnError) && conclusion === 'failure') {
tools.exit.failure(`${analyzedReport.errorCount} errors and ${analyzedReport.warningCount} warnings`)
core.setFailed(`${analyzedReport.errorCount} errors and ${analyzedReport.warningCount} warnings`)
process.exit(1)
}
} catch (err) {
const errorMessage = 'Error creating a status check for the ESLint analysis.'
// err only has an error message if it is an instance of Error
if (err instanceof Error) {
tools.exit.failure(err.message ? err.message : errorMessage)
core.setFailed(err.message ? err.message : errorMessage)
} else {
tools.exit.failure(errorMessage)
core.setFailed(errorMessage)
}
}
// If we got this far things were a success
tools.exit.success('ESLint report analysis complete. No errors found!')
})
core.info('ESLint report analysis complete. No errors found!')
process.exit(0)
}

run()
3 changes: 3 additions & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import {ESLint as ESLintType} from '@types/eslint'
export type eslintResultType = ESLintType.LintResult

// https://www.npmjs.com/package/@octokit/types
import {Endpoints, GetResponseDataTypeFromEndpointMethod} from '@octokit/types'
import {Webhooks} from '@octokit/webhooks-definitions'
Expand Down

0 comments on commit 4e64470

Please sign in to comment.