summaryrefslogtreecommitdiff
path: root/isort/finders.py
blob: 259ddbb487519057a05a061975347def4f7741c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
"""Finders try to find right section for passed module name"""
import importlib.machinery
import inspect
import os
import os.path
import re
import sys
import sysconfig
from abc import ABCMeta, abstractmethod
from fnmatch import fnmatch
from functools import lru_cache
from glob import glob
from typing import Dict, Iterable, Iterator, List, Optional, Pattern, Sequence, Tuple, Type

from . import sections
from .settings import Config
from .utils import chdir, exists_case_sensitive

try:
    from pipreqs import pipreqs

except ImportError:
    pipreqs = None

try:
    from pip_api import parse_requirements

except ImportError:
    parse_requirements = None

try:
    from requirementslib import Pipfile

except ImportError:
    Pipfile = None

KNOWN_SECTION_MAPPING: Dict[str, str] = {
    sections.STDLIB: "STANDARD_LIBRARY",
    sections.FUTURE: "FUTURE_LIBRARY",
    sections.FIRSTPARTY: "FIRST_PARTY",
    sections.THIRDPARTY: "THIRD_PARTY",
}


class BaseFinder(metaclass=ABCMeta):
    def __init__(self, config: Config) -> None:
        self.config = config

    @abstractmethod
    def find(self, module_name: str) -> Optional[str]:
        raise NotImplementedError


class ForcedSeparateFinder(BaseFinder):
    def find(self, module_name: str) -> Optional[str]:
        for forced_separate in self.config.forced_separate:
            # Ensure all forced_separate patterns will match to end of string
            path_glob = forced_separate
            if not forced_separate.endswith("*"):
                path_glob = "%s*" % forced_separate

            if fnmatch(module_name, path_glob) or fnmatch(module_name, "." + path_glob):
                return forced_separate
        return None


class LocalFinder(BaseFinder):
    def find(self, module_name: str) -> Optional[str]:
        if module_name.startswith("."):
            return "LOCALFOLDER"
        return None


class KnownPatternFinder(BaseFinder):
    def __init__(self, config: Config) -> None:
        super().__init__(config)

        self.known_patterns: List[Tuple[Pattern[str], str]] = []
        for placement in reversed(config.sections):
            known_placement = KNOWN_SECTION_MAPPING.get(placement, placement).lower()
            config_key = f"known_{known_placement}"
            known_patterns = list(
                getattr(self.config, config_key, self.config.known_other.get(known_placement, []))
            )
            known_patterns = [
                pattern
                for known_pattern in known_patterns
                for pattern in self._parse_known_pattern(known_pattern)
            ]
            for known_pattern in known_patterns:
                regexp = "^" + known_pattern.replace("*", ".*").replace("?", ".?") + "$"
                self.known_patterns.append((re.compile(regexp), placement))

    def _parse_known_pattern(self, pattern: str) -> List[str]:
        """Expand pattern if identified as a directory and return found sub packages"""
        if pattern.endswith(os.path.sep):
            patterns = [
                filename
                for filename in os.listdir(pattern)
                if os.path.isdir(os.path.join(pattern, filename))
            ]
        else:
            patterns = [pattern]

        return patterns

    def find(self, module_name: str) -> Optional[str]:
        # Try to find most specific placement instruction match (if any)
        parts = module_name.split(".")
        module_names_to_check = (".".join(parts[:first_k]) for first_k in range(len(parts), 0, -1))
        for module_name_to_check in module_names_to_check:
            for pattern, placement in self.known_patterns:
                if pattern.match(module_name_to_check):
                    return placement
        return None


