Skip to content

Commit

Permalink
feat: improve typescript support
Browse files Browse the repository at this point in the history
  • Loading branch information
typicode committed Dec 9, 2022
1 parent 716f672 commit 17ca0d7
Showing 1 changed file with 47 additions and 15 deletions.
62 changes: 47 additions & 15 deletions src/bin.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,33 @@
#!/usr/bin/env node
import { promises as fs } from 'fs'
import { basename, join } from 'path'
import { pathToFileURL } from 'url'
import { fork } from 'node:child_process'
import { promises as fs } from 'node:fs'
import { basename, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'

const regexp = /^test\.(js|ts)$|\.test\.(js|ts)$/

function parse(argv: string[]): [string[], string[]] {
const execArgv: string[] = []
const args = argv.filter((arg) => {
if (arg.startsWith('--')) {
execArgv.push(arg)
return false
}
return true
})
return [execArgv, args]
}

function forkProcess(execArgv: string[], args: string[]) {
const child = fork(fileURLToPath(import.meta.url), args, {
execArgv,
stdio: 'inherit',
})
child.on('exit', (code) => process.exit(code ?? 0))
child.on('error', (err) => {
throw err
})
}

async function* walk(dir: string): AsyncGenerator<string> {
for await (const d of await fs.opendir(dir)) {
Expand All @@ -13,6 +39,7 @@ async function* walk(dir: string): AsyncGenerator<string> {

async function runTestFile(file: string): Promise<void> {
for (const value of Object.values(
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
await import(pathToFileURL(file).toString()),
)) {
if (typeof value === 'function') {
Expand All @@ -26,19 +53,24 @@ async function runTestFile(file: string): Promise<void> {
}
}

async function run(arg = '.') {
if ((await fs.lstat(arg)).isFile()) {
return runTestFile(arg)
}
for await (const file of walk(arg)) {
if (
basename(file) === 'test.js' ||
file.endsWith('.test.js')
) {
console.log(file)
await runTestFile(file)
async function run(paths: string[]) {
for (const p of paths) {
if ((await fs.lstat(p)).isFile()) {
return runTestFile(p)
}
for await (const file of walk(p)) {
if (regexp.test(basename(file))) {
console.log(file)
await runTestFile(file)
}
}
}
}

void run(process.argv[2])
const [execArgv, args] = parse(process.argv.slice(2))
if (!args.length) args.push('.')
if (execArgv.length) {
forkProcess(execArgv, args)
} else {
void run(args)
}

0 comments on commit 17ca0d7

Please sign in to comment.