""" append the nearest parentpath that does not have an __init__.py to sys.path

    uses the file that imported this as the starting path, then starts
    searching the path's parents for an __init__.py* file

    if it finds an __init__.py* in a dir, it walks up to that dir's parents,
    until it finds a dir that doesn't have one, which it then considers to
    be the lib dir and puts on sys.path

    for most packages, this is enough to fix any import issues, as it puts
    the parent of the package dir in the path - however, obviously this
    breaks if a package is placed inside another package that has an
    __init__.py too, so make sure to always place packages in a 'lib' dir
    that doesn't have such an __init__.py or something when using autopath.py!
"""

import os
import sys
import traceback

stack = traceback.extract_stack()
callframe = stack[-2]
dirpath = os.path.dirname(os.path.abspath(callframe[0]))
while 1:
    for ext in ('.py', '.pyc', '.pyo'):
        if os.path.exists(os.path.join(dirpath, '__init__%s' % (ext,))):
            break
    else:
        break
    dirpath = os.path.dirname(dirpath)
sys.path.append(dirpath)


