Skip to content

Commit

Permalink
Improved naming of TypeScript types 📛
Browse files Browse the repository at this point in the history
  • Loading branch information
01taylop committed Jul 16, 2024
1 parent 7d909b4 commit 6672ddb
Show file tree
Hide file tree
Showing 12 changed files with 134 additions and 133 deletions.
4 changes: 1 addition & 3 deletions jest-config/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@ expect.extend({
isCalledWithExpected = expected.every((arg, index) => this.equals(received.mock.calls[0][index], arg))
}

const pass = isCalledOnce && isCalledWithExpected

return {
message: () => `expected ${received.getMockName()} to have been called exactly once with "${expected}" but received "${received.mock.calls[0]}"`,
pass,
pass: isCalledOnce && isCalledWithExpected,
}
},
})
26 changes: 14 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import chalk from 'chalk'
import { Command } from 'commander'
import { spaceLog } from 'space-log'

import { Events, Linter, type LinterResult, type RunLinter, type RunLintPilot } from '@Types'
import { Events, Linter } from '@Types'
import colourLog from '@Utils/colourLog'
import { notifyResults } from '@Utils/notifier'
import { clearTerminal } from '@Utils/terminal'

import type { LintReport, RunLinter, RunLintPilot } from '@Types'

import linters from './linters/index'
import sourceFiles from './sourceFiles'
import { fileChangeEvent, watchFiles } from './watchFiles'
Expand All @@ -31,11 +33,11 @@ const runLinter = async ({ filePattern, linter }: RunLinter) => {
linter,
})

const result: LinterResult = await linters[linter].lintFiles(files)
const report: LintReport = await linters[linter].lintFiles(files)

colourLog.result(result.summary, startTime)
colourLog.result(report.summary, startTime)

return result
return report
}