class PathFinder(BaseFinder):
    def __init__(self, config: Config) -> None:
        super().__init__(config)

        # restore the original import path (i.e. not the path to bin/isort)
        root_dir = os.getcwd()
        src_dir = f"{root_dir}/src"
        self.paths = [root_dir, src_dir]

        # virtual env
        self.virtual_env = self.config.virtual_env or os.environ.get("VIRTUAL_ENV")
        if self.virtual_env:
            self.virtual_env = os.path.realpath(self.virtual_env)
        self.virtual_env_src = ""
        if self.virtual_env:
            self.virtual_env_src = f"{self.virtual_env}/src/"
            for path in glob(f"{self.virtual_env}/lib/python*/site-packages"):
                if path not in self.paths:
                    self.paths.append(path)
            for path in glob(f"{self.virtual_env}/lib/python*/*/site-packages"):
                if path not in self.paths:
                    self.paths.append(path)
            for path in glob(f"{self.virtual_env}/src/*"):
                if os.path.isdir(path):
                    self.paths.append(path)

        # conda
        self.conda_env = self.config.conda_env or os.environ.get("CONDA_PREFIX") or ""
        if self.conda_env:
            self.conda_env = os.path.realpath(self.conda_env)
            for path in glob(f"{self.conda_env}/lib/python*/site-packages"):
                if path not in self.paths:
                    self.paths.append(path)
            for path in glob(f"{self.conda_env}/lib/python*/*/site-packages"):
                if path not in self.paths:
                    self.paths.append(path)

        # handle case-insensitive paths on windows
        self.stdlib_lib_prefix = os.path.normcase(sysconfig.get_paths()["stdlib"])
        if self.stdlib_lib_prefix not in self.paths:
            self.paths.append(self.stdlib_lib_prefix)

        # add system paths
        for path in sys.path[1:]:
            if path not in self.paths:
                self.paths.append(path)

    def find(self, module_name: str) -> Optional[str]:
        for prefix in self.paths:
            package_path = "/".join((prefix, module_name.split(".")[0]))
            is_module = (
                exists_case_sensitive(package_path + ".py")
                or any(
                    exists_case_sensitive(package_path + ext_suffix)
                    for ext_suffix in importlib.machinery.EXTENSION_SUFFIXES
                )
                or exists_case_sensitive(package_path + "/__init__.py")
            )
            is_package = exists_case_sensitive(package_path) and os.path.isdir(package_path)
            if is_module or is_package:
                if "site-packages" in prefix:
                    return sections.THIRDPARTY
                if "dist-packages" in prefix:
                    return sections.THIRDPARTY
                if self.virtual_env and self.virtual_env_src in prefix:
                    return sections.THIRDPARTY
                if os.path.normcase(prefix) == self.stdlib_lib_prefix:
                    return sections.STDLIB
                if self.conda_env and self.conda_env in prefix:
                    return sections.THIRDPARTY
                if os.path.normcase(prefix).startswith(self.stdlib_lib_prefix):
                    return sections.STDLIB
                return self.config.default_section
        return None


class ReqsBaseFinder(BaseFinder):
    enabled = False

    def __init__(self, config: Config, path: str = ".") -> None:
        super().__init__(config)
        self.path = path
        if self.enabled:
            self.mapping = self._load_mapping()
            self.names = self._load_names()

    @abstractmethod
    def _get_names(self, path: str) -> Iterator[str]:
        raise NotImplementedError

    @abstractmethod
    def _get_files_from_dir(self, path: str) -> Iterator[str]:
        raise NotImplementedError

    @staticmethod
    def _load_mapping() -> Optional[Dict[str, str]]:
        """Return list of mappings `package_name -> module_name`

        Example:
            django-haystack -> haystack
        """
        if not pipreqs:
            return None
        path = os.path.dirname(inspect.getfile(pipreqs))
        path = os.path.join(path, "mapping")
        with open(path) as f:
            mappings: Dict[str, str] = {}  # pypi_name: import_name
            for line in f:
                import_name, _, pypi_name = line.strip().partition(":")
                mappings[pypi_name] = import_name
            return mappings
            # return dict(tuple(line.strip().split(":")[::-1]) for line in f)

    def _load_names(self) -> List[str]:
        """Return list of thirdparty modules from requirements"""
        names = []
        for path in self._get_files():
            for name in self._get_names(path):
                names.append(self._normalize_name(name))
        return names

    @staticmethod
    def _get_parents(path: str) -> Iterator[str]:
        prev = ""
        while path != prev:
            prev = path
            yield path
            path = os.path.dirname(path)

    def _get_files(self) -> Iterator[str]:
        """Return paths to all requirements files"""
        path = os.path.abspath(self.path)
        if os.path.isfile(path):
            path = os.path.dirname(path)

        for path in self._get_parents(path):
            yield from self._get_files_from_dir(path)

    def _normalize_name(self, name: str) -> str:
        """Convert package name to module name

        Examples:
            Django -> django
            django-haystack -> django_haystack
            Flask-RESTFul -> flask_restful
        """
        if self.mapping:
            name = self.mapping.get(name, name)
        return name.lower().replace("-", "_")

    def find(self, module_name: str) -> Optional[str]:
        # required lib not installed yet
        if not self.enabled:
            return None

        module_name, _sep, _submodules = module_name.partition(".")
        module_name = module_name.lower()
        if not module_name:
            return None

        for name in self.names:
            if module_name == name:
                return sections.THIRDPARTY
        return None


