Skip to content

Commit

Permalink
fix collection imports formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
souporserious committed Oct 14, 2024
1 parent 10c7cf7 commit cab837b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/many-rivers-kiss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'renoun': patch
---

Fixes issue with trying to format dynamic imports added to collections from CLI causing issues with linters. Now, formatting will only occur if the workspace has access to `prettier`.
23 changes: 15 additions & 8 deletions packages/renoun/src/collections/write-collection-imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import type {
ObjectLiteralExpression,
ArrowFunction,
StringLiteral,
SourceFile,
} from 'ts-morph'
import tsMorph from 'ts-morph'

import { formatSourceText } from '../utils/format-source-text.js'
import {
resolveObjectLiteralExpression,
isLiteralExpressionValue,
Expand Down Expand Up @@ -63,6 +65,7 @@ export async function writeCollectionImports(filename?: string) {
}
})

const sourceFilesToFormat = new Set<SourceFile>()
const collections = (
await Promise.all(
collectionExpressions.map(async (callExpression) => {
Expand Down Expand Up @@ -108,14 +111,7 @@ export async function writeCollectionImports(filename?: string) {

callExpression.addArgument(parsedDynamicImportString)

// Format arguments with new lines so they are close to what the user's formatting is
callExpression.getArguments().forEach((arg, index) => {
const endNewLine = index === 0 ? '' : '\n'
arg.replaceWithText('\n' + arg.getText() + endNewLine)
arg.formatText()
})

callExpression.formatText()
sourceFilesToFormat.add(callExpression.getSourceFile())
})
)
).filter((collection) => collection !== null)
Expand All @@ -124,6 +120,17 @@ export async function writeCollectionImports(filename?: string) {
return
}

/* Format all source files with updated collection imports. */
await Promise.all(
Array.from(sourceFilesToFormat).map(async (sourceFile) => {
const formattedSourceText = await formatSourceText(
sourceFile.getFilePath(),
sourceFile.getText()
)
sourceFile.replaceWithText(formattedSourceText)
})
)

return project.save()
}

Expand Down

0 comments on commit cab837b

Please sign in to comment.