name: get-latest-version
description: "Get the latest version of a package."
inputs:
  versions:
    description: "Newline-seperated list of package versions."
    required: true
  filter:
    description: "String to filter by."
    required: false
  filterIsExpression:
    description: "Is the first filter a Regular Expression? Values: true, false."
    required: false
    default: "false"
  stripPrerelease:
    description: "Whether or not to strip prerelease versions. Values: true, false."
    required: false
    default: "false"
outputs:
  version:
    description: "The latest version of the specified package."
    value: ${{ steps.parse.outputs.version }}
runs:
  using: "composite"
  steps:
  - name: "Get latest package."
    id: parse
    run: |
      VERSIONS="${{ inputs.versions }}"
      # Filter versions, sort them, and get the latest one
      if [[ "${{ inputs.filterIsExpression }}" == "true" ]]; then
        EXPRESSION_FLAG="-E"
      fi
      if [[ "${{ inputs.stripPrerelease }}" == "true" ]]; then
        VERSIONS=$(echo "$VERSIONS" | grep -E "^(v)?[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?$")
      fi
      RESULT=$(echo "$VERSIONS" | grep $EXPRESSION_FLAG "${{ inputs.filter }}" || echo "error")

      VERSION=$(echo "$RESULT" | sort -rV | head -1)
      
      if [[ "$RESULT" != "error" ]]; then
        echo "version=$VERSION" >> "$GITHUB_OUTPUT"
      fi
      # No error if no versions found.
    shell: bash