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 730bc87 commit c1d7ec7
Show file tree
Hide file tree
Showing 16 changed files with 138 additions and 109 deletions.
12 changes: 6 additions & 6 deletions packages/cli-helpers/src/auth/__tests__/authFiles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ beforeEach(() => {
vi.mocked(isTypeScriptProject).mockReturnValue(true)
})

it('generates a record of TS files', () => {
it('generates a record of TS files', async () => {
const filePaths = Object.keys(
apiSideFiles({
await apiSideFiles({
basedir: path.join(__dirname, 'fixtures/supertokensSetup'),
webAuthn: false,
})
Expand All @@ -54,11 +54,11 @@ it('generates a record of TS files', () => {
])
})

it('generates a record of JS files', () => {
it('generates a record of JS files', async () => {
vi.mocked(isTypeScriptProject).mockReturnValue(false)

const filePaths = Object.keys(
apiSideFiles({
await apiSideFiles({
basedir: path.join(__dirname, 'fixtures/supertokensSetup'),
webAuthn: false,
})
Expand All @@ -71,8 +71,8 @@ it('generates a record of JS files', () => {
])
})

it('generates a record of webAuthn files', () => {
const filesRecord = apiSideFiles({
it('generates a record of webAuthn files', async () => {
const filesRecord = await apiSideFiles({
basedir: path.join(__dirname, 'fixtures/dbAuthSetup'),
webAuthn: true,
})
Expand Down
4 changes: 2 additions & 2 deletions packages/cli-helpers/src/auth/__tests__/authTasks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ describe('authTasks', () => {
).toMatchSnapshot()
})

it('writes an auth.js file for JS projects', () => {
it('writes an auth.js file for JS projects', async () => {
vi.mocked(isTypeScriptProject).mockReturnValue(false)

vol.fromJSON({
Expand All @@ -656,7 +656,7 @@ describe('authTasks', () => {
provider: 'auth0',
setupMode: 'FORCE',
}
createWebAuth(getPaths().base, false).task(ctx)
await createWebAuth(getPaths().base, false).task(ctx)

expect(
fs.readFileSync(path.join(getPaths().web.src, 'auth.js'), 'utf-8')
Expand Down
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
6 changes: 4 additions & 2 deletions packages/cli-helpers/src/lib/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ vi.mock('../paths', () => {
}
})

test('prettify formats tsx content', () => {
test('prettify formats tsx content', async () => {
const content = `import React from 'react'
interface Props { foo: number, bar: number }
Expand All @@ -30,5 +30,7 @@ test('prettify formats tsx content', () => {
return <>{foo}, {bar}</>}`

expect(prettify('FooBarComponent.template.tsx', content)).toMatchSnapshot()
expect(
await prettify('FooBarComponent.template.tsx', content)
).toMatchSnapshot()
})
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
Loading

0 comments on commit c1d7ec7

Please sign in to comment.