"""
:copyright: 2010-2015 by Ronny Pfannschmidt
:license: MIT
"""
import os
from pkg_resources import iter_entry_points


from .utils import do, trace
from .version import format_version, _warn_if_setuptools_outdated


def version_from_scm(root):
    ep = find_matching_entrypoint(root, 'setuptools_scm.parse_scm')
    if ep:
        return ep.load()(root)


def get_version(root='.',
                version_scheme='guess-next-dev',
                local_scheme='node-and-date',
                ):
    root = os.path.abspath(root)
    trace('root', repr(root))

    version = version_from_scm(root)

    if version:
        if isinstance(version, str):
            return version
        return format_version(
            version,
            version_scheme=version_scheme,
            local_scheme=local_scheme)
        return version


def _ovalue(obj, name, default):
    if isinstance(obj, dict):
        return obj.get(name, default)
    else:
        return default


def setuptools_version_keyword(dist, keyword, value):
    _warn_if_setuptools_outdated()
    if not value:
        return
    if value is True:
        value = {}
    if getattr(value, '__call__', None):
        value = value()
    try:
        dist.metadata.version = get_version(**value)
    except Exception as e:
        trace('error', e)


def find_matching_entrypoint(path, entrypoint):
    trace('looking for ep', entrypoint, path)
    for ep in iter_entry_points(entrypoint):
        if os.path.exists(os.path.join(path, ep.name)):
            if os.path.isabs(ep.name):
                trace('ignoring bad ep', ep)
            trace('found ep', ep)
            return ep


def find_files(path='.'):
    if not path:
        path = '.'
    abs = os.path.abspath(path)
    ep = find_matching_entrypoint(abs, 'setuptools_scm.files_command')
    if ep:
        command = ep.load()
        if isinstance(command, str):
            return do(ep.load(), path).splitlines()
        else:
            return command(path)
    else:
        return []

@@ -1851,24 +1851,41 @@
 = ep.load()%0A
+        try:%0A    
         if i
@@ -1901,32 +1901,36 @@
 (command, str):%0A
+    
             retu
@@ -1965,16 +1965,20 @@
 lines()%0A
+    
         
@@ -1991,24 +1991,28 @@
             
+    
 return comma
@@ -2016,24 +2016,193 @@
 mmand(path)%0A
+        except Exception as e:%0A            import traceback%0A            print(%22File Finder Failed for %25s%22 %25 ep)%0A            traceback.print_exc()%0A            return %5B%5D%0A%0A
     else:%0A  
@@ -2201,24 +2201,25 @@
 else:%0A        return %5B%5D%0A
+%0A

print exception on failed/broken file finding, fixes #27