summaryrefslogtreecommitdiff
path: root/isort/utils.py
blob: 0f6f57bf84c6c625ee80c6e777c071c543fddcce (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
import os
import sys
from contextlib import contextmanager
from typing import Any, Container, Iterable, Iterator, List


def exists_case_sensitive(path: str) -> bool:
    """
    Returns if the given path exists and also matches the case on Windows.

    When finding files that can be imported, it is important for the cases to match because while
    file os.path.exists("module.py") and os.path.exists("MODULE.py") both return True on Windows, Python
    can only import using the case of the real file.
    """
    result = os.path.exists(path)
    if (sys.platform.startswith('win') or sys.platform == 'darwin') and result:
        directory, basename = os.path.split(path)
        result = basename in os.listdir(directory)
    return result


@contextmanager
def chdir(path: str) -> Iterator[None]:
    """Context manager for changing dir and restoring previous workdir after exit.
    """
    curdir = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(curdir)


def union(a: Iterable[Any], b: Iterable[Any]) -> List[Any]:
    """ Return a list of items that are in `a` or `b`
    """
    u = []  # type: List[Any]
    for item in a:
        if item not in u:
            u.append(item)
    for item in b:
        if item not in u:
            u.append(item)
    return u


def difference(a: Iterable[Any], b: Container[Any]) -> List[Any]:
    """ Return a list of items from `a` that are not in `b`.
    """
    d = []
    for item in a:
        if item not in b:
            d.append(item)
    return d


def infer_line_separator(file_contents: str) -> str:
    if '\r\n' in file_contents:
        return '\r\n'
    elif '\r' in file_contents:
        return '\r'
    else:
        return '\n'