#!/usr/bin/env python
"""
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""

def scan_pyx(lines):
    """
    Scan Cython source for depended-on modules.

    @return: Names of depended-on modules.
    """

    # sage uses the following regex; we don't (yet):
    # re.compile(r"^ *(?:(?:cimport +([\w\. ,]+))|(?:from +([\w.]+)"
    #            r" +cimport)|(?:include *[\'"]([^\'"]+)[\'"])|(?:cdef"
    #            r" *extern *from *[\'"]([^\'"]+)[\'"]))", re.M)

    # build the relevant regex
    from re import compile

    expressions = [
        # FIXME doesn't work with "cimport module1, module2..."
        # FIXME doesn't work with include directives
        # FIXME doesn't work with "cdef extern from..."
        compile("\\s*from\\s+([A-Za-z_.]+)\\s+cimport\\s+.+"),
        compile("\\s*cimport\\s+([A-Za-z_.]+)"),
        ]

    # get the raw module names
    modules = []

    for line in lines:
        for e in expressions:
            m = e.match(line)

            if m:
                modules += m.groups()

                break

    return modules

def find_module(name, include_paths):
    """
    Find the path to a depended-on module.
    """

    from os.path import (
        join,
        exists,
        )

    module_name = "%s.pxd" % name.replace(".", "/")

    for include_path in include_paths:
        possible_path = join(include_path, module_name)

        if exists(possible_path):
            return possible_path

    return None

def write_depends(depends, output_file):
    """
    Write a CMake file containing dependency information.
    """

    output_file.write("set(\n    scanned\n")

    for path in depends:
        if path is not None:
            output_file.write("    \"%s\"\n" % path)

    output_file.write("    )\n")

def scan_pyx_depends(source_path, output_path, *include_paths):
    """
    Scan a Cython source file for dependencies to pass to CMake.
    """

    with open(source_path) as f:
        module_names = scan_pyx(f.readlines())

    module_paths = [find_module(m, include_paths) for m in module_names]

    if output_path is None:
        from sys import stdout

        write_depends(module_paths, stdout)
    else:
        with open(output_path, "w") as f:
            write_depends(module_paths, f)

if __name__ == "__main__":
    from sys import argv

    scan_pyx_depends(*argv[1:])

