File: util_static.py

package info (click to toggle)
python-line-profiler 4.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 776 kB
  • sloc: python: 3,097; sh: 810; ansic: 65; makefile: 15
file content (597 lines) | stat: -rw-r--r-- 21,562 bytes parent folder | download | duplicates (2)
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
"""
This file was autogenerated based on code in :py:mod:`ubelt` and
:py:mod:`xdoctest` via dev/maintain/port_utilities.py in the
line_profiler repo.
"""
from os.path import abspath
from os.path import dirname
from os.path import exists
from os.path import expanduser
from os.path import relpath
from os.path import splitext
from os.path import basename
from os.path import isdir
from os.path import join
import os
from os.path import split
from os.path import isfile
from os.path import realpath
import sys

# from xdoctest import utils


def package_modpaths(
    pkgpath,
    with_pkg=False,
    with_mod=True,
    followlinks=True,
    recursive=True,
    with_libs=False,
    check=True,
):
    r"""
    Finds sub-packages and sub-modules belonging to a package.

    Args:
        pkgpath (str): path to a module or package
        with_pkg (bool): if True includes package __init__ files (default =
            False)
        with_mod (bool): if True includes module files (default = True)
        exclude (list): ignores any module that matches any of these patterns
        recursive (bool): if False, then only child modules are included
        with_libs (bool): if True then compiled shared libs will be returned as well
        check (bool): if False, then then pkgpath is considered a module even
            if it does not contain an __init__ file.

    Yields:
        str: module names belonging to the package

    References:
        http://stackoverflow.com/questions/1707709/list-modules-in-py-package

    Example:
        >>> from xdoctest.static_analysis import *
        >>> pkgpath = modname_to_modpath('xdoctest')
        >>> paths = list(package_modpaths(pkgpath))
        >>> print('\n'.join(paths))
        >>> names = list(map(modpath_to_modname, paths))
        >>> assert 'xdoctest.core' in names
        >>> assert 'xdoctest.__main__' in names
        >>> assert 'xdoctest' not in names
        >>> print('\n'.join(names))
    """
    if isfile(pkgpath):
        (yield pkgpath)
    else:
        if with_pkg:
            root_path = join(pkgpath, "__init__.py")
            if (not check) or exists(root_path):
                (yield root_path)
        valid_exts = [".py"]
        if with_libs:
            valid_exts += _platform_pylib_exts()
        for dpath, dnames, fnames in os.walk(pkgpath, followlinks=followlinks):
            ispkg = exists(join(dpath, "__init__.py"))
            if ispkg or (not check):
                check = True
                if with_mod:
                    for fname in fnames:
                        if splitext(fname)[1] in valid_exts:
                            if fname != "__init__.py":
                                path = join(dpath, fname)
                                (yield path)
                if with_pkg:
                    for dname in dnames:
                        path = join(dpath, dname, "__init__.py")
                        if exists(path):
                            (yield path)
            else:
                del dnames[:]
            if not recursive:
                break


def _parse_static_node_value(node):
    """
    Extract a constant value from a node if possible
    """
    import ast
    from collections import OrderedDict

    if isinstance(node, ast.Num):
        value = node.n
    elif isinstance(node, ast.Str):
        value = node.s
    elif isinstance(node, ast.List):
        value = list(map(_parse_static_node_value, node.elts))
    elif isinstance(node, ast.Tuple):
        value = tuple(map(_parse_static_node_value, node.elts))
    elif isinstance(node, ast.Dict):
        keys = map(_parse_static_node_value, node.keys)
        values = map(_parse_static_node_value, node.values)
        value = OrderedDict(zip(keys, values))
    elif isinstance(node, ast.NameConstant):
        value = node.value
    else:
        print(node.__dict__)
        raise TypeError(
            """Cannot parse a static value from non-static node of type: {!r}""".format(
                type(node)
            )
        )
    return value


def _extension_module_tags():
    """
    Returns valid tags an extension module might have

    Returns:
        List[str]
    """
    import sysconfig

    tags = []
    tags.append(sysconfig.get_config_var("SOABI"))
    tags.append("abi3")
    tags = [t for t in tags if t]
    return tags


