name: "Set up python and conda environment"
description:
  "This action creates a conda environment containing a given python version
  and set of requirements. It caches the environment and restores it from
  the cache when possible to minimize execution time. It uses a cache key
  that includes the runner OS and architecture, python version, hash of all
  requirements, and the number of the week in the year, so that the cache
  refreshes weekly."
inputs:
  python-version:
    description: "Python version to install"
    required: true
  requirements-files:
    description:
      "List of requirements files to install from. May be separated by spaces
      and/or newlines."
    required: false
    default: ""
  requirements:
    description:
      "List of conda packages to install. May be separated by spaces and/or
      newlines."
    required: false
    default: ""
runs:
  using: "composite"
  steps:
    # set up python that's used below to run convert-requirements-to-conda-yml.py
    # after the environment is updated, 'python' will point to the
    # conda-managed python and this python won't be used again
    - name: Set up python
      uses: actions/setup-python@v4
      with:
        python-version: ${{ inputs.python-version }}

    # save week number to use in next step
    # save CONDA_PREFIX to GITHUB_ENV so it's accessible outside of shell commands
    - name: Set environment variables
      shell: bash -l {0} # need login shell so that CONDA_PREFIX is set
      run: |
        echo "WEEK=$(date +%U)" >> $GITHUB_ENV
        echo "CONDA_PREFIX=$CONDA_PREFIX" >> $GITHUB_ENV

    - name: Copy requirements into file
      shell: bash
      run: |
        # make sure each package is separated by a newline
        echo "python=${{ inputs.python-version }}" > extra_requirements.txt
        echo "${{ inputs.requirements }}" | xargs | tr " " "\n" >> extra_requirements.txt

    - name: Combine all requirements into environment YML
      shell: bash
      run: |
        # make sure each file is separated by a space
        REQUIREMENTS_FILES=$(echo "${{ inputs.requirements-files }}" | xargs | tr "\n" " ")
        python ./scripts/convert-requirements-to-conda-yml.py \
          extra_requirements.txt $REQUIREMENTS_FILES \
        > environment.yml
        echo "Will update environment using this environment.yml:"
        cat environment.yml

    - name: Setup conda environment
      uses: mamba-org/setup-micromamba@v1
      with:
        environment-file: environment.yml
        environment-name: env
        condarc: |
              channels:
                - conda-forge
        init-shell: bash
        cache-environment: true
        cache-environment-key: ${{ runner.os }}${{ runner.arch }}-${{ env.WEEK }}-${{ hashFiles('environment.yml') }}

    - name: List conda environment
      shell: bash -l {0}
      run: micromamba list
