Skip to content

Commit

Permalink
don't cache parser
Browse files Browse the repository at this point in the history
  • Loading branch information
souporserious committed Nov 18, 2024
1 parent 6fdd346 commit 46249c8
Showing 1 changed file with 24 additions and 10 deletions.
34 changes: 24 additions & 10 deletions packages/renoun/src/utils/format-source-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,12 @@ function loadPrettier() {
}>('prettier', () => import('prettier').then((module) => module.default))
}

let formatter: (sourceText: string, options?: Record<string, unknown>) => string
type Formatter = (
sourceText: string,
options: Record<string, unknown>
) => string

let formatter: Formatter | null | undefined

/** Formats the provided source text using the installed formatter. */
export async function formatSourceText(
Expand All @@ -74,29 +79,38 @@ export async function formatSourceText(
) {
// TODO: Add support for other formatters like dprint and biome

if (formatter === null) {
return sourceText
}

if (formatter === undefined) {
const prettier = await loadPrettier()

if (prettier) {
const config = (await prettier.resolveConfig(filePath)) || {}
const parser = getPrettierParser(filePath, language)

if (parser) {
config.parser = parser
} else {
config.filepath = filePath
}

if (config.printWidth === undefined) {
config.printWidth = 80
}

formatter = (sourceText: string) => prettier.format(sourceText, config)
formatter = (sourceText: string, options: Record<string, unknown>) => {
return prettier.format(sourceText, {
...config,
...options,
})
}
} else {
// No parser found for the provided language, use the default formatter.
formatter = null
}
}

if (formatter) {
return formatter(sourceText)
const parser = getPrettierParser(filePath, language)

if (parser) {
return formatter(sourceText, { parser })
}
}

return sourceText
Expand Down

0 comments on commit 46249c8

Please sign in to comment.