Skip to content

Commit

Permalink
Add the autofix engine
Browse files Browse the repository at this point in the history
  • Loading branch information
illright committed Jun 18, 2024
1 parent 08deddc commit b329a08
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/steiger/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { cosmiconfig } from 'cosmiconfig'

import { linter } from './app'
import { setConfig, schema as configSchema } from './models/config'
import { applyAutofixes } from './features/autofix'

const yargsProgram = yargs(hideBin(process.argv))
.scriptName('steiger')
Expand All @@ -21,6 +22,11 @@ const yargsProgram = yargs(hideBin(process.argv))
describe: 'watch filesystem changes',
type: 'boolean',
})
.option('fix', {
demandOption: false,
describe: 'apply auto-fixes',
type: 'boolean',
})
.string('_')
.check((argv) => {
const filePaths = argv._
Expand Down Expand Up @@ -58,11 +64,19 @@ if (consoleArgs.watch) {
const unsubscribe = diagnosticsChanged.watch((state) => {
console.clear()
reportPretty(state)
if (consoleArgs.fix) {
applyAutofixes(state)
}
})
prexit(() => {
stopWatching()
unsubscribe()
})
} else {
await linter.run(resolve(consoleArgs._[0])).then(reportPretty)
const diagnostics = await linter.run(resolve(consoleArgs._[0]))

reportPretty(diagnostics)
if (consoleArgs.fix) {
applyAutofixes(diagnostics)
}
}
27 changes: 27 additions & 0 deletions packages/steiger/src/features/autofix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { dirname, join } from 'node:path'
import { rename, open, mkdir, rm } from 'node:fs/promises'
import type { Diagnostic } from '@feature-sliced/steiger-plugin'

export async function applyAutofixes(diagnostics: Array<Diagnostic>) {
return Promise.all(
diagnostics
.flatMap((diagnostic) => diagnostic.fixes ?? [])
.map((fix) => {
switch (fix.type) {
case 'rename':
return rename(fix.path, join(dirname(fix.path), fix.newName))
case 'create-file':
return open(fix.path, 'w').then((file) => file.close())
case 'create-folder':
return mkdir(fix.path, { recursive: true })
case 'delete':
return rm(fix.path, { recursive: true })
case 'modify-file':
return open(fix.path, 'w').then(async (file) => {
await file.write(fix.content)
return file.close()
})
}
}),
)
}

0 comments on commit b329a08

Please sign in to comment.