MigrationId.parse constructor

MigrationId.parse(
  1. String value
)

Implementation

factory MigrationId.parse(String value) {
  // Strip "m_" prefix if present (new format)
  var normalized = value;
  if (value.startsWith('m_')) {
    normalized = value.substring(2);
  }

  // New format: m_YYYYMMDDHHMMSS_slug
  // Old format: YYYY_MM_DD_HHMMSS_slug (for backward compatibility)

  // Check if it's the new format (14 consecutive digits followed by underscore)
  final newFormatMatch = RegExp(r'^(\d{14})_(.+)$').firstMatch(normalized);
  if (newFormatMatch != null) {
    final timestampStr = newFormatMatch.group(1)!;
    final slug = newFormatMatch.group(2)!;

    final year = int.tryParse(timestampStr.substring(0, 4));
    final month = int.tryParse(timestampStr.substring(4, 6));
    final day = int.tryParse(timestampStr.substring(6, 8));
    final hour = int.tryParse(timestampStr.substring(8, 10));
    final minute = int.tryParse(timestampStr.substring(10, 12));
    final second = int.tryParse(timestampStr.substring(12, 14));

    if (year == null ||
        month == null ||
        day == null ||
        hour == null ||
        minute == null ||
        second == null) {
      throw FormatException('Invalid migration timestamp in "$value".');
    }

    final timestamp = DateTime.utc(year, month, day, hour, minute, second);
    return MigrationId(timestamp, slug);
  }

  // Fall back to old format: YYYY_MM_DD_HHMMSS_slug
  final segments = normalized.split('_');
  if (segments.length < 5) {
    throw FormatException(
      'Invalid migration id "$value". Expected m_YYYYMMDDHHMMSS_slug or YYYY_MM_DD_HHMMSS_slug format.',
    );
  }

  final year = int.tryParse(segments[0]);
  final month = int.tryParse(segments[1]);
  final day = int.tryParse(segments[2]);
  final time = segments[3];

  if (year == null || month == null || day == null || time.length != 6) {
    throw FormatException('Invalid migration timestamp in "$value".');
  }

  final hour = int.tryParse(time.substring(0, 2));
  final minute = int.tryParse(time.substring(2, 4));
  final second = int.tryParse(time.substring(4, 6));

  if (hour == null || minute == null || second == null) {
    throw FormatException('Invalid migration time in "$value".');
  }

  final timestamp = DateTime.utc(year, month, day, hour, minute, second);
  final slug = segments.sublist(4).join('_');

  return MigrationId(timestamp, slug);
}