def _static_parse(varname, fpath):
    """
    Statically parse the a constant variable from a python file

    Example:
        >>> # xdoctest: +SKIP("ubelt dependency")
        >>> dpath = ub.Path.appdir('tests/import/staticparse').ensuredir()
        >>> fpath = (dpath / 'foo.py')
        >>> fpath.write_text('a = {1: 2}')
        >>> assert _static_parse('a', fpath) == {1: 2}
        >>> fpath.write_text('a = 2')
        >>> assert _static_parse('a', fpath) == 2
        >>> fpath.write_text('a = "3"')
        >>> assert _static_parse('a', fpath) == "3"
        >>> fpath.write_text('a = ["3", 5, 6]')
        >>> assert _static_parse('a', fpath) == ["3", 5, 6]
        >>> fpath.write_text('a = ("3", 5, 6)')
        >>> assert _static_parse('a', fpath) == ("3", 5, 6)
        >>> fpath.write_text('b = 10' + chr(10) + 'a = None')
        >>> assert _static_parse('a', fpath) is None
        >>> import pytest
        >>> with pytest.raises(TypeError):
        >>>     fpath.write_text('a = list(range(10))')
        >>>     assert _static_parse('a', fpath) is None
        >>> with pytest.raises(AttributeError):
        >>>     fpath.write_text('a = list(range(10))')
        >>>     assert _static_parse('c', fpath) is None
    """
    import ast

    if not exists(fpath):
        raise ValueError("fpath={!r} does not exist".format(fpath))
    with open(fpath, "r") as file_:
        sourcecode = file_.read()
    pt = ast.parse(sourcecode)

    class StaticVisitor(ast.NodeVisitor):
        def visit_Assign(self, node):
            for target in node.targets:
                if getattr(target, "id", None) == varname:
                    self.static_value = _parse_static_node_value(node.value)

        def visit_AnnAssign(self, node):
            if getattr(node.target, "id", None) == varname:
                self.static_value = _parse_static_node_value(node.value)

    visitor = StaticVisitor()
    visitor.visit(pt)
    try:
        value = visitor.static_value
    except AttributeError:
        value = "Unknown {}".format(varname)
        raise AttributeError(value)
    return value


def _platform_pylib_exts():
    """
    Returns .so, .pyd, or .dylib depending on linux, win or mac.
    On python3 return the previous with and without abi (e.g.
    .cpython-35m-x86_64-linux-gnu) flags. On python2 returns with
    and without multiarch.

    Returns:
        tuple
    """
    import sysconfig

    valid_exts = []
    base_ext = "." + sysconfig.get_config_var("EXT_SUFFIX").split(".")[(-1)]
    for tag in _extension_module_tags():
        valid_exts.append((("." + tag) + base_ext))
    valid_exts.append(base_ext)
    return tuple(valid_exts)


