Ejemplo n.º 1
0
    def jedi_script(self, position=None):
        extra_paths = []
        environment_path = None

        if self._config:
            jedi_settings = self._config.plugin_settings('jedi', document_path=self.path)
            environment_path = jedi_settings.get('environment')
            extra_paths = jedi_settings.get('extra_paths') or []

        environment = self.get_enviroment(environment_path) if environment_path else None
        sys_path = self.sys_path(environment_path) + extra_paths
        project_path = self._workspace.root_path

        kwargs = {
            'code': self.source,
            'path': self.path,
            'environment': environment,
            'project': jedi.Project(path=project_path, sys_path=sys_path),
        }

        if position:
            # Deprecated by Jedi to use in Script() constructor
            kwargs += _utils.position_to_jedi_linecolumn(self, position)

        return jedi.Script(**kwargs)
Ejemplo n.º 2
0
def get_project():
    try:
        vim_environment_path = vim_eval("b:jedi_environment_path")
    except VimError:
        vim_environment_path = ""

    if vim_environment_path in ("", None):
        vim_environment_path = vim_eval("g:jedi#environment_path")
    vim_project_path = vim_eval("g:jedi#project_path")
    vim_added_sys_path = vim_eval("g:jedi#added_sys_path")

    global _current_project_cache
    cache_key = dict(project_path=vim_project_path,
                     environment_path=vim_environment_path)
    if cache_key == _current_project_cache[0]:
        return _current_project_cache[1]

    if vim_environment_path in ("auto", "", None):
        environment_path = None
    else:
        environment_path = vim_environment_path

    if vim_project_path in ("auto", "", None):
        project_path = jedi.get_default_project().path
    else:
        project_path = vim_project_path

    project = jedi.Project(project_path,
                           environment_path=environment_path,
                           added_sys_path=vim_added_sys_path)

    _current_project_cache = cache_key, project
    return project
Ejemplo n.º 3
0
def test_rename_mod(Script, dir_with_content):
    script = Script(
        'import modx; modx\n',
        path=os.path.join(dir_with_content, 'some_script.py'),
        project=jedi.Project(dir_with_content),
    )
    refactoring = script.rename(line=1, new_name='modr')
    refactoring.apply()

    p1 = os.path.join(dir_with_content, 'modx.py')
    p2 = os.path.join(dir_with_content, 'modr.py')
    expected_code = 'import modr\nfoo\n'
    assert not os.path.exists(p1)
    with open(p2, newline='') as f:
        assert f.read() == expected_code

    assert refactoring.get_renames() == [(p1, p2)]

    assert refactoring.get_changed_files()[p1].get_new_code() == expected_code

    assert refactoring.get_diff() == dedent('''\
        rename from modx.py
        rename to modr.py
        --- modx.py
        +++ modr.py
        @@ -1,3 +1,3 @@
        -import modx
        +import modr
         foo
        --- some_script.py
        +++ some_script.py
        @@ -1,2 +1,2 @@
        -import modx; modx
        +import modr; modr
        ''').format(dir=dir_with_content)
Ejemplo n.º 4
0
def get_project():
    vim_environment_path = vim_eval(
        "get(b:, 'jedi_environment_path', g:jedi#environment_path)")
    vim_project_path = vim_eval("g:jedi#project_path")

    vim_added_sys_path = vim_eval("get(g:, 'jedi#added_sys_path', [])")
    vim_added_sys_path += vim_eval("get(b:, 'jedi_added_sys_path', [])")

    global _current_project_cache
    cache_key = dict(project_path=vim_project_path,
                     environment_path=vim_environment_path,
                     added_sys_path=vim_added_sys_path)
    if cache_key == _current_project_cache[0]:
        return _current_project_cache[1]

    if vim_environment_path in ("auto", "", None):
        environment_path = None
    else:
        environment_path = vim_environment_path

    if vim_project_path in ("auto", "", None):
        project_path = jedi.get_default_project().path
    else:
        project_path = vim_project_path

    project = jedi.Project(project_path,
                           environment_path=environment_path,
                           added_sys_path=vim_added_sys_path)

    _current_project_cache = cache_key, project
    return project
Ejemplo n.º 5
0
 def refactor(self, environment):
     project = jedi.Project(os.path.join(test_dir, 'refactor'))
     script = jedi.Script(self._code,
                          path=self._path,
                          project=project,
                          environment=environment)
     refactor_func = getattr(script, self.refactor_type)
     return refactor_func(self._line_nr, self._index, **self._kwargs)
