Skip to content

suggestion(semver): Parse python versions #6828

@justinmchase

Description

@justinmchase

Python versions don't actually conform to semantic versioning and if you have a need to parse them then using this library can be difficult.

I wrote a little helper which could theoretically be integrated into this library if you wanted to be flexible with the parsing. I will put it here just in case.

function parse(versionString: string) {
  // Python version documentation:
  // https://peps.python.org/pep-0440/#public-version-identifiers
  //
  // supports converting _most_ python versions into common semver
  // [N!]N(.N)*[{a|b|rc}N][.postN][.devN]
  //
  // | example      | result        |
  // | ------------ | ------------- |
  // | 0.13.1a0     | 0.13.1-a.0    |
  // | 0.13.1b0     | 0.13.1-b.0    |
  // | 0.13.1rc0    | 0.13.1-rc.0   |
  // | 0.13.1.dev0  | 0.13.1-dev.0  |
  // | 0.13.1.post0 | 0.13.1-post.0 |
  //
  const py = versionString.match(
    /^(\d+)[.](\d+)[.](\d+)[.]?(a|b|rc|dev|post)(\d+)$/,
  );
  if (py) {
    const [, major, minor, patch, pre, dev] = py;
    versionString = `${major}.${minor}.${patch}-${pre}.${dev}`;
  }

  // supports converting partial versions such as 1, 1.0 into valid semantic versions.
  if (versionString.match(/^\d+$/)) {
    versionString = `${versionString}.0.0`;
  } else if (versionString.match(/^\d+[.]\d+$/)) {
    versionString = `${versionString}.0`;
  }
  
  return semver.parse(versionString);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions