Skip to content

Add badgesDirectory option, improved error handling, suppress coverage warnings #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ To customise your analysis, use the following options, placed in a `codehawk.jso

| Option | Description | Default |
|----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------|
| `badgesDirectory` | Directory where the two maintainbility badges will be created (when enabled) | `['/generated']` |
| `enableFlow` | Enable Flow support | `false` |
| `extensions` | File extensions that should be analyzed. The default is always used, but you can add more extensions. You can use the `exclude[...]` options to exclude specific files. | `['.js', '.jsx', '.ts', '.tsx']` |
| `excludeFilenames` | Filename matches that should be excluded from static analysis (but still show in the data). The default is always used, but you can add more matches to be excluded. Note that the matching is exact. The exclude list is taken into consideration after the extension list. | `['.d.ts', '.min.js', '.bundle.js']` |
Expand Down
8 changes: 4 additions & 4 deletions codehawk.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"skipDirectories": ["/generated", "/samples", "/test/__mocks__"],
"minimumThreshold": 40
}
{
"skipDirectories": ["/generated", "/samples", "/test/__mocks__"],
"minimumThreshold": 40
}
8 changes: 4 additions & 4 deletions generated/avg-maintainability.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 4 additions & 4 deletions generated/worst-maintainability.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"reflect": "node build/index.js src",
"test:coverage": "jest --coverage",
"test:watch": "jest --watch",
"test": "jest --testTimeout 15000"
"test": "jest --testTimeout 15000",
"verify": "yarn build && yarn test && yarn lint && yarn prettier && yarn reflect && yarn isclean"
},
"author": "Sam Brown (https://github.com/sgb-io)",
"repository": {
Expand Down
22 changes: 17 additions & 5 deletions src/badge.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { badgen } from 'badgen'
import fs from 'fs'
import type { ResultsSummary } from './codehawk'
import slash from 'slash'
import type { Results } from './codehawk'

const getBadgeColor = (percent: number): string => {
let color = 'e05d44' // 'red';
Expand All @@ -14,11 +15,22 @@ const getBadgeColor = (percent: number): string => {
return color
}

export const generateBadge = (resultsSummary: ResultsSummary): void => {
const { average, worst } = resultsSummary
export const generateBadge = (results: Results): void => {
const { average, worst } = results.summary
const { badgesDirectory } = results.options
const badgesPath = badgesDirectory[0] || '' // Fall back to root
const actualPath = slash(process.cwd()) + badgesPath

if (badgesPath !== '' && !fs.existsSync(actualPath)) {
// Fire a specific error message, but also let the upstream generic handling kick in
const err = `[codehawk-cli] The directory "${badgesPath}" does not exist, please create it in order to generate badges.`
console.error(err)
throw new Error(err)
}

try {
fs.writeFileSync(
'generated/avg-maintainability.svg',
`${actualPath}/avg-maintainability.svg`,
badgen({
label: 'maintainability (avg)',
status: `${average.toFixed(2)}`,
Expand All @@ -32,7 +44,7 @@ export const generateBadge = (resultsSummary: ResultsSummary): void => {

try {
fs.writeFileSync(
'generated/worst-maintainability.svg',
`${actualPath}/worst-maintainability.svg`,
badgen({
label: 'maintainability (worst)',
status: `${worst.toFixed(2)}`,
Expand Down
2 changes: 1 addition & 1 deletion src/codehawk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const outputMatchesResult = (projectPath: string): void => {

expect(output.fullResultsTree).toEqual(expected.fullResultsTree)

generateBadge(output.summary)
generateBadge(output)
expect('generateBadge did not throw').toBeTruthy()
}

Expand Down
2 changes: 2 additions & 0 deletions src/codehawk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export interface ResultsSummary {
}

export interface Results {
options: AssembledOptions
resultsList: FullyAnalyzedFile[]
fullResultsTree: FullyAnalyzedEntity[]
summary: ResultsSummary
Expand Down Expand Up @@ -145,6 +146,7 @@ const analyzeProject = (rawPath: string, isCliContext?: boolean): Results => {
}

return {
options,
summary,
resultsList: resultsAsList,
fullResultsTree: secondRunResults,
Expand Down
11 changes: 6 additions & 5 deletions src/coverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ export const getCoverage = (dirPath: string): CoverageMapping[] => {
coverage: coveredFiles[file],
}))
} catch (e) {
console.warn(`
Coverage not found, please generate it using instanbul/nyc.
We expect the json-summary format (coverage/coverage-summary.json).
If you don't have any tests, you can still continue.
`)
// For now, we choose to do nothing. See https://github.com/sgb-io/codehawk-cli/issues/58
// console.warn(`
// Coverage not found, please generate it using instanbul/nyc.
// We expect the json-summary format (coverage/coverage-summary.json).
// If you don't have any tests, you can still continue.
// `)
}

return coverage
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const run = (scanDir: string, createBadge: boolean): void => {

try {
console.log('[codehawk-cli] Generating maintainability badge...')
generateBadge(output.summary)
generateBadge(output)
console.log('[codehawk-cli] Badge was generated')
} catch (e) {
console.warn('[codehawk-cli] Badge was not generated')
Expand Down
17 changes: 14 additions & 3 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import { NO_CONFIGURATION_FOUND } from './consts/errors'
import type { CodehawkOptions, AllOptionKeys, AssembledOptions } from './types'

const baseOptions: CodehawkOptions = {
badgesDirectory: {
type: 'stringArray',
default: ['/generated'],
replaceDefault: true,
},
enableFlow: {
type: 'boolean',
default: false,
Expand Down Expand Up @@ -46,11 +51,14 @@ const injectOptionValues = ({
optionKey: AllOptionKeys
val: any
}): AssembledOptions => {
let err
const newOptions = { ...existingOptions }

switch (optionKey) {
case 'enableFlow':
newOptions[optionKey] = val as boolean
break
case 'badgesDirectory':
case 'excludeDirectories':
case 'excludeFilenames':
case 'skipDirectories':
Expand All @@ -61,9 +69,12 @@ const injectOptionValues = ({
newOptions[optionKey] = parseInt(val, 10)
break
default:
throw new Error(
`Unknown option "${optionKey as string}" is not supported`
)
// Print a friendly error but also allow the upstream generic handling to kick in
err = `[codehawk-cli] Unknown option "${
optionKey as string
}" is not supported`
console.warn(err)
throw new Error(err)
}

return newOptions
Expand Down
1 change: 1 addition & 0 deletions src/types/codehawk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ type SupportedStringArrayKeys =
| 'excludeDirectories'
| 'excludeFilenames'
| 'skipDirectories'
| 'badgesDirectory'
type SupportedBooleanOptions = 'enableFlow'
type SupportedNumberOptions = 'minimumThreshold'

Expand Down