# -*- coding: utf-8 -*-
# milieu - Environment variables manager
#
# Copyright (c) 2013  Yipit, Inc <coders@yipit.com>
# Copyright (c) 2013-2014  Lincoln Clarete <lincoln@clarete.li>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals
from setuptools import setup, find_packages

import ast
import os
import re


PACKAGE = 'milieu'


class VersionFinder(ast.NodeVisitor):
    """Reads the value of the  variable __version__ of an AST tree.

    Take a look in the `read_version()` function below. It uses this
    class with the parsed AST tree from PACKAGE/version.py instead of
    trying to read that dynamically.
    """
    def __init__(self):
        self.version = None

    def visit_Assign(self, node):
        if node.targets[0].id == '__version__':
            self.version = node.value.s


def read_version():
    """Read version from package/version.py without loading any files"""
    finder = VersionFinder()
    finder.visit(ast.parse(local_file(PACKAGE, 'version.py')))
    return finder.version


def parse_requirements():
    """Rudimentary parser for the `requirements.txt` file

    We just want to separate regular packages from links to pass them to the
    `install_requires` and `dependency_links` params of the `setup()`
    function properly.
    """
    try:
        requirements = \
            map(str.strip, local_file('requirements.txt').splitlines())
    except IOError:
        raise RuntimeError("Couldn't find the `requirements.txt' file :(")

    links = []
    pkgs = []
    for req in requirements:
        if not req:
            continue
        if 'http:' in req or 'https:' in req:
            links.append(req)
            name, version = re.findall("\#egg=([^\-]+)-(.+$)", req)[0]
            pkgs.append('{0}=={1}'.format(name, version))
        else:
            pkgs.append(req)

    return pkgs, links


local_file = lambda *f: \
    open(os.path.join(os.path.dirname(__file__), *f)).read()


install_requires, dependency_links = parse_requirements()


if __name__ == '__main__':
    setup(
        name=PACKAGE,
        version=read_version(),
        description=(
            "A helping hand to manage your settings among "
            "different environments"),
        long_description=local_file('README.md'),
        author=u'Lincoln de Sousa',
        author_email=u'lincoln@clarete.li',
        url='https://github.com/Yipit/milieu',
        packages=find_packages(exclude=['*tests*']),
        install_requires=install_requires,
        dependency_links=dependency_links,
    )
