1
0
forked from VimPlug/jedi

Start using pathlib.Path instead of all the os.path functions

This commit is contained in:
Dave Halter
2020-07-10 17:30:36 +02:00
parent 92af043906
commit db0e90763b
12 changed files with 97 additions and 104 deletions

View File

@@ -7,9 +7,9 @@ flexibility to define sys paths and Python interpreters for a project,
Projects can be saved to disk and loaded again, to allow project definitions to
be used across repositories.
"""
import os
import errno
import json
from pathlib import Path
from itertools import chain
from jedi import debug
from jedi.api.environment import get_cached_default_environment, create_environment
@@ -22,7 +22,6 @@ from jedi.inference.sys_path import discover_buildout_paths
from jedi.inference.cache import inference_state_as_method_param_cache
from jedi.inference.references import recurse_find_python_folders_and_files, search_in_file_ios
from jedi.file_io import FolderIO
from jedi.common import traverse_parents
_CONFIG_FOLDER = '.jedi'
_CONTAINS_POTENTIAL_PROJECT = \
@@ -67,11 +66,11 @@ class Project(object):
@staticmethod
def _get_config_folder_path(base_path):
return os.path.join(base_path, _CONFIG_FOLDER)
return base_path.joinpath(_CONFIG_FOLDER)
@staticmethod
def _get_json_path(base_path):
return os.path.join(Project._get_config_folder_path(base_path), 'project.json')
return Project._get_config_folder_path(base_path).joinpath('project.json')
@classmethod
def load(cls, path):
@@ -100,12 +99,7 @@ class Project(object):
data.pop('_django', None) # TODO make django setting public?
data = {k.lstrip('_'): v for k, v in data.items()}
# TODO when dropping Python 2 use pathlib.Path.mkdir(parents=True, exist_ok=True)
try:
os.makedirs(self._get_config_folder_path(self._path))
except OSError as e:
if e.errno != errno.EEXIST:
raise
self._path.mkdir(parents=True, exist_ok=True)
with open(self._get_json_path(self._path), 'w') as f:
return json.dump((_SERIALIZER_VERSION, data), f)
@@ -130,7 +124,9 @@ class Project(object):
"""
def py2_comp(path, environment_path=None, load_unsafe_extensions=False,
sys_path=None, added_sys_path=(), smart_sys_path=True):
self._path = os.path.abspath(path)
if isinstance(path, str):
path = Path(path).absolute()
self._path = path
self._environment_path = environment_path
self._sys_path = sys_path
@@ -174,23 +170,27 @@ class Project(object):
sys_path = list(self._sys_path)
if self._smart_sys_path:
prefixed.append(self._path)
prefixed.append(str(self._path))
if inference_state.script_path is not None:
suffixed += discover_buildout_paths(inference_state, inference_state.script_path)
suffixed += discover_buildout_paths(
inference_state,
inference_state.script_path
)
if add_parent_paths:
# Collect directories in upward search by:
# 1. Skipping directories with __init__.py
# 2. Stopping immediately when above self._path
traversed = []
for parent_path in traverse_parents(inference_state.script_path):
if parent_path == self._path or not parent_path.startswith(self._path):
for parent_path in inference_state.script_path.parents:
if parent_path == self._path \
or self._path not in parent_path.parents:
break
if not add_init_paths \
and os.path.isfile(os.path.join(parent_path, "__init__.py")):
and parent_path.joinpath("__init__.py").is_file():
continue
traversed.append(parent_path)
traversed.append(str(parent_path))
# AFAIK some libraries have imports like `foo.foo.bar`, which
# leads to the conclusion to by default prefer longer paths
@@ -198,7 +198,7 @@ class Project(object):
suffixed += reversed(traversed)
if self._django:
prefixed.append(self._path)
prefixed.append(str(self._path))
path = prefixed + sys_path + suffixed
return list(_remove_duplicates_from_path(path))
@@ -259,7 +259,7 @@ class Project(object):
name = wanted_names[0]
stub_folder_name = name + '-stubs'
ios = recurse_find_python_folders_and_files(FolderIO(self._path))
ios = recurse_find_python_folders_and_files(FolderIO(str(self._path)))
file_ios = []
# 1. Search for modules in the current project
@@ -280,8 +280,7 @@ class Project(object):
continue
else:
file_ios.append(file_io)
file_name = os.path.basename(file_io.path)
if file_name in (name + '.py', name + '.pyi'):
if Path(file_io.path).name in (name + '.py', name + '.pyi'):
m = load_module_from_path(inference_state, file_io).as_context()
else:
continue
@@ -318,7 +317,7 @@ class Project(object):
p for p in self._get_sys_path(inference_state)
# Exclude folders that are handled by recursing of the Python
# folders.
if not p.startswith(self._path)
if not p.startswith(str(self._path))
]
names = list(iter_module_names(inference_state, empty_module_context, sys_path))
yield from search_in_module(
@@ -337,7 +336,7 @@ class Project(object):
def _is_potential_project(path):
for name in _CONTAINS_POTENTIAL_PROJECT:
if os.path.exists(os.path.join(path, name)):
if path.joinpath(name).exists():
return True
return False
@@ -345,7 +344,7 @@ def _is_potential_project(path):
def _is_django_path(directory):
""" Detects the path of the very well known Django library (if used) """
try:
with open(os.path.join(directory, 'manage.py'), 'rb') as f:
with open(directory.joinpath('manage.py'), 'rb') as f:
return b"DJANGO_SETTINGS_MODULE" in f.read()
except (FileNotFoundError, IsADirectoryError, PermissionError):
return False
@@ -362,12 +361,12 @@ def get_default_project(path=None):
``requirements.txt`` and ``MANIFEST.in``.
"""
if path is None:
path = os.getcwd()
path = Path.cwd()
check = os.path.realpath(path)
check = path.absolute()
probable_path = None
first_no_init_file = None
for dir in traverse_parents(check, include_current=True):
for dir in chain([check], check.parents):
try:
return Project.load(dir)
except (FileNotFoundError, IsADirectoryError, PermissionError):
@@ -376,7 +375,7 @@ def get_default_project(path=None):
continue
if first_no_init_file is None:
if os.path.exists(os.path.join(dir, '__init__.py')):
if dir.joinpath('__init__.py').exists():
# In the case that a __init__.py exists, it's in 99% just a
# Python package and the project sits at least one level above.
continue
@@ -398,7 +397,7 @@ def get_default_project(path=None):
if first_no_init_file is not None:
return Project(first_no_init_file)
curdir = path if os.path.isdir(path) else os.path.dirname(path)
curdir = path if path.is_dir() else path.parent
return Project(curdir)