def _syspath_modname_to_modpath(modname, sys_path=None, exclude=None):
    """
    syspath version of modname_to_modpath

    Args:
        modname (str): name of module to find

        sys_path (None | List[str | PathLike]):
            The paths to search for the module.
            If unspecified, defaults to ``sys.path``.

        exclude (List[str | PathLike] | None):
            If specified prevents these directories from being searched.
            Defaults to None.

    Returns:
        str: path to the module.

    Note:
        This is much slower than the pkgutil mechanisms.

        There seems to be a change to the editable install mechanism:
        https://github.com/pypa/setuptools/issues/3548
        Trying to find more docs about it.

        TODO: add a test where we make an editable install, regular install,
        standalone install, and check that we always find the right path.

    Example:
        >>> print(_syspath_modname_to_modpath('xdoctest.static_analysis'))
        ...static_analysis.py
        >>> print(_syspath_modname_to_modpath('xdoctest'))
        ...xdoctest
        >>> # xdoctest: +REQUIRES(CPython)
        >>> print(_syspath_modname_to_modpath('_ctypes'))
        ..._ctypes...
        >>> assert _syspath_modname_to_modpath('xdoctest', sys_path=[]) is None
        >>> assert _syspath_modname_to_modpath('xdoctest.static_analysis', sys_path=[]) is None
        >>> assert _syspath_modname_to_modpath('_ctypes', sys_path=[]) is None
        >>> assert _syspath_modname_to_modpath('this', sys_path=[]) is None

    Example:
        >>> # test what happens when the module is not visible in the path
        >>> modname = 'xdoctest.static_analysis'
        >>> modpath = _syspath_modname_to_modpath(modname)
        >>> exclude = [split_modpath(modpath)[0]]
        >>> found = _syspath_modname_to_modpath(modname, exclude=exclude)
        >>> if found is not None:
        >>>     # Note: the basic form of this test may fail if there are
        >>>     # multiple versions of the package installed. Try and fix that.
        >>>     other = split_modpath(found)[0]
        >>>     assert other not in exclude
        >>>     exclude.append(other)
        >>>     found = _syspath_modname_to_modpath(modname, exclude=exclude)
        >>> if found is not None:
        >>>     raise AssertionError(
        >>>         'should not have found {}.'.format(found) +
        >>>         ' because we excluded: {}.'.format(exclude) +
        >>>         ' cwd={} '.format(os.getcwd()) +
        >>>         ' sys.path={} '.format(sys.path)
        >>>     )
    """
    import glob

    def _isvalid(modpath, base):
        subdir = dirname(modpath)
        while subdir and (subdir != base):
            if not exists(join(subdir, "__init__.py")):
                return False
            subdir = dirname(subdir)
        return True

    _fname_we = modname.replace(".", os.path.sep)
    candidate_fnames = [(_fname_we + ".py")]
    candidate_fnames += [(_fname_we + ext) for ext in _platform_pylib_exts()]
    if sys_path is None:
        sys_path = sys.path
    candidate_dpaths = [("." if (p == "") else p) for p in sys_path]
    if exclude:

        def normalize(p):
            if sys.platform.startswith("win32"):
                return realpath(p).lower()
            else:
                return realpath(p)

        real_exclude = {normalize(p) for p in exclude}
        candidate_dpaths = [
            p for p in candidate_dpaths if (normalize(p) not in real_exclude)
        ]

    def check_dpath(dpath):
        modpath = join(dpath, _fname_we)
        if exists(modpath):
            if isfile(join(modpath, "__init__.py")):
                if _isvalid(modpath, dpath):
                    return modpath
        for fname in candidate_fnames:
            modpath = join(dpath, fname)
            if isfile(modpath):
                if _isvalid(modpath, dpath):
                    return modpath

    _pkg_name = _fname_we.split(os.path.sep)[0]
    _pkg_name_hypen = _pkg_name.replace("_", "-")
    _egglink_fname1 = _pkg_name + ".egg-link"
    _egglink_fname2 = _pkg_name_hypen + ".egg-link"
    _editable_fname_pth_pat = ("__editable__." + _pkg_name) + "-*.pth"
    _editable_fname_finder_py_pat = ("__editable___" + _pkg_name) + "_*finder.py"
    found_modpath = None
    for dpath in candidate_dpaths:
        modpath = check_dpath(dpath)
        if modpath:
            found_modpath = modpath
            break
        new_editable_finder_paths = sorted(
            glob.glob(join(dpath, _editable_fname_finder_py_pat))
        )
        if new_editable_finder_paths:
            for finder_fpath in new_editable_finder_paths:
                mapping = _static_parse("MAPPING", finder_fpath)
                try:
                    target = dirname(mapping[_pkg_name])
                except KeyError:
                    ...
                else:
                    if (not exclude) or (normalize(target) not in real_exclude):
                        modpath = check_dpath(target)
                        if modpath:
                            found_modpath = modpath
                            break
            if found_modpath is not None:
                break
        new_editable_pth_paths = sorted(glob.glob(join(dpath, _editable_fname_pth_pat)))
        if new_editable_pth_paths:
            import pathlib

            for editable_pth in new_editable_pth_paths:
                editable_pth = pathlib.Path(editable_pth)
                target = editable_pth.read_text().strip().split("\n")[(-1)]
                if (not exclude) or (normalize(target) not in real_exclude):
                    modpath = check_dpath(target)
                    if modpath:
                        found_modpath = modpath
                        break
            if found_modpath is not None:
                break
        linkpath1 = join(dpath, _egglink_fname1)
        linkpath2 = join(dpath, _egglink_fname2)
        linkpath = None
        if isfile(linkpath1):
            linkpath = linkpath1
        elif isfile(linkpath2):
            linkpath = linkpath2
        if linkpath is not None:
            with open(linkpath, "r") as file:
                target = file.readline().strip()
            if (not exclude) or (normalize(target) not in real_exclude):
                modpath = check_dpath(target)
                if modpath:
                    found_modpath = modpath
                    break
    return found_modpath


