def magic(refresh=None):
    if not imported:
        print("No importmagic. Run 'pip install importmagic'")
        return
    refresh = True if refresh == "!" else False
    current = vim.current.buffer  # or vim.current.range
    text = '\n'.join(current)

    config = vim.eval('g:vim_importmagic_config')
    if not isinstance(config, dict):
        print('g:vim_importmagic_config should be dict, found %s' %
              type(config))
        return

    path = sys.path + [os.getcwd()]

    # XXX indexing takes too long do it async in background!?
    index = importmagic.SymbolIndex()
    index.get_or_create_index(paths=path, refresh=refresh)

    scope = importmagic.Scope.from_source(text)

    unresolved, unreferenced = scope.find_unresolved_and_unreferenced_symbols()
    text_updated = importmagic.update_imports(text, index, unresolved,
                                              unreferenced)
    text_updated = text_updated.split('\n')[:-1]
    current[:] = text_updated
Example #2
0
def fix_imports(project_root):
    if not project_root:
        project_root = os.getcwd()
    index = importmagic.SymbolIndex()
    try:
        with open('.index.json') as fd:
            index = importmagic.SymbolIndex.deserialize(fd)
        print('Index loaded')
    except:
        print('Building index...')
        index.build_index(sys.path + [project_root])
        with open('.index.json', 'w') as fd:
            index.serialize(fd)

    # files = u.matched_files(['*.py'], root_dir=project_root)
    for root, dirs, files in os.walk(project_root):
        for file in files:
            if not file.endswith('.py'):
                continue
            with open(file) as fh:
                py_source = fh.read()
            py_source = fix_imports_in_code(index, py_source)

            with open(file, 'w') as fh:
                fh.write(py_source)
 def create_index(self):
     index = importmagic.SymbolIndex()
     index.build_index(sys.path + [self.cwd])
     with open(self._tmp_index_file, 'w') as fd:
         index.serialize(fd)
     # Prevent multiple access
     if os.path.exists(self._tmp_index_file):
         os.rename(self._tmp_index_file, self.index_file)
Example #4
0
def add_import(files):
    logging.info("add_import:"+str(files))
    path_ = sys.path + [os.getcwd()]
    index = importmagic.SymbolIndex()
    logging.info("add_import: build index")
    index.build_index(paths=path_)
    result=[]
    for file in files:
        filelist_ = filelist(file)
        if(isinstance(filelist_,list)):
            result=result+filelist_
    return get_unresolve.add_import(result,index)
Example #5
0
def _fix_imports(project_root):
    index = importmagic.SymbolIndex()
    name = project_root.split('/')[-1]
    index.get_or_create_index(name=name, paths=[project_root] + sys.path)
    importmagic.Imports(index=index, source=None, root_dir=project_root)

    files = get_files_with_patterns(['*.py'], root=project_root)
    for filename in files:
        with open(filename, 'r') as fh:
            code = fh.read()
        if not code:
            continue
        code = importmagic_fixup(index, code)
        with open(filename, 'w') as fh:
            fh.write(code)
    def method_build_index(self, **kwargs):
        workspace_path = kwargs.get('workspacePath')
        extra_paths = kwargs.get('extraPaths', [])
        skip_test_folders = kwargs.get('skipTestFolders')

        if not workspace_path:
            raise ValueError('Empty workspacePath')

        paths = list(set(extra_paths + [workspace_path] + sys.path))

        if skip_test_folders:
            blacklist_re = importmagic.index.DEFAULT_BLACKLIST_RE
        else:
            blacklist_re = re.compile(r'^$')

        self._index = importmagic.SymbolIndex(blacklist_re=blacklist_re)
        self._index.build_index(paths)

        return dict(success=True)
Example #7
0
def imp_mgc_fixup(project_root):
    index = importmagic.SymbolIndex()
    try:
        print('loading index')
        with open('index.json') as fd:
            index = importmagic.SymbolIndex.deserialize(fd)
    except:
        print('building index')
        index.build_index(sys.path)
        with open('index.json', 'w') as fd:
            index.serialize(fd)

    files = get_files_with_patterns(['*.py'], root=project_root)
    for f in files:
        with open(f, 'w+') as fh:
            py_source = fh.read()
            print(py_source)
            py_source = fix_imports(index, py_source)
            print(py_source)
            fh.write(py_source)
Example #8
0
def _build_index(sys_path=sys.path, user_path=None):
    # since index is a global variable, need the global keyword. I did
    # not know this
    # http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them
    global index
    try:
        paths = []

        if user_path is not None:
            if isinstance(user_path, list):
                paths = paths + user_path
            else:
                paths.append(user_path)

        if isinstance(sys_path, list):
            paths = paths + sys_path
        else:
            paths.append(sys_path)

        index = importmagic.SymbolIndex()
        index.build_index(paths=paths)
    except:
        print('Failed to build index')
        sys.exit(-1)
Example #9
0
 def index(self):
     log.info('Indexing imports')
     self._importmagic_index = importmagic.SymbolIndex()
     self._importmagic_index.build_index(sys.path)
     log.info('Indexing imports done')
 def __init__(self, nvim):
     global g_nvim
     global g_index
     global g_index_built
     g_nvim = nvim
     g_index = importmagic.SymbolIndex()
Example #11
0
    import numpy as np

    import pandas as pd
    from pandas import DataFrame as df

    from PIL import Image, ImageFont, ImageDraw, ImageChops

    from pyflash.core import *

    import redis
    rc = redis.StrictRedis(host='localhost', port=6379, db=0)

    from t import *

    import importmagic
    index = importmagic.SymbolIndex()
    index.get_or_create_index(name='py35', paths=['.'] + sys.path)

except Exception as e:
    print(e)

try:
    exec(open('./scripts/django_shell_plus_init.py').read())
except:
    pass


# utilities

def to_pickle(obj, file='data.pkl'):
    with open(file, 'wb') as fh:
Example #12
0
 def index(self):
     self._importmagic_index = importmagic.SymbolIndex()
     self._importmagic_index.build_index(sys.path)