from setuptools import setup, Command


class Requirements(Command):
    """
    Externalize requirements so that you are able to install e.g. from conda install --file
    """

    description = "Installs the foo."
    user_options = [
        ("extra=", None, "Extra to add to requirements"),
    ]

    def initialize_options(self):
        self.extra = None

    def finalize_options(self):
        # assert self.foo in (None, 'myFoo', 'myFoo2'), 'Invalid foo!'
        pass

    def run(self):
        self.externalize(self.extra)

    def externalize(self, extra=None):
        import configparser
        import os

        config = configparser.ConfigParser()
        config.read("setup.cfg")
        deps = config["options"]["install_requires"].split("\n")
        if extra is not None:
            deps = config["options.extras_require"][extra].split("\n")
        deps = [x for x in deps if x]
        head = (
            "# Autogenerated by Makefile from setup.cfg install_requies section."
            "Remove this line if you want to fix this file."
        )
        path = "requirements.txt"
        f = open(path, "r") if os.path.exists(path) else None
        line = f.readline() if f else ""
        if f and not line.startswith(head[:20]):
            quit("User defined requirements already existing.")
        f = open("requirements.txt", "w")
        f.write("\n".join([head] + deps))


setup(
    version="0.3.6",
    cmdclass={
        "requirements": Requirements,
    },
)