Ejemplo n.º 6
0
    def get_completions(self, loc):
        """
           Overridden method.
           Returns a list of completion objects for GPS.
        """

        # this works only on Python files
        if loc.buffer().file().language() != "python":
            return []

        # check if the current char can belong to an identifier
        current_char = loc.forward_char(-1).get_char()
        if not (current_char and
                (current_char in ['_', '.'] or current_char.isalnum())):
            return []

        # We can't rely on sys.path and must create a jedi.Project see
        # extract from the online doc below:
        #    If project is provided with a sys_path, that is going to be used.
        #    If environment is provided, its sys.path will be used
        #    (see Environment.get_sys_path);
        #    Otherwise sys.path will match that of the default environment of
        #    Jedi, which typically matches the sys path that was used at the
        #    time when Jedi was imported.

        self.source_dirs.update([loc.buffer().file().directory()])
        project = jedi.Project(None,
                               sys_path=sys.path + list(self.source_dirs))

        try:
            # filter out ^L in source text
            text = loc.buffer().get_chars()
            # text = text.replace('\x0c', ' ')
            # Feed Jedi API
            script = jedi.Script(code=text, project=project)
            completions = script.complete(line=loc.line(),
                                          column=loc.column() - 1)

            # Sort, filter results
            result = sorted((CompletionProposal(
                name=i.name,
                label=i.name,
                documentation=i.docstring(),
                language_category=TYPE_LABELS.get(
                    i.type, completion.CAT_UNKNOWN))
                for i in completions
                if i.name.startswith(self.__prefix)),
                key=lambda d: d.name)
        except:
            jedi_log = GPS.Logger("JEDI_PARSING")
            jedi_log.log("jedi fails to parse:" +
                         loc.buffer().file().path)
            result = []

        return result
def test_sub_module(Script, jedi_path):
    """
    ``full_name needs to check sys.path to actually find it's real path module
    path.
    """
    sys_path = [jedi_path]
    project = jedi.Project('.', sys_path=sys_path)
    defs = Script('from jedi.api import classes; classes',
                  project=project).infer()
    assert [d.full_name for d in defs] == ['jedi.api.classes']
    defs = Script('import jedi.api; jedi.api', project=project).infer()
    assert [d.full_name for d in defs] == ['jedi.api']
Ejemplo n.º 8
0
def test_follow_definition_nested_import(Script):
    Script = partial(Script,
                     project=jedi.Project(
                         join(test_dir, 'completion', 'import_tree')))
    types = check_follow_definition_types(Script, "import pkg.mod1; pkg")
    assert types == ['module']

    types = check_follow_definition_types(Script, "import pkg.mod1; pkg.mod1")
    assert types == ['module']

    types = check_follow_definition_types(Script,
                                          "import pkg.mod1; pkg.mod1.a")
    assert types == ['instance']
Ejemplo n.º 9
0
def jedi_try_autocomplete_with_folder(content, line, position, folderName):
    result = []
    try:
        script = jedi.Script(code=content, project=jedi.Project(folderName))
        completions = script.complete(line=line, column=position)
    except:
        completions = []
    for completion in completions:
        result.append({
            'append_type': 'no_space',
            'complete': completion.complete,
            'name_with_symbols': completion.name_with_symbols
        })
    return result
Ejemplo n.º 10
0
def test_completion_docstring(Script, jedi_path):
    """
    Jedi should follow imports in certain conditions
    """
    def docstr(src, result):
        c = Script(src, project=project).complete()[0]
        assert c.docstring(raw=True, fast=False) == cleandoc(result)

    project = jedi.Project('.', sys_path=[jedi_path])
    c = Script('import jedi\njed', project=project).complete()[0]
    assert c.docstring(fast=False) == cleandoc(jedi_doc)

    docstr('import jedi\njedi.Scr', cleandoc(jedi.Script.__doc__))

    docstr('abcd=3;abcd', '')
    docstr('"hello"\nabcd=3\nabcd', '')
    docstr(
        dedent('''
        def x():
            "hello"
            0
        x'''),
        'hello'
    )
    docstr(
        dedent('''
        def x():
            "hello";0
        x'''),
        'hello'
    )
    # Shouldn't work with a tuple.
    docstr(
        dedent('''
        def x():
            "hello",0
        x'''),
        ''
    )
    # Should also not work if we rename something.
    docstr(
        dedent('''
        def x():
            "hello"
        y = x
        y'''),
        ''
    )
Ejemplo n.º 11
0
    def __init__(self, project_path, settings):
        """Prepare to call daemon.

        :type settings: dict
        """
        environment_path = (settings.get('python_interpreter')
                            or settings.get('python_virtualenv') or None)

        self.project = jedi.Project(
            project_path,
            environment_path=environment_path,
            added_sys_path=settings.get('extra_packages') or [],
        )

        # how to autocomplete arguments
        self.complete_funcargs = settings.get('complete_funcargs')
