fix(migrations): don't include folders when collecting migrations

It should be possible to have folders inside your migrations folder
This commit is contained in:
Joakim Carlstein 2024-01-26 09:17:47 +01:00 committed by Joakim Carlstein
parent 9109238b86
commit f1b9098750
3 changed files with 95 additions and 29 deletions

View file

@ -3,37 +3,42 @@ import fs from 'node:fs/promises';
import { type MigrationMetadata } from '@emigrate/types';
import { withLeadingPeriod } from './with-leading-period.js';
import { BadOptionError } from './errors.js';
import { arrayFromAsync } from './array-from-async.js';
export type GetMigrationsFunction = typeof getMigrations;
const tryReadDirectory = async (directoryPath: string): Promise<string[]> => {
async function* tryReadDirectory(directoryPath: string): AsyncIterable<string> {
try {
return await fs.readdir(directoryPath);
for await (const entry of await fs.opendir(directoryPath)) {
if (
entry.isFile() &&
!entry.name.startsWith('.') &&
!entry.name.startsWith('_') &&
path.extname(entry.name) !== ''
) {
yield entry.name;
}
}
} catch {
throw BadOptionError.fromOption('directory', `Couldn't read directory: ${directoryPath}`);
}
};
}
export const getMigrations = async (cwd: string, directory: string): Promise<MigrationMetadata[]> => {
const directoryPath = path.resolve(cwd, directory);
const allFilesInMigrationDirectory = await tryReadDirectory(directoryPath);
const allFilesInMigrationDirectory = await arrayFromAsync(tryReadDirectory(directoryPath));
const migrationFiles: MigrationMetadata[] = allFilesInMigrationDirectory
.filter((name) => !name.startsWith('.') && !name.startsWith('_') && path.extname(name) !== '')
.sort()
.map((name) => {
const filePath = path.join(directoryPath, name);
return allFilesInMigrationDirectory.sort().map((name) => {
const filePath = path.join(directoryPath, name);
return {
name,
filePath,
relativeFilePath: path.relative(cwd, filePath),
extension: withLeadingPeriod(path.extname(name)),
directory,
cwd,
};
});
return migrationFiles;
return {
name,
filePath,
relativeFilePath: path.relative(cwd, filePath),
extension: withLeadingPeriod(path.extname(name)),
directory,
cwd,
} satisfies MigrationMetadata;
});
};