class RequirementsFinder(ReqsBaseFinder):
    exts = (".txt", ".in")
    enabled = bool(parse_requirements)

    def _get_files_from_dir(self, path: str) -> Iterator[str]:
        """Return paths to requirements files from passed dir."""
        yield from self._get_files_from_dir_cached(path)

    @classmethod
    @lru_cache(maxsize=16)
    def _get_files_from_dir_cached(cls, path: str) -> List[str]:
        results = []

        for fname in os.listdir(path):
            if "requirements" not in fname:
                continue
            full_path = os.path.join(path, fname)

            # *requirements*/*.{txt,in}
            if os.path.isdir(full_path):
                for subfile_name in os.listdir(full_path):
                    for ext in cls.exts:
                        if subfile_name.endswith(ext):
                            results.append(os.path.join(full_path, subfile_name))
                continue

            # *requirements*.{txt,in}
            if os.path.isfile(full_path):
                for ext in cls.exts:
                    if fname.endswith(ext):
                        results.append(full_path)
                        break

        return results

    def _get_names(self, path: str) -> Iterator[str]:
        """Load required packages from path to requirements file"""
        yield from self._get_names_cached(path)

    @classmethod
    @lru_cache(maxsize=16)
    def _get_names_cached(cls, path: str) -> List[str]:
        result = []

        with chdir(os.path.dirname(path)):
            requirements = parse_requirements(path)
            for req in requirements.values():
                if req.name:
                    result.append(req.name)

        return result


class PipfileFinder(ReqsBaseFinder):
    enabled = bool(Pipfile)

    def _get_names(self, path: str) -> Iterator[str]:
        with chdir(path):
            project = Pipfile.load(path)
            for req in project.packages:
                yield req.name

    def _get_files_from_dir(self, path: str) -> Iterator[str]:
        if "Pipfile" in os.listdir(path):
            yield path


class DefaultFinder(BaseFinder):
    def find(self, module_name: str) -> Optional[str]:
        return self.config.default_section


class FindersManager:
    _default_finders_classes: Sequence[Type[BaseFinder]] = (
        ForcedSeparateFinder,
        LocalFinder,
        KnownPatternFinder,
        PathFinder,
        PipfileFinder,
        RequirementsFinder,
        DefaultFinder,
    )

    def __init__(
        self, config: Config, finder_classes: Optional[Iterable[Type[BaseFinder]]] = None
    ) -> None:
        self.verbose: bool = config.verbose

        if finder_classes is None:
            finder_classes = self._default_finders_classes
        finders: List[BaseFinder] = []
        for finder_cls in finder_classes:
            try:
                finders.append(finder_cls(config))
            except Exception as exception:
                # if one finder fails to instantiate isort can continue using the rest
                if self.verbose:
                    print(
                        (
                            f"{finder_cls.__name__} encountered an error ({exception}) during "
                            "instantiation and cannot be used"
                        )
                    )
        self.finders: Tuple[BaseFinder, ...] = tuple(finders)

    def find(self, module_name: str) -> Optional[str]:
        for finder in self.finders:
            try:
                section = finder.find(module_name)
            except Exception as exception:
                # isort has to be able to keep trying to identify the correct
                # import section even if one approach fails
                if self.verbose:
                    print(
                        f"{finder.__class__.__name__} encountered an error ({exception}) while "
                        f"trying to identify the {module_name} module"
                    )
            if section is not None:
                return section
        return None