Ejemplo n.º 12
0
 def __init__(
     self,
     root_dir: str,
 ) -> None:
     self.root_dir = root_dir
     self.project = jedi.Project(path=root_dir)
     # cache the actual codes as lines
     # this cache is very useful as there will be unsaved changes
     self.content_cache: Dict[str, Sequence[str]] = {}
     # script path -> Jedi script
     self.jedi_scripts_by_path: Dict[str, Script] = {}
     # script path -> ParsedClass list of the script
     self.parsed_names_by_path: Dict[str, Sequence[ParsedClass]] = {}
     # class full name -> ParsedClass
     self.parsed_name_by_full_name: Dict[str, ParsedClass] = {}
     # set of the outdated scripts' path
     self.outdated_scripts: Set[str] = set()
Ejemplo n.º 13
0
 def __init__(self,
              test_type,
              correct,
              line_nr,
              column,
              start,
              line,
              path=None,
              skip_version_info=None):
     super().__init__(skip_version_info)
     self.test_type = test_type
     self.correct = correct
     self.line_nr = line_nr
     self.column = column
     self.start = start
     self.line = line
     self.path = path
     self._project = jedi.Project(test_dir)
Ejemplo n.º 14
0
    def load_prj(self):
        nodes = prj_man.global_project_info.get('nodes')
        if not nodes:
            return
        fn = ct.ed.get_filename()

        if fn == self.fn and [x for x in nodes if x in self.nodes]:
            return
        else:
            self.nodes = nodes
            self.fn = fn

        prj_fn = prj_man.global_project_info['filename']
        if os.path.isfile(fn):
            for n in nodes:
                if n in fn:
                    if os.path.exists(prj_fn):
                        fn = prj_fn
                    break
            fpath = os.path.dirname(fn)
        else:
            if os.path.exists(prj_fn):
                fpath = os.path.dirname(prj_fn)
            else:
                fpath = None

        prj_sys_path = []
        if os.path.isfile(self.fn):
            prj_sys_path.append(os.path.dirname(self.fn))
        prj_sys_path.extend(sys.path)
        for n in nodes:
            if os.path.isdir(n):
                prj_sys_path.append(n)
            elif os.path.isfile(n):
                prj_sys_path.append(os.path.dirname(n))

        # only for me
        stubs_dir = os.path.join(ct.app_path(ct.APP_DIR_PY), 'cuda_stubs_builder', 'stubs')
        if os.path.exists(stubs_dir):
            prj_sys_path.append(stubs_dir)

        self.app.project = jedi.Project(
            path=fpath,
            added_sys_path=prj_sys_path)
Ejemplo n.º 15
0
def single_file_extraction(file_name, top_dir):
    from jedi.cache import clear_time_caches
    import jedi

    symbols_dict = {}
    errors_dict = {}
    # TODO: check for `__init__.py` existence or that the file is top level
    folder_path = file_name.rpartition(top_dir + "/")[-1]
    import_name = file_path_to_import(folder_path)
    module_import = import_name.split(".")[0]
    try:
        data = jedi.Script(path=file_name,
                           project=jedi.Project("".join(top_dir))).complete()
    except Exception as e:
        print(import_name, str(e))
        errors_dict[import_name] = {
            "exception": str(e),
            "traceback": str(traceback.format_exc()).split("\n", ),
        }
        data = []

    symbols_from_script = {
        k.full_name: k.type
        for k in data
        # Checks that the symbol has a name and comes from the pkg in question
        if k.full_name and module_import + "." in k.full_name
    }

    # cull statements within functions and classes, which are not importable
    classes_and_functions = {
        k
        for k, v in symbols_from_script.items() if v in ["class", "function"]
    }
    for k in list(symbols_from_script):
        for cf in classes_and_functions:
            if k != cf and k.startswith(cf) and k in symbols_from_script:
                symbols_from_script.pop(k)

    symbols_dict[import_name] = set(symbols_from_script)
    del data
    del symbols_from_script
    clear_time_caches(True)
    return symbols_dict, errors_dict
Ejemplo n.º 16
0
def load_project():
    path = vim.eval('a:args')
    vim.vars['jedi#project_path'] = path
    env_path = vim_eval("g:jedi#environment_path")
    if env_path == 'auto':
        env_path = None
    if path:
        try:
            project = jedi.Project.load(path)
        except FileNotFoundError:
            project = jedi.Project(path, environment_path=env_path)
            project.save()
    else:
        project = jedi.get_default_project()
        path = project.path
        project.save()

    global _current_project_cache
    cache_key = dict(project_path=path, environment_path=env_path)
    _current_project_cache = cache_key, project
