Skip to content

Commit

Permalink
refactor: remove some promisify to fs.promises (#18990)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jolg42 committed Apr 28, 2023
1 parent ccf3df0 commit cec59d3
Show file tree
Hide file tree
Showing 17 changed files with 51 additions and 96 deletions.
9 changes: 3 additions & 6 deletions packages/cli/helpers/build.ts
Expand Up @@ -3,14 +3,11 @@ import fs from 'fs'
import { copy } from 'fs-extra'
import lineReplace from 'line-replace'
import path from 'path'
import { promisify } from 'util'

import type { BuildOptions } from '../../../helpers/compile/build'
import { build } from '../../../helpers/compile/build'
import { run } from '../../../helpers/compile/run'

const copyFile = promisify(fs.copyFile)

/**
* Manages the extra actions that are needed for the CLI to work
*/
Expand All @@ -33,20 +30,20 @@ const cliLifecyclePlugin: esbuild.Plugin = {
})

// we copy the contents from checkpoint-client to build
await copyFile(
await fs.promises.copyFile(
path.join(require.resolve('checkpoint-client/package.json'), '../dist/child.js'),
'./build/child.js',
)

// we copy the contents from xdg-open to build
await copyFile(path.join(require.resolve('open/package.json'), '../xdg-open'), './build/xdg-open')
await fs.promises.copyFile(path.join(require.resolve('open/package.json'), '../xdg-open'), './build/xdg-open')

// as a convention, we install all Prisma's Wasm modules in the internals package
const wasmResolveDir = path.join(__dirname, '..', '..', 'internals', 'node_modules')

// TODO: create a glob helper for this to import all the wasm modules having pattern /^@prisma\/.*-wasm$/
const prismaWasmFile = path.join(wasmResolveDir, '@prisma', 'prisma-fmt-wasm', 'src', 'prisma_fmt_build_bg.wasm')
await copyFile(prismaWasmFile, './build/prisma_fmt_build_bg.wasm')
await fs.promises.copyFile(prismaWasmFile, './build/prisma_fmt_build_bg.wasm')

await replaceFirstLine('./build/index.js', '#!/usr/bin/env node\n')

Expand Down
4 changes: 1 addition & 3 deletions packages/cli/src/Doctor.ts
Expand Up @@ -18,9 +18,7 @@ import equal from 'fast-deep-equal'
import fs from 'fs'
import { bold, dim, green, red, underline } from 'kleur/colors'
import path from 'path'
import { promisify } from 'util'

const readFile = promisify(fs.readFile)
type IncorrectFieldTypes = Array<{
localField: DMMF.Field
remoteField: DMMF.Field
Expand Down Expand Up @@ -75,7 +73,7 @@ ${bold('Examples')}

const schemaPath = await getSchemaPathAndPrint(args['--schema'])

const schema = await readFile(schemaPath, 'utf-8')
const schema = await fs.promises.readFile(schemaPath, 'utf-8')
const localDmmf = await getDMMF({ datamodel: schema })
const config = await getConfig({ datamodel: schema, ignoreEnvVarErrors: false })

Expand Down
7 changes: 2 additions & 5 deletions packages/cli/src/utils/getClientVersion.ts
@@ -1,9 +1,6 @@
import fs from 'fs'
import Module from 'module'
import pkgUp from 'pkg-up'
import { promisify } from 'util'

const readFileAsync = promisify(fs.readFile)

/**
* Try reading the installed Prisma Client version
Expand All @@ -23,7 +20,7 @@ async function getPrismaClientVersionFromNodeModules(cwd: string = process.cwd()
return null
}

const pkgJsonString = await readFileAsync(pkgJsonPath, 'utf-8')
const pkgJsonString = await fs.promises.readFile(pkgJsonPath, 'utf-8')
const pkgJson = JSON.parse(pkgJsonString)

if (!pkgJson.version) {
Expand All @@ -47,7 +44,7 @@ async function getPrismaClientVersionFromLocalPackageJson(cwd: string = process.
return null
}

const pkgJsonString = await readFileAsync(pkgJsonPath, 'utf-8')
const pkgJsonString = await fs.promises.readFile(pkgJsonPath, 'utf-8')
const pkgJson = JSON.parse(pkgJsonString)
const clientVersion = pkgJson.dependencies?.['@prisma/client'] ?? pkgJson.devDependencies?.['@prisma/client']

Expand Down
4 changes: 1 addition & 3 deletions packages/cli/src/utils/prompt/utils/isDirEmpty.ts
@@ -1,10 +1,8 @@
import fs from 'fs'
import { promisify } from 'util'

const readdir = promisify(fs.readdir)
const allowList = ['.DS_Store']

export async function isDirEmpty(dir: string): Promise<boolean> {
const files = await readdir(dir)
const files = await fs.promises.readdir(dir)
return files.filter((f) => !allowList.includes(f)).length === 0
}
19 changes: 8 additions & 11 deletions packages/client/scripts/postinstall.js
Expand Up @@ -6,9 +6,6 @@ const path = require('path')
const c = require('./colors')

const exec = promisify(childProcess.exec)
const copyFile = promisify(fs.copyFile)
const mkdir = promisify(fs.mkdir)
const stat = promisify(fs.stat)

function debug(message, ...optionalParams) {
if (process.env.DEBUG && process.env.DEBUG === 'prisma:postinstall') {
Expand Down Expand Up @@ -215,27 +212,27 @@ async function createDefaultGeneratedThrowFiles() {
await makeDir(defaultDenoClientDir)

if (!fs.existsSync(defaultNodeIndexPath)) {
await copyFile(path.join(__dirname, 'default-index.js'), defaultNodeIndexPath)
await fs.promises.copyFile(path.join(__dirname, 'default-index.js'), defaultNodeIndexPath)
}

if (!fs.existsSync(defaultBrowserIndexPath)) {
await copyFile(path.join(__dirname, 'default-index-browser.js'), defaultBrowserIndexPath)
await fs.promises.copyFile(path.join(__dirname, 'default-index-browser.js'), defaultBrowserIndexPath)
}

if (!fs.existsSync(defaultNodeIndexDtsPath)) {
await copyFile(path.join(__dirname, 'default-index.d.ts'), defaultNodeIndexDtsPath)
await fs.promises.copyFile(path.join(__dirname, 'default-index.d.ts'), defaultNodeIndexDtsPath)
}

if (!fs.existsSync(defaultEdgeIndexPath)) {
await copyFile(path.join(__dirname, 'default-edge.js'), defaultEdgeIndexPath)
await fs.promises.copyFile(path.join(__dirname, 'default-edge.js'), defaultEdgeIndexPath)
}

if (!fs.existsSync(defaultEdgeIndexDtsPath)) {
await copyFile(path.join(__dirname, 'default-index.d.ts'), defaultEdgeIndexDtsPath)
await fs.promises.copyFile(path.join(__dirname, 'default-index.d.ts'), defaultEdgeIndexDtsPath)
}

if (!fs.existsSync(defaultDenoEdgeIndexPath)) {
await copyFile(path.join(__dirname, 'default-deno-edge.ts'), defaultDenoEdgeIndexPath)
await fs.promises.copyFile(path.join(__dirname, 'default-deno-edge.ts'), defaultDenoEdgeIndexPath)
}
} catch (e) {
console.error(e)
Expand All @@ -246,7 +243,7 @@ async function createDefaultGeneratedThrowFiles() {
function makeDir(input) {
const make = async (pth) => {
try {
await mkdir(pth)
await fs.promises.mkdir(pth)

return pth
} catch (error) {
Expand All @@ -269,7 +266,7 @@ function makeDir(input) {
}

try {
const stats = await stat(pth)
const stats = await fs.promises.stat(pth)
if (!stats.isDirectory()) {
throw new Error('The path is not a directory')
}
Expand Down
@@ -1,14 +1,11 @@
import fs from 'fs'
import path from 'path'
import { promisify } from 'util'

import { getTestClient } from '../../../../utils/getTestClient'

const copyFile = promisify(fs.copyFile)

test('atomic-operations', async () => {
// start with a fresh db
await copyFile(path.join(__dirname, 'dev.db'), path.join(__dirname, 'dev-tmp.db'))
await fs.promises.copyFile(path.join(__dirname, 'dev.db'), path.join(__dirname, 'dev-tmp.db'))

const PrismaClient = await getTestClient()
const prisma = new PrismaClient()
Expand Down
@@ -1,13 +1,10 @@
import fs from 'fs'
import path from 'path'
import { promisify } from 'util'

import { getTestClient } from '../../../../utils/getTestClient'

const copyFile = promisify(fs.copyFile)

test('uncheckedScalarInputs', async () => {
await copyFile(path.join(__dirname, 'dev.db'), path.join(__dirname, 'dev-tmp.db'))
await fs.promises.copyFile(path.join(__dirname, 'dev.db'), path.join(__dirname, 'dev-tmp.db'))
const PrismaClient = await getTestClient()
const prisma = new PrismaClient()
await prisma.user.deleteMany()
Expand Down
20 changes: 8 additions & 12 deletions packages/client/src/generation/generateClient.ts
Expand Up @@ -15,11 +15,7 @@ import type { Dictionary } from '../runtime/utils/common'
import { getPrismaClientDMMF } from './getDMMF'
import { BrowserJS, JS, TS, TSClient } from './TSClient'

const remove = promisify(fs.unlink)
const writeFile = promisify(fs.writeFile)
const exists = promisify(fs.exists)
const copyFile = promisify(fs.copyFile)
const stat = promisify(fs.stat)

const GENERATED_PACKAGE_NAME = '.prisma/client'

Expand Down Expand Up @@ -261,9 +257,9 @@ export async function generateClient(options: GenerateClientOptions): Promise<vo
// The deletion of the file is necessary, so VSCode
// picks up the changes.
if (await exists(filePath)) {
await remove(filePath)
await fs.promises.unlink(filePath)
}
await writeFile(filePath, file)
await fs.promises.writeFile(filePath, file)
}),
)
const runtimeSourceDir = testMode
Expand Down Expand Up @@ -341,28 +337,28 @@ export async function generateClient(options: GenerateClientOptions): Promise<vo

const schemaTargetPath = path.join(finalOutputDir, 'schema.prisma')
if (schemaPath !== schemaTargetPath) {
await copyFile(schemaPath, schemaTargetPath)
await fs.promises.copyFile(schemaPath, schemaTargetPath)
}

const proxyIndexJsPath = path.join(outputDir, 'index.js')
const proxyIndexBrowserJsPath = path.join(outputDir, 'index-browser.js')
const proxyIndexDTSPath = path.join(outputDir, 'index.d.ts')
if (!fs.existsSync(proxyIndexJsPath)) {
await copyFile(path.join(__dirname, '../../index.js'), proxyIndexJsPath)
await fs.promises.copyFile(path.join(__dirname, '../../index.js'), proxyIndexJsPath)
}

if (!fs.existsSync(proxyIndexDTSPath)) {
await copyFile(path.join(__dirname, '../../index.d.ts'), proxyIndexDTSPath)
await fs.promises.copyFile(path.join(__dirname, '../../index.d.ts'), proxyIndexDTSPath)
}

if (!fs.existsSync(proxyIndexBrowserJsPath)) {
await copyFile(path.join(__dirname, '../../index-browser.js'), proxyIndexBrowserJsPath)
await fs.promises.copyFile(path.join(__dirname, '../../index-browser.js'), proxyIndexBrowserJsPath)
}
}

async function fileSize(name: string): Promise<number | null> {
try {
const statResult = await stat(name)
const statResult = await fs.promises.stat(name)
return statResult.size
} catch (e) {
return null
Expand Down Expand Up @@ -574,5 +570,5 @@ async function copyRuntimeFiles({ from, to, runtimeName, sourceMaps }: CopyRunti
files.push(...files.filter((file) => file.endsWith('.js')).map((file) => `${file}.map`))
}

await Promise.all(files.map((file) => copyFile(path.join(from, file), path.join(to, file))))
await Promise.all(files.map((file) => fs.promises.copyFile(path.join(from, file), path.join(to, file))))
}
11 changes: 3 additions & 8 deletions packages/client/src/runtime/utils/find.ts
@@ -1,11 +1,6 @@
/* eslint-disable @typescript-eslint/no-inferrable-types */
import fs from 'fs'
import path from 'path'
import { promisify } from 'util'

const readdirAsync = promisify(fs.readdir)
const realpathAsync = promisify(fs.realpath)
const statAsync = promisify(fs.stat)

const readdirSync = fs.readdirSync
const realpathSync = fs.realpathSync
Expand Down Expand Up @@ -182,7 +177,7 @@ export async function findAsync(
seen: Record<string, true> = {},
) {
try {
const realRoot = await realpathAsync(root)
const realRoot = await fs.promises.realpath(root)

// we make sure not to loop infinitely
if (seen[realRoot]) {
Expand All @@ -195,12 +190,12 @@ export async function findAsync(
}

// we check that the root is a directory
if (direntToType(await statAsync(realRoot)) !== 'd') {
if (direntToType(await fs.promises.stat(realRoot)) !== 'd') {
return found
}

// we list the items in the current root
const items = await readdirAsync(root, { withFileTypes: true })
const items = await fs.promises.readdir(root, { withFileTypes: true })

seen[realRoot] = true
for (const item of items) {
Expand Down
5 changes: 1 addition & 4 deletions packages/client/src/utils/getTestClient.ts
Expand Up @@ -13,16 +13,13 @@ import {
import fs from 'fs'
import path from 'path'
import { parse } from 'stacktrace-parser'
import { promisify } from 'util'

import { getDMMF } from '../generation/getDMMF'
import type { GetPrismaClientConfig } from '../runtime/getPrismaClient'
import { getPrismaClient } from '../runtime/getPrismaClient'
import { ensureTestClientQueryEngine } from './ensureTestClientQueryEngine'
import { generateInFolder } from './generateInFolder'

const readFile = promisify(fs.readFile)

//TODO Rename to generateTestClientInMemory
/**
* Returns an in-memory client for testing
Expand All @@ -31,7 +28,7 @@ export async function getTestClient(schemaDir?: string, printWarnings?: boolean)
const callSite = path.dirname(require.main?.filename ?? '')
const absSchemaDir = path.resolve(callSite, schemaDir ?? '')
const schemaPath = await getRelativeSchemaPath(absSchemaDir)
const datamodel = await readFile(schemaPath!, 'utf-8')
const datamodel = await fs.promises.readFile(schemaPath!, 'utf-8')
const config = await getConfig({ datamodel, ignoreEnvVarErrors: true })
if (printWarnings) {
printConfigWarnings(config.warnings)
Expand Down
6 changes: 2 additions & 4 deletions packages/fetch-engine/src/cleanupCache.ts
Expand Up @@ -9,8 +9,6 @@ import { getRootCacheDir } from './utils'

const debug = Debug('cleanupCache')
const del = promisify(rimraf)
const readdir = promisify(fs.readdir)
const stat = promisify(fs.stat)

export async function cleanupCache(n = 5): Promise<void> {
try {
Expand All @@ -21,11 +19,11 @@ export async function cleanupCache(n = 5): Promise<void> {
}
const channel = 'master'
const cacheDir = path.join(rootCacheDir, channel)
const dirs = await readdir(cacheDir)
const dirs = await fs.promises.readdir(cacheDir)
const dirsWithMeta = await Promise.all(
dirs.map(async (dirName) => {
const dir = path.join(cacheDir, dirName)
const statResult = await stat(dir)
const statResult = await fs.promises.stat(dir)

return {
dir,
Expand Down

0 comments on commit cec59d3

Please sign in to comment.