def modname_to_modpath(modname, hide_init=True, hide_main=False, sys_path=None):
    """
    Finds the path to a python module from its name.

    Determines the path to a python module without directly import it

    Converts the name of a module (__name__) to the path (__file__) where it is
    located without importing the module. Returns None if the module does not
    exist.

    Args:
        modname (str):
            The name of a module in ``sys_path``.

        hide_init (bool):
            if False, __init__.py will be returned for packages.
            Defaults to True.

        hide_main (bool):
            if False, and ``hide_init`` is True, __main__.py will be returned
            for packages, if it exists. Defaults to False.

        sys_path (None | List[str | PathLike]):
            The paths to search for the module.
            If unspecified, defaults to ``sys.path``.

    Returns:
        str | None:
            modpath - path to the module, or None if it doesn't exist

    Example:
        >>> modname = 'xdoctest.__main__'
        >>> modpath = modname_to_modpath(modname, hide_main=False)
        >>> assert modpath.endswith('__main__.py')
        >>> modname = 'xdoctest'
        >>> modpath = modname_to_modpath(modname, hide_init=False)
        >>> assert modpath.endswith('__init__.py')
        >>> # xdoctest: +REQUIRES(CPython)
        >>> modpath = basename(modname_to_modpath('_ctypes'))
        >>> assert 'ctypes' in modpath
    """
    modpath = _syspath_modname_to_modpath(modname, sys_path)
    if modpath is None:
        return None
    modpath = normalize_modpath(modpath, hide_init=hide_init, hide_main=hide_main)
    return modpath


def split_modpath(modpath, check=True):
    """
    Splits the modpath into the dir that must be in PYTHONPATH for the module
    to be imported and the modulepath relative to this directory.

    Args:
        modpath (str): module filepath
        check (bool): if False, does not raise an error if modpath is a
            directory and does not contain an ``__init__.py`` file.

    Returns:
        Tuple[str, str]: (directory, rel_modpath)

    Raises:
        ValueError: if modpath does not exist or is not a package

    Example:
        >>> from xdoctest import static_analysis
        >>> modpath = static_analysis.__file__.replace('.pyc', '.py')
        >>> modpath = abspath(modpath)
        >>> dpath, rel_modpath = split_modpath(modpath)
        >>> recon = join(dpath, rel_modpath)
        >>> assert recon == modpath
        >>> assert rel_modpath == join('xdoctest', 'static_analysis.py')
    """
    modpath_ = abspath(expanduser(modpath))
    if check:
        if not exists(modpath_):
            if not exists(modpath):
                raise ValueError("modpath={} does not exist".format(modpath))
            raise ValueError("modpath={} is not a module".format(modpath))
        if isdir(modpath_) and (not exists(join(modpath, "__init__.py"))):
            raise ValueError("modpath={} is not a module".format(modpath))
    (full_dpath, fname_ext) = split(modpath_)
    _relmod_parts = [fname_ext]
    dpath = full_dpath
    while exists(join(dpath, "__init__.py")):
        (dpath, dname) = split(dpath)
        _relmod_parts.append(dname)
    relmod_parts = _relmod_parts[::(-1)]
    rel_modpath = os.path.sep.join(relmod_parts)
    return (dpath, rel_modpath)


