using System;
using System.CommandLine;
using Microsoft.Extensions.Logging;
using Migrato.Cli;
using Migrato.Core;
using Migrato.Sqlite;
using Spectre.Console;
namespace Migrato.Cli.Commands;
///
/// Reverts the most recently applied migration
///
internal static class DownCommand
{
public static Command Build()
{
var command = new Command("down", "Reverts the most recently applied migration")
{
MigrationOptions.Dir,
MigrationOptions.Db,
MigrationOptions.Verbose
};
command.SetAction(parseResult =>
{
var dir = parseResult.GetValue(MigrationOptions.Dir)!;
var db = parseResult.GetValue(MigrationOptions.Db)!;
var verbose = parseResult.GetValue(MigrationOptions.Verbose);
try
{
var migrations = MigrationLoader.LoadFromDirectory(dir);
IMigrationProvider provider = new SqliteMigrationProvider();
using var connection = provider.CreateConnection(db);
using var loggerFactory = Logging.CreateFactory(verbose);
var runner = new MigrationRunner(provider, loggerFactory.CreateLogger());
var reverted = runner.MigrateDown(connection, migrations);
if (reverted is null)
{
AnsiConsole.MarkupLine("[yellow]No applied migrations to revert.[/]");
return 0;
}
AnsiConsole.MarkupLineInterpolated($"[green]Reverted[/] {reverted.Version}_{reverted.Name}");
return 0;
}
catch (Exception ex)
{
AnsiConsole.MarkupLineInterpolated($"[red]Error:[/] {ex.Message}");
return 1;
}
});
return command;
}
}