#!/usr/bin/env python

"""
Rebuilds the .circleci/config.yml file based on the output of ``tox --listenvs``
"""

import jinja2
import subprocess as sp

template = jinja2.Template("""\
# !!! WARNING !!!
# This file is automatically generated by ../rebuild-circleci-yaml
# !!! WARNING !!!
version: 2.1

jobs:
  {% for (tox_env, python_ver) in env_list: %}
  # !!! WARNING !!!
  # This file is automatically generated by ../rebuild-circleci-yaml
  # !!! WARNING !!!

  test-{{ tox_env }}:
    docker:
      {% if python_ver == "pypy" -%}
      - image: pypy:2
      {%- else -%}
      - image: python:{{ python_ver }}
      {%- endif %}
    steps:
      - checkout
      - run:
          name: install tox
          command: pip install tox==3.7.0
      - run:
          name: run tests
          command: tox -e {{ tox_env }}
  {% endfor %}

workflows:
  main:
    jobs:
      {% for (tox_env, _) in env_list: -%}
      - test-{{ tox_env }}
      {% endfor -%}

# !!! WARNING !!!
# This file is automatically generated by ../rebuild-circleci-yaml
# !!! WARNING !!!
""")

# Maps tox python versions (ex, "py27") to Travis Python versions (ex, "2.7")
py_version_map = {
    "py26": "2.6",
    "py27": "2.7",
    "py35": "3.5",
    "py36": "3.6",
    "py37": "3.7",
    "py38": "3.8",
    "py39": "3.9-rc",
    "pypy": "pypy",
}

def main():
    env_list_str = sp.check_output("tox --listenvs", shell=True).splitlines()
    env_list = []
    for env in env_list_str:
        if not env.strip():
            continue
        py_ver, _, _ = env.partition("-")
        env_list.append((env, py_version_map[py_ver]))

    with open(".circleci/config.yml", "w") as f:
        f.write(template.render(env_list=env_list))


if __name__ == "__main__":
    main()