def normalize_modpath(modpath, hide_init=True, hide_main=False):
    """
    Normalizes __init__ and __main__ paths.

    Args:
        modpath (str | PathLike):
            path to a module

        hide_init (bool):
            if True, always return package modules as __init__.py files
            otherwise always return the dpath. Defaults to True.

        hide_main (bool):
            if True, always strip away main files otherwise ignore __main__.py.
            Defaults to False.

    Returns:
        str | PathLike: a normalized path to the module

    Note:
        Adds __init__ if reasonable, but only removes __main__ by default

    Example:
        >>> from xdoctest import static_analysis as module
        >>> modpath = module.__file__
        >>> assert normalize_modpath(modpath) == modpath.replace('.pyc', '.py')
        >>> dpath = dirname(modpath)
        >>> res0 = normalize_modpath(dpath, hide_init=0, hide_main=0)
        >>> res1 = normalize_modpath(dpath, hide_init=0, hide_main=1)
        >>> res2 = normalize_modpath(dpath, hide_init=1, hide_main=0)
        >>> res3 = normalize_modpath(dpath, hide_init=1, hide_main=1)
        >>> assert res0.endswith('__init__.py')
        >>> assert res1.endswith('__init__.py')
        >>> assert not res2.endswith('.py')
        >>> assert not res3.endswith('.py')
    """
    if hide_init:
        if basename(modpath) == "__init__.py":
            modpath = dirname(modpath)
            hide_main = True
    else:
        modpath_with_init = join(modpath, "__init__.py")
        if exists(modpath_with_init):
            modpath = modpath_with_init
    if hide_main:
        if basename(modpath) == "__main__.py":
            parallel_init = join(dirname(modpath), "__init__.py")
            if exists(parallel_init):
                modpath = dirname(modpath)
    return modpath


def modpath_to_modname(
    modpath, hide_init=True, hide_main=False, check=True, relativeto=None
):
    """
    Determines importable name from file path

    Converts the path to a module (__file__) to the importable python name
    (__name__) without importing the module.

    The filename is converted to a module name, and parent directories are
    recursively included until a directory without an __init__.py file is
    encountered.

    Args:
        modpath (str): module filepath
        hide_init (bool, default=True): removes the __init__ suffix
        hide_main (bool, default=False): removes the __main__ suffix
        check (bool, default=True): if False, does not raise an error if
            modpath is a dir and does not contain an __init__ file.
        relativeto (str | None, default=None): if specified, all checks are ignored
            and this is considered the path to the root module.

    TODO:
        - [ ] Does this need modification to support PEP 420?
              https://www.python.org/dev/peps/pep-0420/

    Returns:
        str: modname

    Raises:
        ValueError: if check is True and the path does not exist

    Example:
        >>> from xdoctest import static_analysis
        >>> modpath = static_analysis.__file__.replace('.pyc', '.py')
        >>> modpath = modpath.replace('.pyc', '.py')
        >>> modname = modpath_to_modname(modpath)
        >>> assert modname == 'xdoctest.static_analysis'

    Example:
        >>> import xdoctest
        >>> assert modpath_to_modname(xdoctest.__file__.replace('.pyc', '.py')) == 'xdoctest'
        >>> assert modpath_to_modname(dirname(xdoctest.__file__.replace('.pyc', '.py'))) == 'xdoctest'

    Example:
        >>> # xdoctest: +REQUIRES(CPython)
        >>> modpath = modname_to_modpath('_ctypes')
        >>> modname = modpath_to_modname(modpath)
        >>> assert modname == '_ctypes'

    Example:
        >>> modpath = '/foo/libfoobar.linux-x86_64-3.6.so'
        >>> modname = modpath_to_modname(modpath, check=False)
        >>> assert modname == 'libfoobar'
    """
    if check and (relativeto is None):
        if not exists(modpath):
            raise ValueError("modpath={} does not exist".format(modpath))
    modpath_ = abspath(expanduser(modpath))
    modpath_ = normalize_modpath(modpath_, hide_init=hide_init, hide_main=hide_main)
    if relativeto:
        dpath = dirname(abspath(expanduser(relativeto)))
        rel_modpath = relpath(modpath_, dpath)
    else:
        (dpath, rel_modpath) = split_modpath(modpath_, check=check)
    modname = splitext(rel_modpath)[0]
    if "." in modname:
        (modname, abi_tag) = modname.split(".", 1)
    modname = modname.replace("/", ".")
    modname = modname.replace("\\", ".")
    return modname