File: misc.py

package info (click to toggle)
python-tatsu 5.17.1%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,516 kB
  • sloc: python: 13,185; makefile: 127
file content (47 lines) | stat: -rw-r--r-- 1,005 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
# Copyright (c) 2017-2026 Juancarlo AƱez (apalala@gmail.com)
# SPDX-License-Identifier: BSD-4-Clause
from __future__ import annotations

import importlib.util
import re
import shutil
from functools import cache
from pathlib import Path

from .itertools import first  # bwcompat

__all__ = [
    'first',
    'cached_re_compile',
    'module_available',
    'module_missing',
    'platform_has_command',
]


@cache
def cached_re_compile(
    pattern: str | bytes | re.Pattern,
    /,
    flags: int = 0,
) -> re.Pattern:
    if isinstance(pattern, re.Pattern):
        return pattern
    pattern = str(pattern)
    return re.compile(pattern, flags=flags)


def module_available(name):
    return importlib.util.find_spec(name) is not None


def module_missing(name):
    return not module_available(name)


def platform_has_command(name) -> bool:
    return shutil.which(name) is not None


def pathtomodulename(path: Path):
    return str(path.with_suffix('')).replace('/', '.').replace('.__init__', '')