Skip to content

Commit

Permalink
work on linting
Browse files Browse the repository at this point in the history
  • Loading branch information
jtoar committed Mar 8, 2024
1 parent 2c2abef commit bfb632d
Show file tree
Hide file tree
Showing 13 changed files with 126 additions and 99 deletions.
126 changes: 63 additions & 63 deletions packages/cli-helpers/src/auth/authFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,76 +24,76 @@ interface FilesArgs {
* }
* ```
*/
export const apiSideFiles = ({ basedir, webAuthn }: FilesArgs) => {
export const apiSideFiles = async ({ basedir, webAuthn }: FilesArgs) => {
const apiSrcPath = getPaths().api.src
const apiBaseTemplatePath = path.join(basedir, 'templates', 'api')
const templateDirectories = fs.readdirSync(apiBaseTemplatePath)

const filesRecord = templateDirectories.reduce<Record<string, string>>(
(acc, dir) => {
const templateFiles = fs.readdirSync(path.join(apiBaseTemplatePath, dir))
const filePaths = templateFiles
.filter((fileName) => {
const fileNameParts = fileName.split('.')
// Remove all webAuthn files. We'll handle those in the next step
return (
fileNameParts.length <= 3 || fileNameParts.at(-3) !== 'webAuthn'
)
})
.map((fileName) => {
// remove "template" from the end, and change from {ts,tsx} to {js,jsx} for
// JavaScript projects
let outputFileName = fileName.replace(/\.template$/, '')
if (!isTypeScriptProject()) {
outputFileName = outputFileName.replace(/\.ts(x?)$/, '.js$1')
}

if (!webAuthn) {
return { templateFileName: fileName, outputFileName }
}

// Insert "webAuthn." before the second to last part
const webAuthnFileName = fileName
.split('.')
.reverse()
.map((part, i) => (i === 1 ? 'webAuthn.' + part : part))
.reverse()
.join('.')

// Favor the abc.xyz.webAuthn.ts.template file if it exists, otherwise
// just go with the "normal" filename
if (templateFiles.includes(webAuthnFileName)) {
return { templateFileName: webAuthnFileName, outputFileName }
} else {
return { templateFileName: fileName, outputFileName }
}
})
.map((f) => {
const templateFilePath = path.join(
apiBaseTemplatePath,
dir,
f.templateFileName
)
const outputFilePath = path.join(apiSrcPath, dir, f.outputFileName)

return { templateFilePath, outputFilePath }
})

filePaths.forEach((paths) => {
const content = fs.readFileSync(paths.templateFilePath, 'utf8')

acc = {
...acc,
[paths.outputFilePath]: isTypeScriptProject()
? content
: transformTSToJS(paths.outputFilePath, content),
const filesRecord = await templateDirectories.reduce<
Promise<Record<string, string>>
>(async (accP, dir) => {
const templateFiles = fs.readdirSync(path.join(apiBaseTemplatePath, dir))
const filePaths = templateFiles
.filter((fileName) => {
const fileNameParts = fileName.split('.')
// Remove all webAuthn files. We'll handle those in the next step
return fileNameParts.length <= 3 || fileNameParts.at(-3) !== 'webAuthn'
})
.map((fileName) => {
// remove "template" from the end, and change from {ts,tsx} to {js,jsx} for
// JavaScript projects
let outputFileName = fileName.replace(/\.template$/, '')
if (!isTypeScriptProject()) {
outputFileName = outputFileName.replace(/\.ts(x?)$/, '.js$1')
}

if (!webAuthn) {
return { templateFileName: fileName, outputFileName }
}

// Insert "webAuthn." before the second to last part
const webAuthnFileName = fileName
.split('.')
.reverse()
.map((part, i) => (i === 1 ? 'webAuthn.' + part : part))
.reverse()
.join('.')

// Favor the abc.xyz.webAuthn.ts.template file if it exists, otherwise
// just go with the "normal" filename
if (templateFiles.includes(webAuthnFileName)) {
return { templateFileName: webAuthnFileName, outputFileName }
} else {
return { templateFileName: fileName, outputFileName }
}
})
.map((f) => {
const templateFilePath = path.join(
apiBaseTemplatePath,
dir,
f.templateFileName
)
const outputFilePath = path.join(apiSrcPath, dir, f.outputFileName)

return { templateFilePath, outputFilePath }
})

return acc
},
{}
)
const acc = await accP
let nextAcc = {}

for (const paths of filePaths) {
const content = fs.readFileSync(paths.templateFilePath, 'utf8')

nextAcc = {
...acc,
[paths.outputFilePath]: isTypeScriptProject()
? content
: await transformTSToJS(paths.outputFilePath, content),
}
}

return nextAcc
}, Promise.resolve({}))

return filesRecord
}
Expand Down
6 changes: 3 additions & 3 deletions packages/cli-helpers/src/auth/authTasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ export const createWebAuth = (basedir: string, webAuthn: boolean) => {

return {
title: `Creating web/src/auth.${ext}`,
task: (ctx: AuthGeneratorCtx) => {
task: async (ctx: AuthGeneratorCtx) => {
// @MARK - finding unused file name here,
// We should only use an unused filename, if the user is CHOOSING not to replace the existing provider

Expand Down Expand Up @@ -399,7 +399,7 @@ export const createWebAuth = (basedir: string, webAuthn: boolean) => {

template = isTSProject
? template
: transformTSToJS(authFileName, template)
: await transformTSToJS(authFileName, template)

fs.writeFileSync(authFileName, template)
},
Expand Down Expand Up @@ -448,7 +448,7 @@ export const generateAuthApiFiles = <Renderer extends typeof ListrRenderer>(

// The keys in `filesRecord` are the full paths to where the file contents,
// which is the values in `filesRecord`, will be written.
let filesRecord = apiSideFiles({ basedir, webAuthn })
let filesRecord = await apiSideFiles({ basedir, webAuthn })

// Always overwrite files in force mode, no need to prompt
let existingFiles: ExistingFiles = 'FAIL'
Expand Down
14 changes: 9 additions & 5 deletions packages/cli-helpers/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ export const transformTSToJS = (filename: string, content: string) => {
/**
* This returns the config present in `prettier.config.js` of a Redwood project.
*/
export const prettierOptions = () => {
export const getPrettierOptions = async () => {
try {
const options = require(path.join(getPaths().base, 'prettier.config.js'))
const options = await import(
path.join(getPaths().base, 'prettier.config.js')
)

if (options.tailwindConfig?.startsWith('.')) {
// Make this work with --cwd
Expand All @@ -70,10 +72,10 @@ export const prettierOptions = () => {
}
}

export const prettify = (
export const prettify = async (
templateFilename: string,
renderedTemplate: string
): string => {
): Promise<string> => {
// We format .js and .css templates, we need to tell prettier which parser
// we're using.
// https://prettier.io/docs/en/options.html#parser
Expand All @@ -88,8 +90,10 @@ export const prettify = (
return renderedTemplate
}

const prettierOptions = await getPrettierOptions()

return format(renderedTemplate, {
...prettierOptions(),
...prettierOptions,
parser,
})
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/experimental/setupRscHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ export const handler = async ({ force, verbose }) => {

writeFile(
tsconfigPath,
prettify('tsconfig.json', JSON.stringify(tsconfig, null, 2)),
await prettify('tsconfig.json', JSON.stringify(tsconfig, null, 2)),
{
overwriteExisting: true,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import execa from 'execa'
import { Listr } from 'listr2'
import { format } from 'prettier'

import { colors, prettierOptions, setTomlSetting } from '@redwoodjs/cli-helpers'
import {
colors,
getPrettierOptions,
setTomlSetting,
} from '@redwoodjs/cli-helpers'
import { getConfig, getPaths } from '@redwoodjs/project-config'

import type { Args } from './fragments'
Expand Down Expand Up @@ -67,8 +71,10 @@ export async function handler({ force }: Args) {
const appPath = getPaths().web.app
const source = fs.readFileSync(appPath, 'utf-8')

const prettierOptions = await getPrettierOptions()

const prettifiedApp = format(source, {
...prettierOptions(),
...prettierOptions,
parser: 'babel-ts',
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import execa from 'execa'
import { Listr } from 'listr2'
import { format } from 'prettier'

import { prettierOptions, setTomlSetting } from '@redwoodjs/cli-helpers'
import { getPrettierOptions, setTomlSetting } from '@redwoodjs/cli-helpers'
import { getConfig, getPaths, resolveFile } from '@redwoodjs/project-config'

import { runTransform } from '../fragments/runTransform.js'
Expand Down Expand Up @@ -62,8 +62,10 @@ export async function handler({ force }: { force: boolean }) {

const source = fs.readFileSync(graphqlPath, 'utf-8')

const prettierOptions = await getPrettierOptions()

const prettifiedApp = format(source, {
...prettierOptions(),
...prettierOptions,
parser: 'babel-ts',
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const handler = async ({ force }: Args) => {
},
{
title: 'Implementing the Envelop plugin',
task: (ctx) => {
task: async (ctx) => {
const graphqlHandlerPath = path.join(
rwPaths.api.functions,
`graphql.${extension}`
Expand Down Expand Up @@ -95,13 +95,13 @@ export const handler = async ({ force }: Args) => {

fs.writeFileSync(
graphqlHandlerPath,
prettify('graphql.ts', contentLines.join('\n'))
await prettify('graphql.ts', contentLines.join('\n'))
)
},
},
{
title: "Replacing Redwood's Error boundary",
task: () => {
task: async () => {
const contentLines = fs
.readFileSync(rwPaths.web.app)
.toString()
Expand Down Expand Up @@ -136,7 +136,7 @@ export const handler = async ({ force }: Args) => {

fs.writeFileSync(
rwPaths.web.app,
prettify('App.tsx', contentLines.join('\n'))
await prettify('App.tsx', contentLines.join('\n'))
)
},
},
Expand Down
13 changes: 9 additions & 4 deletions packages/cli/src/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const generateTemplate = (templateFilename, { name, ...rest }) => {
}
}

export const prettify = (templateFilename, renderedTemplate) => {
export const prettify = async (templateFilename, renderedTemplate) => {
// We format .js and .css templates, we need to tell prettier which parser
// we're using.
// https://prettier.io/docs/en/options.html#parser
Expand All @@ -97,8 +97,10 @@ export const prettify = (templateFilename, renderedTemplate) => {
return renderedTemplate
}

const prettierOptions = await getPrettierOptions()

return format(renderedTemplate, {
...prettierOptions(),
...prettierOptions,
parser,
})
}
Expand Down Expand Up @@ -228,9 +230,12 @@ export const getConfig = () => {
/**
* This returns the config present in `prettier.config.js` of a Redwood project.
*/
export const prettierOptions = () => {
export const getPrettierOptions = async () => {
try {
return require(path.join(getPaths().base, 'prettier.config.js'))
const prettierOptions = await import(
path.join(getPaths().base, 'prettier.config.js')
)
return prettierOptions
} catch (e) {
// If we're in our vitest environment we want to return a consistent set of prettier options
// such that snapshots don't change unexpectedly.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const removeBabelConfig = async () => {

const newConfig = `module.exports = ${JSON.stringify(otherConfig)}`

fs.writeFileSync(webBabelConfigPath, prettify(newConfig))
fs.writeFileSync(webBabelConfigPath, await prettify(newConfig))
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default async function addApiAliasToTsConfig() {
ts.sys.writeFile(
webConfigPath,
// @NOTE: prettier will remove trailing commas, but whatever
prettify(JSON.stringify(updatedConfig), { parser: 'json' })
await prettify(JSON.stringify(updatedConfig), { parser: 'json' })
)
} else {
throw new Error(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const handler = () => {
// They don't show up in tests cause we run prettier. Let's do the same here.
fs.writeFileSync(
API_SERVER_CONFIG_PATH,
prettify(fs.readFileSync(API_SERVER_CONFIG_PATH, 'utf-8'))
await prettify(fs.readFileSync(API_SERVER_CONFIG_PATH, 'utf-8'))
)

setOutput('All done!')
Expand All @@ -51,7 +51,7 @@ export const handler = () => {
'server.config.js'
)

fs.writeFileSync(NEW_API_SERVER_CONFIG_PATH, prettify(text))
fs.writeFileSync(NEW_API_SERVER_CONFIG_PATH, await prettify(text))

setOutput(
'Done! No server.config.js found, so we updated your project to use the latest version.'
Expand Down
15 changes: 10 additions & 5 deletions packages/codemods/src/lib/prettify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,26 @@ import { format } from 'prettier'

import { getPaths } from '@redwoodjs/project-config'

const getPrettierConfig = () => {
const getPrettierConfig = async () => {
try {
return require(path.join(getPaths().base, 'prettier.config.js'))
const prettierConfig = await import(
path.join(getPaths().base, 'prettier.config.js')
)
return prettierConfig
} catch (e) {
return undefined
}
}

const prettify = (code: string, options: Record<string, any> = {}) =>
format(code, {
const prettify = async (code: string, options: Record<string, any> = {}) => {
const prettierConfig = await getPrettierConfig()
return format(code, {
singleQuote: true,
semi: false,
...getPrettierConfig(),
...prettierConfig(),
parser: 'babel',
...options,
})
}

export default prettify
Loading

0 comments on commit bfb632d

Please sign in to comment.