From aa878003b9ed2f792910321873582bfd17e07c33 Mon Sep 17 00:00:00 2001 From: Joakim Carlstein Date: Tue, 14 Nov 2023 16:19:36 +0100 Subject: [PATCH] feat(emigrate): add support for reading config from emigrate.config.js (and others) Also add a new "extension" option for generating empty migration files with the right file extension. --- .changeset/little-moons-rush.md | 5 +++++ .changeset/shaggy-doors-trade.md | 5 +++++ packages/emigrate/package.json | 9 ++++++++- packages/emigrate/src/cli.ts | 18 ++++++++++++++--- packages/emigrate/src/get-config.ts | 20 +++++++++++++++++++ packages/emigrate/src/index.ts | 2 ++ packages/emigrate/src/new-command.ts | 29 ++++++++++++++++++---------- packages/emigrate/src/types.ts | 16 +++++++++++++++ packages/tsconfig/base.json | 1 + pnpm-lock.yaml | 3 +++ 10 files changed, 94 insertions(+), 14 deletions(-) create mode 100644 .changeset/little-moons-rush.md create mode 100644 .changeset/shaggy-doors-trade.md create mode 100644 packages/emigrate/src/get-config.ts create mode 100644 packages/emigrate/src/types.ts diff --git a/.changeset/little-moons-rush.md b/.changeset/little-moons-rush.md new file mode 100644 index 0000000..e782a15 --- /dev/null +++ b/.changeset/little-moons-rush.md @@ -0,0 +1,5 @@ +--- +'emigrate': minor +--- + +Add the "extension" option for the "new" command to be able to generate empty migration files without any plugin and template and still get the right file extension. It can also be used together with the "template" option to override the template file's file extension when saving the new migration file. diff --git a/.changeset/shaggy-doors-trade.md b/.changeset/shaggy-doors-trade.md new file mode 100644 index 0000000..b5336ae --- /dev/null +++ b/.changeset/shaggy-doors-trade.md @@ -0,0 +1,5 @@ +--- +'emigrate': minor +--- + +Support reading config from for instance emigrate.config.js diff --git a/packages/emigrate/package.json b/packages/emigrate/package.json index c04ffda..ecdf2c5 100644 --- a/packages/emigrate/package.json +++ b/packages/emigrate/package.json @@ -8,6 +8,12 @@ "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", + "exports": { + ".": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + } + }, "bin": { "emigrate": "dist/cli.js" }, @@ -28,7 +34,8 @@ "author": "Aboviq AB (https://www.aboviq.com)", "license": "MIT", "dependencies": { - "@emigrate/plugin-tools": "workspace:*" + "@emigrate/plugin-tools": "workspace:*", + "cosmiconfig": "8.3.6" }, "volta": { "extends": "../../package.json" diff --git a/packages/emigrate/src/cli.ts b/packages/emigrate/src/cli.ts index 97fca72..862ea5b 100644 --- a/packages/emigrate/src/cli.ts +++ b/packages/emigrate/src/cli.ts @@ -2,6 +2,7 @@ import process from 'node:process'; import { parseArgs } from 'node:util'; import { ShowUsageError } from './show-usage-error.js'; +import { getConfig } from './get-config.js'; type Action = (args: string[]) => Promise; @@ -57,6 +58,7 @@ Examples: }; const newMigration: Action = async (args) => { + const config = await getConfig('new'); const { values, positionals } = parseArgs({ args, options: { @@ -72,6 +74,10 @@ const newMigration: Action = async (args) => { type: 'string', short: 't', }, + extension: { + type: 'string', + short: 'e', + }, plugin: { type: 'string', short: 'p', @@ -92,13 +98,18 @@ Options: -d, --directory The directory where the migration files are located (required) -p, --plugin The plugin(s) to use (can be specified multiple times) -t, --template A template file to use as contents for the new migration file + (if the extension option is not provided the template file's extension will be used) + -e, --extension The extension to use for the new migration file + (if no template or plugin is provided an empty migration file will be created with the given extension) - Either the --template or the --plugin option is required must be specified + One of the --template, --extension or the --plugin options must be specified Examples: emigrate new -d src/migrations -t migration-template.js create users table emigrate new --directory ./migrations --plugin @emigrate/plugin-generate-sql create_users_table + emigrate new -d ./migrations -e .sql create_users_table + emigrate new -d ./migrations -t .migration-template -e .sql "drop some table" `; if (values.help) { @@ -107,12 +118,13 @@ Examples: return; } - const { plugin: plugins = [], directory, template } = values; + const { directory = config.directory, template = config.template, extension = config.extension } = values; + const plugins = [...(config.plugins ?? []), ...(values.plugin ?? [])]; const name = positionals.join(' ').trim(); try { const { default: newCommand } = await import('./new-command.js'); - await newCommand({ directory, template, plugins, name }); + await newCommand({ directory, template, plugins, name, extension }); } catch (error) { if (error instanceof ShowUsageError) { console.error(error.message, '\n'); diff --git a/packages/emigrate/src/get-config.ts b/packages/emigrate/src/get-config.ts new file mode 100644 index 0000000..85d26b2 --- /dev/null +++ b/packages/emigrate/src/get-config.ts @@ -0,0 +1,20 @@ +import { cosmiconfig } from 'cosmiconfig'; +import { type Config, type EmigrateConfig } from './types.js'; + +export const getConfig = async (command: 'up' | 'list' | 'new'): Promise => { + const explorer = cosmiconfig('emigrate'); + + const result = await explorer.search(); + + if (!result?.config) { + return {}; + } + + const { plugins, directory, template, ...commandsConfig } = result.config as EmigrateConfig; + + if (commandsConfig[command]) { + return { plugins, directory, template, ...commandsConfig[command] }; + } + + return { plugins, directory, template }; +}; diff --git a/packages/emigrate/src/index.ts b/packages/emigrate/src/index.ts index 411e46f..f780588 100644 --- a/packages/emigrate/src/index.ts +++ b/packages/emigrate/src/index.ts @@ -1,3 +1,5 @@ +export * from './types.js'; + export const emigrate = () => { console.log('Done!'); }; diff --git a/packages/emigrate/src/new-command.ts b/packages/emigrate/src/new-command.ts index 20e4df0..3ee2d43 100644 --- a/packages/emigrate/src/new-command.ts +++ b/packages/emigrate/src/new-command.ts @@ -1,18 +1,19 @@ import process from 'node:process'; import fs from 'node:fs/promises'; import path from 'node:path'; -import { getTimestampPrefix, sanitizeMigrationName, loadPlugin } from '@emigrate/plugin-tools'; -import { type GeneratorPlugin } from '@emigrate/plugin-tools/types'; +import { getTimestampPrefix, sanitizeMigrationName, loadPlugin, isGeneratorPlugin } from '@emigrate/plugin-tools'; +import { type Plugin, type GeneratorPlugin } from '@emigrate/plugin-tools/types'; import { ShowUsageError } from './show-usage-error.js'; type NewCommandOptions = { directory?: string; template?: string; - plugins: string[]; + extension?: string; + plugins: Array; name?: string; }; -export default async function newCommand({ directory, template, plugins, name }: NewCommandOptions) { +export default async function newCommand({ directory, template, plugins, name, extension }: NewCommandOptions) { if (!directory) { throw new ShowUsageError('Missing required option: directory'); } @@ -21,8 +22,8 @@ export default async function newCommand({ directory, template, plugins, name }: throw new ShowUsageError('Missing required migration name'); } - if (!template && plugins.length === 0) { - throw new ShowUsageError('Missing required option: template or plugin'); + if (!extension && !template && plugins.length === 0) { + throw new ShowUsageError('Missing required option: extension, template or plugin'); } let filename: string | undefined; @@ -31,7 +32,7 @@ export default async function newCommand({ directory, template, plugins, name }: if (template) { const fs = await import('node:fs/promises'); const templatePath = path.resolve(process.cwd(), template); - const extension = path.extname(templatePath); + const fileExtension = path.extname(templatePath); try { content = await fs.readFile(templatePath, 'utf8'); @@ -40,12 +41,17 @@ export default async function newCommand({ directory, template, plugins, name }: throw new Error(`Failed to read template file: ${templatePath}`, { cause: error }); } - filename = `${getTimestampPrefix()}_${sanitizeMigrationName(name)}${extension}`; + filename = `${getTimestampPrefix()}_${sanitizeMigrationName(name)}${extension ?? fileExtension}`; } else if (plugins.length > 0) { let generatorPlugin: GeneratorPlugin | undefined; for await (const plugin of plugins) { - generatorPlugin = await loadPlugin('generator', plugin); + if (isGeneratorPlugin(plugin)) { + generatorPlugin = plugin; + break; + } + + generatorPlugin = typeof plugin === 'string' ? await loadPlugin('generator', plugin) : undefined; if (generatorPlugin) { break; @@ -60,9 +66,12 @@ export default async function newCommand({ directory, template, plugins, name }: filename = generated.filename; content = generated.content; + } else if (extension) { + content = ''; + filename = `${getTimestampPrefix()}_${sanitizeMigrationName(name)}${extension}`; } - if (!filename || !content) { + if (!filename || content === undefined) { throw new Error('Unexpected error, missing filename or content for migration file'); } diff --git a/packages/emigrate/src/types.ts b/packages/emigrate/src/types.ts new file mode 100644 index 0000000..65836b8 --- /dev/null +++ b/packages/emigrate/src/types.ts @@ -0,0 +1,16 @@ +import { type Plugin } from '@emigrate/plugin-tools/types'; + +export type EmigratePlugin = Plugin; + +export type Config = { + plugins?: Array; + directory?: string; + template?: string; + extension?: string; +}; + +export type EmigrateConfig = Config & { + up?: Config; + new?: Config; + list?: Config; +}; diff --git a/packages/tsconfig/base.json b/packages/tsconfig/base.json index 73df33f..91a38e3 100644 --- a/packages/tsconfig/base.json +++ b/packages/tsconfig/base.json @@ -24,6 +24,7 @@ "noUnusedLocals": true, "noUnusedParameters": true, "preserveWatchOutput": true, + "preserveSymlinks": true, "resolveJsonModule": false, "skipLibCheck": true, "sourceMap": true, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bf5a108..9f89048 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -59,6 +59,9 @@ importers: '@emigrate/plugin-tools': specifier: workspace:* version: link:../plugin-tools + cosmiconfig: + specifier: 8.3.6 + version: 8.3.6(typescript@5.2.2) devDependencies: '@emigrate/tsconfig': specifier: workspace:*