using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
namespace Migrato.Core;
///
/// Loads and orders the migrations found in a directory
///
public static class MigrationLoader
{
///
/// Parses every "*.sql" file in and returns them ordered by version
///
/// does not exist
/// A file is malformed, or two files share the same version
public static IReadOnlyList LoadFromDirectory(string directory)
{
if (!Directory.Exists(directory))
{
throw new DirectoryNotFoundException($"Migrations directory '{directory}' does not exist");
}
var migrations = Directory.EnumerateFiles(directory, "*.sql")
.Select(MigrationParser.Parse)
.OrderBy(m => m.Version)
.ToList();
var duplicate = migrations
.GroupBy(m => m.Version)
.FirstOrDefault(g => g.Count() > 1);
return duplicate is not null ?
throw new MigrationFormatException($"Multiple migration files share version {duplicate.Key}")
: migrations;
}
}