Skip to content

Commit

Permalink
chore: change all packages to strict (#5114)
Browse files Browse the repository at this point in the history
  • Loading branch information
williamluke4 committed Jan 15, 2021
1 parent ae04cf9 commit 6f1a031
Show file tree
Hide file tree
Showing 13 changed files with 230 additions and 112 deletions.
1 change: 1 addition & 0 deletions src/packages/fetch-engine/package.json
Expand Up @@ -11,6 +11,7 @@
"@types/node": "12.19.13",
"@types/node-fetch": "2.5.7",
"@types/progress": "2.0.3",
"@types/find-cache-dir": "^3.2.0",
"@typescript-eslint/eslint-plugin": "4.13.0",
"@typescript-eslint/parser": "4.13.0",
"del": "6.0.0",
Expand Down
4 changes: 2 additions & 2 deletions src/packages/fetch-engine/src/__tests__/download.test.ts
Expand Up @@ -193,7 +193,7 @@ describe('download', () => {
'query-engine': __dirname,
},
})
const dummyPath = e['query-engine'][Object.keys(e['query-engine'])[0]]!
const dummyPath = e['query-engine']![Object.keys(e['query-engine']!)[0]]!
const targetPath = path.join(
__dirname,
getBinaryName('query-engine', 'marvin'),
Expand All @@ -207,7 +207,7 @@ describe('download', () => {
},
binaryTargets: ['marvin'] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
})
expect(testResult['query-engine']['marvin']).toEqual(targetPath)
expect(testResult['query-engine']!['marvin']).toEqual(targetPath)
})
test.skip('download all binaries & cache them', async () => {
const baseDir = path.join(__dirname, 'all')
Expand Down
9 changes: 7 additions & 2 deletions src/packages/fetch-engine/src/cleanupCache.ts
Expand Up @@ -4,15 +4,20 @@ import { getRootCacheDir } from './util'
import rimraf from 'rimraf'
import { promisify } from 'util'
import pMap from 'p-map'
// import Debug from '@prisma/debug'
// const debug = Debug('cleanupCache')

import Debug from '@prisma/debug'
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 {
const rootCacheDir = await getRootCacheDir()
if(!rootCacheDir){
debug('no rootCacheDir found')
return
}
const channel = 'master'
const cacheDir = path.join(rootCacheDir, channel)
const dirs = await readdir(cacheDir)
Expand Down
61 changes: 30 additions & 31 deletions src/packages/fetch-engine/src/download.ts
Expand Up @@ -67,15 +67,15 @@ type BinaryDownloadJob = {
binaryTarget: string
fileName: string
targetFilePath: string
envVarPath: string
envVarPath: string | null
}

export async function download(options: DownloadOptions): Promise<BinaryPaths> {
// get platform
const platform = await getPlatform()
const os = await getos()

if (['nixos'].includes(os.distro)) {
if (os.distro && ['nixos'].includes(os.distro)) {
console.error(
`${chalk.yellow('Warning')} Precompiled binaries are not available for ${
os.distro
Expand All @@ -97,19 +97,18 @@ export async function download(options: DownloadOptions): Promise<BinaryPaths> {
}

// merge options
options = {
const opts = {
...options,
binaryTargets: options.binaryTargets ?? [platform],
version: options.version ?? 'latest',
binaries: mapKeys(options.binaries, (key) =>
engineTypeToBinaryType(key, platform),
binaries: mapKeys(options.binaries, (key) => engineTypeToBinaryType(key, platform),
), // just necessary to support both camelCase and hyphen-case
}

const binaryJobs: Array<BinaryDownloadJob> = flatMap(
Object.entries(options.binaries),
([binaryName, targetFolder]) =>
options.binaryTargets.map((binaryTarget) => {
const binaryJobs = flatMap(
Object.entries(opts.binaries),
([binaryName, targetFolder]: [string, string]) =>
opts.binaryTargets.map((binaryTarget) => {
const fileName = getBinaryName(binaryName, binaryTarget)
return {
binaryName,
Expand All @@ -123,30 +122,30 @@ export async function download(options: DownloadOptions): Promise<BinaryPaths> {
)

if (process.env.BINARY_DOWNLOAD_VERSION) {
options.version = process.env.BINARY_DOWNLOAD_VERSION
opts.version = process.env.BINARY_DOWNLOAD_VERSION
}

if (options.version === 'latest') {
options.version = await getLatestTag()
if (opts.version === 'latest') {
opts.version = await getLatestTag()
}

if (options.printVersion) {
console.log(`version: ${options.version}`)
if (opts.printVersion) {
console.log(`version: ${opts.version}`)
}

// filter out files, which don't yet exist or have to be created
const binariesToDownload = await pFilter(binaryJobs, async (job) => {
const needsToBeDownloaded = await binaryNeedsToBeDownloaded(
job,
platform,
options.version,
options.failSilent,
opts.version,
opts.failSilent,
)
const isSupported = platforms.includes(job.binaryTarget as Platform)
const shouldDownload =
isSupported &&
!job.envVarPath &&
(options.ignoreCache || needsToBeDownloaded)
(opts.ignoreCache || needsToBeDownloaded)
if (needsToBeDownloaded && !isSupported) {
throw new Error(
`Unknown binaryTarget ${job.binaryTarget} and no custom binaries were provided`,
Expand All @@ -163,8 +162,8 @@ export async function download(options: DownloadOptions): Promise<BinaryPaths> {
| undefined
| ((sourcePath: string) => (progress: number) => void)

if (options.showProgress) {
const collectiveBar = getCollectiveBar(options)
if (opts.showProgress) {
const collectiveBar = getCollectiveBar(opts)
finishBar = collectiveBar.finishBar
setProgress = collectiveBar.setProgress
}
Expand All @@ -174,8 +173,8 @@ export async function download(options: DownloadOptions): Promise<BinaryPaths> {
binariesToDownload.map((job) =>
downloadBinary({
...job,
version: options.version,
failSilent: options.failSilent,
version: opts.version,
failSilent: opts.failSilent,
progressCb: setProgress ? setProgress(job.targetFilePath) : undefined,
}),
),
Expand Down Expand Up @@ -212,15 +211,15 @@ function getCollectiveBar(
} {
const bar = getBar(
`Downloading Prisma engines for ${options.binaryTargets
.map((p) => chalk.bold(p))
?.map((p) => chalk.bold(p))
.join(' and ')}`,
)

const progressMap: { [key: string]: number } = {}
// Object.values is faster than Object.keys
const numDownloads =
Object.values(options.binaries).length *
Object.values(options.binaryTargets).length
Object.values(options?.binaryTargets ?? []).length
const setProgress = (sourcePath: string) => (progress): void => {
progressMap[sourcePath] = progress
const progressValues = Object.values(progressMap)
Expand Down Expand Up @@ -262,7 +261,7 @@ async function binaryNeedsToBeDownloaded(
job: BinaryDownloadJob,
nativePlatform: string,
version: string,
failSilent: boolean,
failSilent?: boolean,
): Promise<boolean> {
const binaryPath = job.envVarPath ?? job.targetFilePath

Expand Down Expand Up @@ -337,7 +336,7 @@ export function getBinaryName(binaryName: string, platform: string): string {

type GetCachedBinaryOptions = BinaryDownloadJob & {
version: string
failSilent: boolean
failSilent?: boolean
}

async function getCachedBinaryPath({
Expand Down Expand Up @@ -372,7 +371,7 @@ async function getCachedBinaryPath({
export function getBinaryEnvVarPath(binaryName: string): string | null {
const envVar = binaryToEnvVar[binaryName]
if (envVar && process.env[envVar]) {
const envVarPath = path.resolve(process.cwd(), process.env[envVar])
const envVarPath = path.resolve(process.cwd(), process.env[envVar] as string)
if (!fs.existsSync(envVarPath)) {
throw new Error(
`Env var ${chalk.bold(
Expand Down Expand Up @@ -508,15 +507,15 @@ function engineTypeToBinaryType(
return engineType
}

function mapKeys<T extends object>(
function mapKeys<T extends object, K extends keyof T>(
obj: T,
mapper: (key: keyof T) => string,
mapper: (key: K) => string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): any {
) {
return Object.entries(obj).reduce((acc, [key, value]) => {
acc[mapper(key as keyof T)] = value
acc[mapper(key as K)] = value
return acc
}, {})
}, {} as Record<string, any>)
}

export async function maybeCopyToTmp(file: string): Promise<string> {
Expand Down
2 changes: 1 addition & 1 deletion src/packages/fetch-engine/src/downloadZip.ts
Expand Up @@ -61,7 +61,7 @@ export async function downloadZip(
}

const lastModified = resp.headers.get('last-modified')!
const size = parseFloat(resp.headers.get('content-length'))
const size = parseFloat(resp.headers.get('content-length') as string)
const ws = fs.createWriteStream(partial)

// eslint-disable-next-line @typescript-eslint/no-misused-promises, no-async-promise-executor
Expand Down
1 change: 1 addition & 0 deletions src/packages/fetch-engine/src/flatMap.ts
@@ -1,4 +1,5 @@
function flatten<T>(array: T[]): [] {
// @ts-ignore
return Array.prototype.concat.apply([], array)
}

Expand Down
4 changes: 2 additions & 2 deletions src/packages/fetch-engine/src/getLatestTag.ts
Expand Up @@ -51,7 +51,7 @@ export async function getLatestTag(): Promise<any> {
}

export function getAllUrls(branch: string, commit: string): string[] {
const urls = []
const urls: string[] = []
const excludedPlatforms = [
'freebsd',
'arm',
Expand Down Expand Up @@ -96,7 +96,7 @@ export function getAllUrls(branch: string, commit: string): string[] {
async function getFirstFinishedCommit(
branch: string,
commits: string[],
): Promise<string> {
): Promise<string | void> {
for (const commit of commits) {
const urls = getAllUrls(branch, commit)
// TODO: potential to speed things up
Expand Down
2 changes: 1 addition & 1 deletion src/packages/fetch-engine/src/util.ts
Expand Up @@ -8,7 +8,7 @@ const debug = Debug('cache-dir')

export async function getRootCacheDir(): Promise<string | null> {
if (os.platform() === 'win32') {
const cacheDir = await findCacheDir({ name: 'prisma', create: true })
const cacheDir = findCacheDir({ name: 'prisma', create: true })
if (cacheDir) {
return cacheDir
}
Expand Down
2 changes: 1 addition & 1 deletion src/packages/fetch-engine/tsconfig.json
Expand Up @@ -4,7 +4,7 @@
"lib": ["esnext"],
"module": "commonjs",
"target": "es2018",
"strict": false,
"strict": true,
"esModuleInterop": true,
"sourceMap": true,
"noImplicitAny": false,
Expand Down
2 changes: 1 addition & 1 deletion src/packages/get-platform/tsconfig.json
Expand Up @@ -3,7 +3,7 @@
"lib": ["esnext"],
"module": "commonjs",
"target": "es2018",
"strict": false,
"strict": true,
"esModuleInterop": true,
"sourceMap": true,
"noImplicitAny": false,
Expand Down
Expand Up @@ -410,7 +410,7 @@ function makeDatasourceBlock(providerName: string, url: string) {
* Create Prisma schema enabled features array of strings.
*/
function renderPreviewFeatures(
featureMatrix: Input['prismaClientSettings']['previewFeatures'] | undefined,
featureMatrix: PreviewFeature[] | undefined,
) {
if (featureMatrix) {
return `previewFeatures = [${featureMatrix.map(
Expand Down
2 changes: 1 addition & 1 deletion src/packages/tests/tsconfig.json
Expand Up @@ -3,7 +3,7 @@
"lib": ["esnext"],
"module": "commonjs",
"target": "es2018",
"strict": false,
"strict": true,
"esModuleInterop": true,
"sourceMap": true,
"noImplicitAny": false,
Expand Down

0 comments on commit 6f1a031

Please sign in to comment.