File: _env.py

package info (click to toggle)
python-cyclopts 3.12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,288 kB
  • sloc: python: 11,445; makefile: 24
file content (39 lines) | stat: -rw-r--r-- 1,440 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
import os
from typing import TYPE_CHECKING

from attrs import define, field

from cyclopts.argument import ArgumentCollection, Token

if TYPE_CHECKING:
    from cyclopts.core import App


@define
class Env:
    prefix: str = ""
    command: bool = field(default=True, kw_only=True)

    def __call__(self, apps: list["App"], commands: tuple[str, ...], arguments: "ArgumentCollection"):
        prefix = self.prefix
        if self.command and commands:
            prefix += "_".join(x.upper() for x in commands) + "_"

        candidate_env_keys = [x for x in os.environ if x.startswith(prefix)]
        candidate_env_keys.sort()
        for candidate_env_key in candidate_env_keys:
            try:
                argument, remaining_keys, _ = arguments.match(
                    candidate_env_key[len(prefix) :],
                    transform=lambda s: s.upper().replace("-", "_").replace(".", "_").lstrip("_"),
                    delimiter="_",
                )
            except ValueError:
                continue
            if any(x.source != "env" for x in argument.tokens):
                continue
            remaining_keys = tuple(x.lower() for x in remaining_keys)
            for i, value in enumerate(argument.env_var_split(os.environ[candidate_env_key])):
                argument.append(
                    Token(keyword=candidate_env_key, value=value, source="env", index=i, keys=remaining_keys)
                )