constraint method

({dynamic name, dynamic version})? constraint(
  1. dynamic name,
  2. dynamic version, {
  3. VersionBump bump = VersionBump.breaking,
  4. bool pin = false,
})

Implementation

({dynamic name, dynamic version})? constraint(
  dynamic name,
  dynamic version, {
  VersionBump bump = VersionBump.breaking,
  bool pin = false,
}) {
  if (name is! String || version is! String) {
    return null;
  }

  Version semVersion;

  final minVersion = RegExp(r'^\^');
  final rangedVersion = RegExp(r'^\>\=?([\d.+-\w]+)');

  final sanitized = switch (version) {
    _ when minVersion.hasMatch(version) => version.replaceFirst('^', ''),
    _ when rangedVersion.hasMatch(version) =>
      rangedVersion.firstMatch(version)?.group(1) ?? version,
    _ => version,
  };

  try {
    semVersion = Version.parse(sanitized);
  } on FormatException {
    return null;
  }

  if (pin) {
    return (name: name, version: semVersion.toString());
  }

  final nextVersion = switch (bump) {
    VersionBump.patch => semVersion.nextPatch,
    VersionBump.minor => semVersion.nextMinor,
    VersionBump.major => semVersion.nextMajor,
    VersionBump.breaking => semVersion.nextBreaking,
  };

  final constraint = '>=$semVersion <$nextVersion';

  return (name: name, version: constraint);
}