Ejemplo n.º 17
0
    def jedi_script(self, position=None, use_document_path=False):
        extra_paths = []
        environment_path = None
        env_vars = None

        if self._config:
            jedi_settings = self._config.plugin_settings(
                'jedi', document_path=self.path)
            environment_path = jedi_settings.get('environment')
            extra_paths = jedi_settings.get('extra_paths') or []
            env_vars = jedi_settings.get('env_vars')

        # Drop PYTHONPATH from env_vars before creating the environment because that makes
        # Jedi throw an error.
        if env_vars is None:
            env_vars = os.environ.copy()
        env_vars.pop('PYTHONPATH', None)

        environment = self.get_enviroment(
            environment_path, env_vars=env_vars) if environment_path else None
        sys_path = self.sys_path(environment_path,
                                 env_vars=env_vars) + extra_paths
        project_path = self._workspace.root_path

        # Extend sys_path with document's path if requested
        if use_document_path:
            sys_path += [os.path.normpath(os.path.dirname(self.path))]

        kwargs = {
            'code': self.source,
            'path': self.path,
            'environment': environment,
            'project': jedi.Project(path=project_path, sys_path=sys_path),
        }

        if position:
            # Deprecated by Jedi to use in Script() constructor
            kwargs += _utils.position_to_jedi_linecolumn(self, position)

        return jedi.Script(**kwargs)
Ejemplo n.º 18
0
def test_init_extension_module(Script, load_unsafe_extensions):
    """
    ``__init__`` extension modules are also packages and Jedi should understand
    that.

    Originally coming from #472.

    This test was built by the module.c and setup.py combination you can find
    in the init_extension_module folder. You can easily build the
    `__init__.cpython-38m.so` by compiling it (create a virtualenv and run
    `setup.py install`.

    This is also why this test only runs on certain systems and Python 3.8.
    """

    project = jedi.Project(get_example_dir(),
                           load_unsafe_extensions=load_unsafe_extensions)
    s = jedi.Script(
        'import init_extension_module as i\ni.',
        path='not_existing.py',
        project=project,
    )
    if load_unsafe_extensions:
        assert 'foo' in [c.name for c in s.complete()]
    else:
        assert 'foo' not in [c.name for c in s.complete()]

    s = jedi.Script(
        'from init_extension_module import foo\nfoo',
        path='not_existing.py',
        project=project,
    )
    c, = s.complete()
    assert c.name == 'foo'
    if load_unsafe_extensions:
        assert c.infer()
    else:
        assert not c.infer()
Ejemplo n.º 19
0
    def _GetJediProject(self, request_data, environment):
        settings = {'sys_path': []}
        settings.update(self._SettingsForRequest(request_data))
        settings['interpreter_path'] = environment.executable
        settings['sys_path'].extend(environment.get_sys_path())

        filepath = request_data['filepath']
        module = extra_conf_store.ModuleForSourceFile(filepath)
        # We don't warn the user if no extra conf file is found.
        if module:
            if hasattr(module, 'PythonSysPath'):
                settings['sys_path'] = module.PythonSysPath(**settings)
            LOGGER.debug('No PythonSysPath function defined in %s',
                         module.__file__)

        project_directory = settings.get('project_directory')
        if not project_directory:
            default_project = jedi.get_default_project(
                os.path.dirname(request_data['filepath']))
            project_directory = default_project._path
        return jedi.Project(project_directory,
                            sys_path=settings['sys_path'],
                            environment_path=settings['interpreter_path'])
Ejemplo n.º 20
0
def test_pyc(pyc_project_path, environment, load_unsafe_extensions):
    """
    The list of completion must be greater than 2.
    """
    path = os.path.join(pyc_project_path, 'blub.py')
    if not isinstance(environment, InterpreterEnvironment):
        # We are using the same version for pyc completions here, because it
        # was compiled in that version. However with interpreter environments
        # we also have the same version and it's easier to debug.
        environment = SameEnvironment()
    environment = environment
    project = jedi.Project(pyc_project_path,
                           load_unsafe_extensions=load_unsafe_extensions)
    s = jedi.Script(
        "from dummy_package import dummy; dummy.",
        path=path,
        environment=environment,
        project=project,
    )
    if load_unsafe_extensions:
        assert len(s.complete()) >= 2
    else:
        assert not s.complete()
Ejemplo n.º 21
0
def ScriptWithProject(Script):
    project = jedi.Project(test_dir)
    return partial(jedi.Script, project=project)