Skip to content

Commit

Permalink
refactor(migration): reuse resolve migration logic in run command
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Feb 3, 2024
1 parent 471e491 commit 063f8eb
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type {Migration} from '@sanity/migrate'
import {Table} from 'console-table-printer'
import {register} from 'esbuild-register/dist/node'
import {MIGRATIONS_DIRECTORY, MIGRATION_SCRIPT_EXTENSIONS} from './constants'
import {resolveMigrationScript} from './utils'
import {isLoadableMigrationScript, resolveMigrationScript} from './utils'

const helpText = ``

Expand Down Expand Up @@ -85,13 +85,9 @@ export async function resolveMigrations(workDir: string): Promise<ResolvedMigrat
const migrations: ResolvedMigration[] = []
for (const entry of migrationEntries) {
const entryName = entry.isDirectory() ? entry.name : removeMigrationScriptExtension(entry.name)
const candidates = resolveMigrationScript(workDir, entryName)
const candidates = resolveMigrationScript(workDir, entryName).filter(isLoadableMigrationScript)

for (const candidate of candidates) {
if (!candidate.mod?.default) {
continue
}

migrations.push({
id: entryName,
migration: candidate.mod.default,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import path from 'node:path'
import type {CliCommandDefinition} from '@sanity/cli'
import {
DEFAULT_MUTATION_CONCURRENCY,
Expand All @@ -15,6 +14,7 @@ import yargs from 'yargs/yargs'
import {debug} from '../../debug'
import {resolveMigrations} from './listMigrationsCommand'
import {prettyFormat} from './prettyMutationFormatter'
import {isLoadableMigrationScript, resolveMigrationScript} from './utils'

const helpText = `
Options
Expand Down Expand Up @@ -43,27 +43,6 @@ interface CreateFlags {
confirm?: boolean
}

const tryExtensions = ['mjs', 'js', 'ts', 'cjs']

function resolveMigrationScript(workDir: string, migrationId: string) {
return [migrationId, path.join(migrationId, 'index')].flatMap((location) =>
tryExtensions.map((ext) => {
const relativePath = path.join('migrations', `${location}.${ext}`)
const absolutePath = path.resolve(workDir, relativePath)
let mod
try {
// eslint-disable-next-line import/no-dynamic-require
mod = require(absolutePath)
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') {
throw new Error(`Error: ${err.message}"`)
}
}
return {relativePath, absolutePath, mod}
}),
)
}

function parseCliFlags(args: {argv?: string[]}) {
return yargs(hideBin(args.argv || process.argv).slice(2))
.options('dry-run', {type: 'boolean', default: true})
Expand Down Expand Up @@ -123,8 +102,7 @@ const runMigrationCommand: CliCommandDefinition<CreateFlags> = {
}

const candidates = resolveMigrationScript(workDir, id)

const resolvedScripts = candidates.filter((candidate) => candidate!.mod?.default)
const resolvedScripts = candidates.filter(isLoadableMigrationScript)

if (resolvedScripts.length > 1) {
// todo: consider prompt user about which one to run? note: it's likely a mistake if multiple files resolve to the same name
Expand All @@ -134,7 +112,9 @@ const runMigrationCommand: CliCommandDefinition<CreateFlags> = {
.join(', ')}`,
)
}
if (resolvedScripts.length === 0) {

const script = resolvedScripts[0]
if (!script) {
throw new Error(
`No migration found for "${id}" in current directory. Make sure that the migration file exists and exports a valid migration as its default export.\n
Tried the following files:\n -${candidates
Expand All @@ -143,9 +123,7 @@ const runMigrationCommand: CliCommandDefinition<CreateFlags> = {
)
}

const script = resolvedScripts[0]!

const mod = script!.mod
const mod = script.mod
if ('up' in mod || 'down' in mod) {
// todo: consider adding support for up/down as separate named exports
// For now, make sure we reserve the names for future use
Expand Down
23 changes: 21 additions & 2 deletions packages/sanity/src/_internal/cli/commands/migration/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path from 'path'
import path from 'node:path'
import {isPlainObject} from 'lodash'
import type {Migration} from '@sanity/migrate'
import {MIGRATION_SCRIPT_EXTENSIONS, MIGRATIONS_DIRECTORY} from './constants'

Expand All @@ -16,7 +17,7 @@ interface ResolvedMigrationScript {
/**
* The migration module, if it could be resolved - otherwise `undefined`
*/
mod?: {default: Migration}
mod?: {default: Migration; up?: unknown; down?: unknown}
}

/**
Expand Down Expand Up @@ -55,3 +56,21 @@ export function resolveMigrationScript(
}),
)
}

/**
* Checks whether or not the passed resolved migration script is actually loadable (eg has a default export)
*
* @param script - The resolved migration script to check
* @returns `true` if the script is loadable, `false` otherwise
* @internal
*/
export function isLoadableMigrationScript(
script: ResolvedMigrationScript,
): script is Required<ResolvedMigrationScript> {
if (typeof script.mod === 'undefined' || !isPlainObject(script.mod.default)) {
return false
}

const mod = script.mod.default
return typeof mod.title === 'string' && mod.migrate !== undefined
}

0 comments on commit 063f8eb

Please sign in to comment.