File: knowledge.py

package info (click to toggle)
python-scooby 0.10.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 352 kB
  • sloc: python: 864; makefile: 33
file content (219 lines) | stat: -rw-r--r-- 5,585 bytes parent folder | download
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
"""
The knowledge base.

Knowledge
=========

It contains, for instance, known odd locations of version information for
particular modules (``VERSION_ATTRIBUTES``, ``VERSION_METHODS``)

"""

import os
import sys
import sysconfig
from typing import Callable, Dict, List, Literal, Set, Tuple, Union

PACKAGE_ALIASES = {
    'vtkmodules': 'vtk',
    'vtkmodules.all': 'vtk',
}

# Define unusual version locations
VERSION_ATTRIBUTES = {
    'PyQt5': 'Qt.PYQT_VERSION_STR',
    'sip': 'SIP_VERSION_STR',
}


def get_pyqt5_version() -> str:
    """Return the PyQt5 version."""
    try:
        from PyQt5.Qt import PYQT_VERSION_STR
    except ImportError:
        return 'Version unknown'

    return PYQT_VERSION_STR


VERSION_METHODS: Dict[str, Callable[[], str]] = {
    'PyQt5': get_pyqt5_version,
}


# Check the environments
def in_ipython() -> bool:
    """Check if we are in a IPython environment.

    Returns
    -------
    bool : True
        ``True`` when in an IPython environment.
    """
    try:
        __IPYTHON__
        return True
    except NameError:
        return False


def in_ipykernel() -> bool:
    """Check if in a ipykernel (most likely Jupyter) environment.

    Warning
    -------
    There is no way to tell if the code is being executed in a notebook
    (Jupyter Notebook or Jupyter Lab) or a kernel is used but executed in a
    QtConsole, or in an IPython console, or any other frontend GUI. However, if
    `in_ipykernel` returns True, you are most likely in a Jupyter Notebook/Lab,
    just keep it in mind that there are other possibilities.

    Returns
    -------
    bool : True if using an ipykernel
    """
    ipykernel = False
    if in_ipython():
        try:
            ipykernel: bool = type(get_ipython()).__module__.startswith('ipykernel.')
        except NameError:
            pass
    return ipykernel


def get_standard_lib_modules() -> Set[str]:
    """Return a set of the names of all modules in the standard library."""
    site_path = sysconfig.get_path('stdlib')
    if getattr(sys, 'frozen', False):  # within pyinstaller
        lib_path = os.path.join(site_path, '..')
        if os.path.isdir(lib_path):
            names = os.listdir(lib_path)
        else:
            names = []

        stdlib_pkgs = {name[:-3] for name in names if name.endswith(".py")}

    else:
        names = os.listdir(site_path)

        stdlib_pkgs = set([name if not name.endswith(".py") else name[:-3] for name in names])

    stdlib_pkgs = {
        "python",
        "sys",
        "__builtin__",
        "__builtins__",
        "builtins",
        "session",
        "math",
        "itertools",
        "binascii",
        "array",
        "atexit",
        "fcntl",
        "errno",
        "gc",
        "time",
        "unicodedata",
        "mmap",
    }.union(stdlib_pkgs)
    return stdlib_pkgs


def version_tuple(v: str) -> Tuple[int, ...]:
    """Convert a version string to a tuple containing ints.

    Non-numeric version strings will be converted to 0.  For example:
    ``'0.28.0dev0'`` will be converted to ``'0.28.0'``

    Returns
    -------
    ver_tuple : tuple
        Length 3 tuple representing the major, minor, and patch
        version.
    """
    split_v = v.split(".")
    while len(split_v) < 3:
        split_v.append('0')

    if len(split_v) > 3:
        raise ValueError('Version strings containing more than three parts ' 'cannot be parsed')

    vals: List[int] = []
    for item in split_v:
        if item.isnumeric():
            vals.append(int(item))
        else:
            vals.append(0)

    return tuple(vals)


def meets_version(version: str, meets: str) -> bool:
    """Check if a version string meets a minimum version.

    This is a simplified way to compare version strings. For a more robust
    tool, please check out the ``packaging`` library:

    https://github.com/pypa/packaging

    Parameters
    ----------
    version : str
        Version string.  For example ``'0.25.1'``.

    meets : str
        Version string.  For example ``'0.25.2'``.

    Returns
    -------
    newer : bool
        True if version ``version`` is greater or equal to version ``meets``.

    Examples
    --------
    >>> meets_version('0.25.1', '0.25.2')
    False

    >>> meets_version('0.26.0', '0.25.2')
    True
    """
    va = version_tuple(version)
    vb = version_tuple(meets)

    if len(va) != len(vb):
        raise AssertionError("Versions are not comparable.")

    for i in range(len(va)):
        if va[i] > vb[i]:
            return True
        elif va[i] < vb[i]:
            return False

    # Arrived here if same version
    return True


def get_filesystem_type() -> Union[str, Literal[False]]:
    """Get the type of the file system at the path of the scooby package."""
    try:
        import psutil  # lazy-load see PR#85
    except ImportError:
        psutil = False
    from pathlib import Path  # lazy-load see PR#85
    import platform  # lazy-load see PR#85

    # Skip Windows due to https://github.com/banesullivan/scooby/issues/75
    fs_type: Union[str, Literal[False]]
    if psutil and platform.system() != 'Windows':
        # Code by https://stackoverflow.com/a/35291824/10504481
        my_path = str(Path(__file__).resolve())
        best_match = ""
        fs_type = ""
        for part in psutil.disk_partitions():
            if my_path.startswith(part.mountpoint) and len(best_match) < len(part.mountpoint):
                fs_type = part.fstype
                best_match = part.mountpoint
    else:
        fs_type = False
    return fs_type