Skip to content

envglobals

Class info

🛈 DocStrings

add

add(text: str | None, prefix: str = '', suffix: str = '') -> str

Add a pre- or suffix to a value if the value is true-ish.

Parameters:

Name Type Description Default
text str | None

The text to check

required
prefix str

Prefix to add if text is true-ish

''
suffix str

Suffix to add if text is true-ish

''
Source code in src/jinjarope/envglobals.py
68
69
70
71
72
73
74
75
76
def add(text: str | None, prefix: str = "", suffix: str = "") -> str:
    """Add a pre- or suffix to a value if the value is true-ish.

    Args:
        text: The text to check
        prefix: Prefix to add if text is true-ish
        suffix: Suffix to add if text is true-ish
    """
    return f"{prefix}{text}{suffix}" if text else ""

get_output_from_call

get_output_from_call(
    call: str | Sequence[str],
    cwd: str | PathLike[str] | None = None,
    use_cache: bool = False,
) -> str | None

Execute a system call and return its output as a string.

Parameters:

Name Type Description Default
call str | Sequence[str]

The system call to make

required
cwd str | PathLike[str] | None

The working directory for the call

None
use_cache bool

Whether to cache the output of calls

False
Source code in src/jinjarope/envglobals.py
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
def get_output_from_call(
    call: str | Sequence[str],
    cwd: str | os.PathLike[str] | None = None,
    use_cache: bool = False,
) -> str | None:
    """Execute a system call and return its output as a string.

    Args:
        call: The system call to make
        cwd: The working directory for the call
        use_cache: Whether to cache the output of calls
    """
    import subprocess

    if not call:
        return None
    if not isinstance(call, str):
        call = " ".join(call)
    key = pathlib.Path(cwd or ".").resolve().as_posix() + call
    if key in _cache and use_cache:
        return _cache[key]
    logger.info("Executing %r...", call)
    try:
        text = subprocess.getoutput(call)
        _cache[key] = text
        return text  # noqa: TRY300
    except subprocess.CalledProcessError:
        logger.warning("Executing %s failed", call)
        return None

has_internet

has_internet() -> bool

Return true if machine is connected to internet.

Checks connection with a HEAD request to the Google DNS server.

Source code in src/jinjarope/envglobals.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def has_internet() -> bool:
    """Return true if machine is connected to internet.

    Checks connection with a HEAD request to the Google DNS server.
    """
    import http.client as httplib

    conn = httplib.HTTPSConnection("8.8.8.8", timeout=2)
    try:
        conn.request("HEAD", "/")
        return True  # noqa: TRY300
    except Exception:  # noqa: BLE001
        return False
    finally:
        conn.close()

load_file_cached

load_file_cached(path: str | PathLike[str]) -> str

Return the text-content of file at given path.

Call is cached based on resolved file path. Also supports fsspec-style URLs and UPaths.

Parameters:

Name Type Description Default
path str | PathLike[str]

The path to get str content from

required
Source code in src/jinjarope/envglobals.py
21
22
23
24
25
26
27
28
29
30
31
@dec.cache_with_transforms(arg_transformers={0: lambda p: upath.UPath(p).resolve()})
def load_file_cached(path: str | os.PathLike[str]) -> str:
    """Return the text-content of file at given path.

    Call is cached based on resolved file path.
    Also supports fsspec-style URLs and UPaths.

    Args:
        path: The path to get str content from
    """
    return upath.UPath(path).read_text("utf-8")

match

match(obj: Any, mapping: dict[str | type, str] | None = None, **kwargs: Any) -> str

A filter trying to imitate a python match-case statement.

Parameters:

Name Type Description Default
obj Any

match object

required
mapping dict[str | type, str] | None

a mapping for the different cases. If key is type, an isinstance will be performed. If key is a str, check for equality.

None
kwargs Any

Same functionality as mapping, but provided as keyword arguments for convenience.

{}

Examples:

{{ "a" | match(a="hit", b="miss")
{{ MyClass() | match({MyClass: "hit", OtherClass: "miss"}) }}
Source code in src/jinjarope/envglobals.py
 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
def match(obj: Any, mapping: dict[str | type, str] | None = None, **kwargs: Any) -> str:
    """A filter trying to imitate a python match-case statement.

    Args:
        obj: match object
        mapping: a mapping for the different cases. If key is type, an isinstance will
                 be performed. If key is a str, check for equality.
        kwargs: Same functionality as mapping, but provided as keyword arguments for
                convenience.

    Examples:
        ``` jinja
        {{ "a" | match(a="hit", b="miss")
        {{ MyClass() | match({MyClass: "hit", OtherClass: "miss"}) }}
        ```
    """
    # kwargs can only contain strs as keys, so we can perform simply getitem.
    if kwargs and obj in kwargs:
        return kwargs[obj]

    for k, v in (mapping or {}).items():
        match k:
            case type() if isinstance(obj, k):
                return v
            case _ if k == obj:
                return v
    return ""

now

now(tz: tzinfo | None = None) -> datetime

Get current Datetime.

Parameters:

Name Type Description Default
tz tzinfo | None

timezone for retuned datetime

None
Source code in src/jinjarope/envglobals.py
139
140
141
142
143
144
145
def now(tz: datetime.tzinfo | None = None) -> datetime.datetime:
    """Get current Datetime.

    Args:
        tz: timezone for retuned datetime
    """
    return datetime.datetime.now(tz)

ternary

ternary(value: Any, true_val: Any, false_val: Any, none_val: Any = None)

Value ? true_val : false_val.

Parameters:

Name Type Description Default
value Any

The value to check.

required
true_val Any

The value to return if given value is true-ish

required
false_val Any

The value to return if given value is false-ish

required
none_val Any

Optional value to return if given value is None

None
Source code in src/jinjarope/envglobals.py
79
80
81
82
83
84
85
86
87
88
89
90
def ternary(value: Any, true_val: Any, false_val: Any, none_val: Any = None):
    """Value ? true_val : false_val.

    Args:
        value: The value to check.
        true_val: The value to return if given value is true-ish
        false_val: The value to return if given value is false-ish
        none_val: Optional value to return if given value is None
    """
    if value is None and none_val is not None:
        return none_val
    return true_val if bool(value) else false_val

utcnow

utcnow() -> datetime

Get UTC datetime.

Source code in src/jinjarope/envglobals.py
148
149
150
def utcnow() -> datetime.datetime:
    """Get UTC datetime."""
    return datetime.datetime.now(datetime.UTC)