Skip to content

Commit

Permalink
promise watcher
Browse files Browse the repository at this point in the history
  • Loading branch information
mmkal committed Sep 6, 2024
1 parent dfb1e74 commit 19ffb05
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 62 deletions.
8 changes: 4 additions & 4 deletions packages/typegen/src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,10 +244,8 @@ export const generate = async (inputOptions: Partial<Options>) => {
const content = new Map<string, string>()
const promises: Array<Promise<void>> = []
const getContentSync = (filepath: string) => fs.readFileSync(filepath).toString()
const handler = async (filepath: string, ...args: unknown[]) => {
const handler = async (filepath: string, ..._args: unknown[]) => {
const fullpath = path.join(cwd, filepath)
// eslint-disable-next-line @typescript-eslint/no-var-requires
logger.info(require('util').inspect({filepath, fullpath, args}))
if (content.get(fullpath) === getContentSync(fullpath)) {
return // didn't change from what we'd expect
}
Expand All @@ -266,12 +264,14 @@ export const generate = async (inputOptions: Partial<Options>) => {
watcher.on('add', async f => handler(f, 'add'))
// eslint-disable-next-line @typescript-eslint/no-misused-promises
watcher.on('change', async f => handler(f, 'change'))
return {
const closer = {
async close() {
await watcher.close()
await Promise.all(promises)
},
}

return Object.assign(new Promise(() => {}), closer)
}

return watch
Expand Down
121 changes: 64 additions & 57 deletions packages/typegen/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,67 +6,75 @@ import {generate, Options} from './generate'

const trpc = trpcServer.initTRPC.meta<TrpcCliMeta>().create()

const CliOptions = z.object({
config: z
.string()
.optional()
.default(existsSync(defaults.typegenConfigFile) ? defaults.typegenConfigFile : (undefined as never))
.describe(
'Path to a module containing parameters to be passed to generate. Note: any options passed on the command line will override those in the config file.',
),
rootDir: z.string().describe('Path to the source directory containing SQL queries.').default(defaults.defaultRootDir),
connectionString: z
.string()
.describe('URL for connecting to postgres.') //
.default(defaults.defaultConnectionURI),
psql: z
.string()
.describe(
'psql command used to query postgres via CLI client. If using docker, you may want to use `docker-compose exec -T postgres psql`',
)
.default(defaults.defaultPsqlCommand),
defaultType: z
.string()
.describe('TypeScript fallback type for when no type is found.')
.default(defaults.defaultTypeScriptType),
include: z
.array(z.string())
.describe('Glob pattern of files to search for SQL queries in.')
.default(defaults.defaultIncludePatterns),
exclude: z
.array(z.string())
.describe('Glob pattern for files to be excluded from processing.')
.default(defaults.defaultExcludePatterns),
since: z
.string()
.optional()
.describe('Limit affected files to those which have been changed since the given git ref.'),
migrate: z
.enum(['<=0.8.0'])
.optional()
.describe('Before generating types, attempt to migrate a codebase which has used a prior version of this tool.'),
skipCheckClean: z
.boolean()
.optional()
.describe('If enabled, the tool will not check the git status to ensure changes are checked in.'),
watch: z
.boolean()
.optional()
.describe(
'Run the type checker in watch mode. Files will be run through the code generator when changed or added.',
),
lazy: z.boolean().optional().describe('Skip initial processing of input files. Only useful with --watch.'),
} satisfies {
[K in keyof Options & {config: unknown}]: unknown
})
const CliOptions = z
.object({
config: z
.string()
.optional()
.default(existsSync(defaults.typegenConfigFile) ? defaults.typegenConfigFile : (undefined as never))
.describe(
'Path to a module containing parameters to be passed to generate. Note: any options passed on the command line will override those in the config file.',
),
rootDir: z
.string()
.describe('Path to the source directory containing SQL queries.')
.default(defaults.defaultRootDir),
connectionString: z
.string()
.describe('URL for connecting to postgres.') //
.default(defaults.defaultConnectionURI),
psql: z
.string()
.describe(
'psql command used to query postgres via CLI client. If using docker, you may want to use `docker-compose exec -T postgres psql`',
)
.default(defaults.defaultPsqlCommand),
defaultType: z
.string()
.describe('TypeScript fallback type for when no type is found.')
.default(defaults.defaultTypeScriptType),
include: z
.array(z.string())
.describe('Glob pattern of files to search for SQL queries in.')
.default(defaults.defaultIncludePatterns),
exclude: z
.array(z.string())
.describe('Glob pattern for files to be excluded from processing.')
.default(defaults.defaultExcludePatterns),
since: z
.string()
.optional()
.describe('Limit affected files to those which have been changed since the given git ref.'),
migrate: z
.enum(['<=0.8.0'])
.optional()
.describe('Before generating types, attempt to migrate a codebase which has used a prior version of this tool.'),
checkClean: z
.array(z.enum(['before-migrate', 'after-migrate']))
.default([])
.describe('Run a git check to make sure there are no working changes before/after modifying source files.'),
watch: z
.boolean()
.optional()
.describe(
'Run the type checker in watch mode. Files will be run through the code generator when changed or added.',
),
lazy: z.boolean().optional().describe('Skip initial processing of input files. Implies --watch.'),
} satisfies {
[K in keyof Options & {config: unknown}]: unknown
})
.transform(val => ({
...val,
watch: val.watch ?? val.lazy,
}))

export const router = trpc.router({
generate: trpc.procedure
.meta({
description: 'Scans source files for SQL queries and generates TypeScript interfaces for them.',
})
.input(CliOptions)
.mutation(async ({input: {config: configPath, psql, watch, skipCheckClean, ...input}}) => {
.mutation(async ({input: {config: configPath, psql, watch, ...input}}) => {
let configModule: Partial<Options> | {default: Partial<Options>} | null = null

if (!configPath && existsSync(defaults.typegenConfigFile)) {
Expand All @@ -88,11 +96,10 @@ export const router = trpc.router({
...configModule,
...(psql && {psqlCommand: psql}),
...input,
...(skipCheckClean && {checkClean: []}),
})

if (watch || input.lazy) {
run.watch()
if (watch) {
await run.watch()
}
}),
})
2 changes: 1 addition & 1 deletion packages/typegen/typegen.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/** @type {Partial<import('./src/types').Options>} */
module.exports = {
checkClean: [],
// checkClean: [],
}

0 comments on commit 19ffb05

Please sign in to comment.