feat(storage): add "end" method to storage for cleaning up resources when commands are finished

This commit is contained in:
Joakim Carlstein 2023-12-08 13:01:19 +01:00
parent 334e2099bb
commit 703e6f028a
15 changed files with 150 additions and 77 deletions

View file

@ -7,10 +7,12 @@ import {
MissingArgumentsError,
MissingOptionError,
OptionNeededError,
StorageInitError,
} from '../errors.js';
import { type Config } from '../types.js';
import { getMigration } from '../get-migration.js';
import { getDuration } from '../get-duration.js';
import { exec } from '../exec.js';
type ExtraFlags = {
force?: boolean;
@ -37,7 +39,6 @@ export default async function removeCommand(
throw new BadOptionError('storage', 'No storage found, please specify a storage using the storage option');
}
const storage = await storagePlugin.initializeStorage();
const reporter = await getOrLoadReporter([reporterConfig ?? lazyDefaultReporter]);
if (!reporter) {
@ -47,6 +48,16 @@ export default async function removeCommand(
);
}
const [storage, storageError] = await exec(async () => storagePlugin.initializeStorage());
if (storageError) {
await reporter.onFinished?.([], new StorageInitError('Could not initialize storage', { cause: storageError }));
return 1;
}
await reporter.onInit?.({ command: 'remove', cwd, dry: false, directory });
const migrationFile = await getMigration(cwd, directory, name, !force);
const finishedMigrations: MigrationMetadataFinished[] = [];
@ -59,17 +70,15 @@ export default async function removeCommand(
}
if (migrationHistoryEntry.status === 'done' && !force) {
throw new OptionNeededError(
removalError = new OptionNeededError(
'force',
`The migration "${migrationFile.name}" is not in a failed state. Use the "force" option to force its removal`,
);
} else {
historyEntry = migrationHistoryEntry;
}
historyEntry = migrationHistoryEntry;
}
await reporter.onInit?.({ command: 'remove', cwd, dry: false, directory });
await reporter.onMigrationRemoveStart?.(migrationFile);
const start = process.hrtime();
@ -107,4 +116,8 @@ export default async function removeCommand(
}
await reporter.onFinished?.(finishedMigrations, removalError);
await storage.end();
return removalError ? 1 : 0;
}