const runLintPilot = ({ title, watch }: RunLintPilot) => {
Expand All @@ -52,29 +54,29 @@ const runLintPilot = ({ title, watch }: RunLintPilot) => {
filePattern: '**/*.{css,scss,less,sass,styl,stylus}',
linter: Linter.Stylelint,
}),
]).then((results) => {
results.forEach(({ logs, summary }) => {
if (Object.keys(logs).length === 0) {
]).then((reports) => {
reports.forEach(({ results, summary }) => {
if (Object.keys(results).length === 0) {
return
}

colourLog.info(`\nLogging ${summary.linter.toLowerCase()} results:`)

Object.entries(logs).forEach(([file, log]) => {
Object.entries(results).forEach(([file, formattedResults]) => {
console.log()
console.log(chalk.underline(`${process.cwd()}/${file}`))
spaceLog({
columnKeys: ['type', 'position', 'message', 'rule'],
columnKeys: ['severity', 'position', 'message', 'rule'],
spaceSize: 2,
}, log)
}, formattedResults)
})
})

results.forEach(({ summary }) => {
reports.forEach(({ summary }) => {
colourLog.resultBlock(summary)
})

const exitCode = notifyResults(results, title)
const exitCode = notifyResults(reports, title)

if (watch) {
colourLog.info('Watching for changes...')
Expand Down
20 changes: 10 additions & 10 deletions src/linters/eslint.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ESLint } from 'eslint'

import { Linter, type LinterResult, type ResultSummary } from '@Types'
import { Linter, type LintReport, type ReportSummary } from '@Types'

const lintFiles = async (files: Array<string>): Promise<LinterResult> => {
const lintFiles = async (files: Array<string>): Promise<LintReport> => {
try {
const eslint = new ESLint({
// @ts-expect-error
Expand All @@ -19,7 +19,7 @@ const lintFiles = async (files: Array<string>): Promise<LinterResult> => {

const results = await eslint.lintFiles(files)

const summary: ResultSummary = {
const reportSummary: ReportSummary = {
deprecatedRules: [],
errorCount: 0,
fileCount: results.length,
Expand All @@ -30,16 +30,16 @@ const lintFiles = async (files: Array<string>): Promise<LinterResult> => {
}

results.forEach(({ errorCount, fixableErrorCount, fixableWarningCount, usedDeprecatedRules, warningCount }) => {
summary.deprecatedRules = [...new Set([...summary.deprecatedRules, ...usedDeprecatedRules.map(({ ruleId }) => ruleId)])]
summary.errorCount += errorCount
summary.fixableErrorCount += fixableErrorCount
summary.fixableWarningCount += fixableWarningCount
summary.warningCount += warningCount
reportSummary.deprecatedRules = [...new Set([...reportSummary.deprecatedRules, ...usedDeprecatedRules.map(({ ruleId }) => ruleId)])]
reportSummary.errorCount += errorCount
reportSummary.fixableErrorCount += fixableErrorCount
reportSummary.fixableWarningCount += fixableWarningCount
reportSummary.warningCount += warningCount
})

return {
logs: {},
summary,
results: {},
summary: reportSummary,
}
} catch (error: any) {
console.error(error.stack)
Expand Down
4 changes: 2 additions & 2 deletions src/linters/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import eslint from './eslint'
import stylelint from './stylelint'
import markdownlint from './markdownlint'

import { Linter, type LinterResult } from '@Types'
import { Linter, type LintReport } from '@Types'

type Linters = {
[key in Linter]: {
lintFiles: (files: Array<string>) => Promise<LinterResult>
lintFiles: (files: Array<string>) => Promise<LintReport>
}
}

Expand Down
49 changes: 25 additions & 24 deletions src/linters/markdownlint/__tests__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,15 @@ describe('markdownlint', () => {
expect(colourLog.error).toHaveBeenCalledOnceWith('An error occurred while running markdownlint: no results')
})

it('resolves with logs and a summary when markdownlint successfully lints (no errors)', async () => {
it('resolves with results and a summary when markdownlint successfully lints (no errors)', async () => {
jest.mocked(markdownlint).mockImplementationOnce((_options, callback) => {
callback(null, {
'README.md': []
})
})

expect(await markdownLib.lintFiles(testFiles)).toStrictEqual({
logs: {},
results: {},
summary: {
deprecatedRules: [],
errorCount: 0,
Expand Down Expand Up @@ -111,6 +111,7 @@ describe('markdownlint', () => {
'README.md': [{
...commonError,
lineNumber: 7,
errorRange: [],
fixInfo: {
lineNumber: 7,
},
Expand All @@ -135,48 +136,48 @@ describe('markdownlint', () => {
})

expect(await markdownLib.lintFiles(testFiles)).toStrictEqual({
logs: {
results: {
'CHANGELOG.md': [{
message: ' test-rule-description: test-error-detail ',
message: 'test-rule-description: test-error-detail',
messageTheme: expect.any(Function),
position: ' 1:1 ',
position: '1:1',
positionTheme: expect.any(Function),
rule: ' test-rule',
rule: 'test-rule',
ruleTheme: expect.any(Function),
type: 'X ',
severity: 'X',
}],
'README.md': [{
message: ' test-rule-description: test-error-detail ',
message: 'test-rule-description: test-error-detail',
messageTheme: expect.any(Function),
position: ' 7:1 ',
position: '7',
positionTheme: expect.any(Function),
rule: ' test-rule',
rule: 'test-rule',
ruleTheme: expect.any(Function),
type: 'X ',
severity: 'X',
}, {
message: ' test-rule-description: test-error-detail ',
message: 'test-rule-description: test-error-detail',
messageTheme: expect.any(Function),
position: ' 13:1 ',
position: '13:1',
positionTheme: expect.any(Function),
rule: ' test-rule-a',
rule: 'test-rule-a',
ruleTheme: expect.any(Function),
type: 'X ',
severity: 'X',
}, {
message: ' test-rule-description: test-error-detail ',
message: 'test-rule-description: test-error-detail',
messageTheme: expect.any(Function),
position: ' 13:1 ',
position: '13:1',
positionTheme: expect.any(Function),
rule: ' test-rule-b',
rule: 'test-rule-b',
ruleTheme: expect.any(Function),
type: 'X ',
severity: 'X',
}, {
message: ' test-rule-description ',
message: 'test-rule-description',
messageTheme: expect.any(Function),
position: ' 18:1 ',
position: '18:1',
positionTheme: expect.any(Function),
rule: ' test-rule',
rule: 'test-rule',
ruleTheme: expect.any(Function),
type: 'X ',
severity: 'X',
}],
},
summary: expect.any(Object),
Expand All @@ -189,7 +190,7 @@ describe('markdownlint', () => {
})

expect(await markdownLib.lintFiles(testFiles)).toStrictEqual({
logs: expect.any(Object),
results: expect.any(Object),
summary: {
deprecatedRules: [],
errorCount: 5,
Expand Down
26 changes: 13 additions & 13 deletions src/linters/markdownlint/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import markdownlint, { type LintResults } from 'markdownlint'

import { Linter, LogType } from '@Types'
import { Linter, RuleSeverity } from '@Types'
import colourLog from '@Utils/colourLog'
import { formatFileLog } from '@Utils/transform'
import { formatResult } from '@Utils/transform'

import type { LinterResult, ResultLogs, ResultSummary } from '@Types'
import type { LintReport, ReportResults, ReportSummary } from '@Types'

import loadConfig from './loadConfig'

const lintFiles = (files: Array<string>): Promise<LinterResult> => new Promise((resolve, reject) => {
const lintFiles = (files: Array<string>): Promise<LintReport> => new Promise((resolve, reject) => {
const [configName, config] = loadConfig()

colourLog.configDebug(`Using ${configName} markdownlint config:`, config)
Expand All @@ -27,9 +27,9 @@ const lintFiles = (files: Array<string>): Promise<LinterResult> => new Promise((
return reject(new Error('No results'))
}

const logs: ResultLogs = {}
const reportResults: ReportResults = {}

const summary: ResultSummary = {
const reportSummary: ReportSummary = {
deprecatedRules: [],
errorCount: 0,
fileCount: Object.keys(results).length,
Expand All @@ -44,30 +44,30 @@ const lintFiles = (files: Array<string>): Promise<LinterResult> => new Promise((
return
}

logs[file] = []
reportResults[file] = []

summary.errorCount += errors.length
reportSummary.errorCount += errors.length

errors
.sort((a, b) => a.lineNumber - b.lineNumber || a.ruleNames[1].localeCompare(b.ruleNames[1]))
.forEach(({ errorDetail, errorRange, fixInfo, lineNumber, ruleDescription, ruleNames }) => {
logs[file].push(formatFileLog({
reportResults[file].push(formatResult({
column: errorRange?.length ? errorRange[0] : undefined,
lineNumber,
message: errorDetail?.length ? `${ruleDescription}: ${errorDetail}` : ruleDescription,
rule: ruleNames[1],
type: LogType.ERROR,
severity: RuleSeverity.ERROR,
}))

if (fixInfo) {
summary.fixableErrorCount += 1
reportSummary.fixableErrorCount += 1
}
})
})

resolve({
logs,
summary,
results: reportResults,
summary: reportSummary,
})
})
})
Expand Down
16 changes: 8 additions & 8 deletions src/linters/stylelint.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import stylelint from 'stylelint'

import { Linter, type LinterResult, type ResultSummary } from '@Types'
import { Linter, type LintReport, type ReportSummary } from '@Types'

const lintFiles = async (files: Array<string>): Promise<LinterResult> => {
const lintFiles = async (files: Array<string>): Promise<LintReport> => {
try {
const { results, ruleMetadata } = await stylelint.lint({
allowEmptyInput: true,
Expand All @@ -14,7 +14,7 @@ const lintFiles = async (files: Array<string>): Promise<LinterResult> => {
files,
})

const summary: ResultSummary = {
const reportSummary: ReportSummary = {
deprecatedRules: [],
errorCount: 0,
fileCount: results.length,
Expand All @@ -25,19 +25,19 @@ const lintFiles = async (files: Array<string>): Promise<LinterResult> => {
}

results.forEach(({ deprecations, warnings }) => {
summary.deprecatedRules = [...new Set([...summary.deprecatedRules, ...deprecations.map(({ text }) => text)])]
summary.errorCount += warnings.length
reportSummary.deprecatedRules = [...new Set([...reportSummary.deprecatedRules, ...deprecations.map(({ text }) => text)])]
reportSummary.errorCount += warnings.length

warnings.forEach(({ rule }) => {
if (ruleMetadata[rule]?.fixable) {
summary.fixableErrorCount += 1
reportSummary.fixableErrorCount += 1
}
})
})

return {
logs: {},
summary,
results: {},
summary: reportSummary,
}
} catch (error: any) {
console.error(error.stack)
Expand Down
Loading

0 comments on commit 6672ddb

Please sign in to comment.