summaryrefslogtreecommitdiff
path: root/src/tox/tox_env/api.py
blob: 6c45ce796ffa8b8a1dfda78bc99a40f5917096f9 (plain)
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
"""
Defines the abstract base traits of a tox environment.
"""
import logging
import os
import re
import shutil
import sys
from abc import ABC, abstractmethod
from pathlib import Path
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Union, cast

from tox.config.main import Config
from tox.config.sets import ConfigSet
from tox.execute.api import Execute, Outcome
from tox.execute.request import ExecuteRequest

from .info import Info

if TYPE_CHECKING:
    from tox.config.cli.parser import Parsed


class ToxEnv(ABC):
    def __init__(self, conf: ConfigSet, core: ConfigSet, options: "Parsed"):
        self.conf: ConfigSet = conf
        self.core: ConfigSet = core
        self.options = options
        self._executor = self.executor()
        self.register_config()
        self._cache = Info(self.conf["env_dir"])
        self._paths: List[Path] = []
        self.logger = logging.getLogger(self.conf["env_name"])
        self._env_vars: Optional[Dict[str, str]] = None

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}(name={self.conf['env_name']})"

    @abstractmethod
    def executor(self) -> Execute:
        raise NotImplementedError

    def register_config(self) -> None:
        self.conf.add_constant(
            keys=["env_name", "envname"],
            desc="the name of the tox environment",
            value=self.conf.name,
        )
        self.conf.add_config(
            keys=["env_dir", "envdir"],
            of_type=Path,
            default=lambda conf, name: cast(Path, conf.core["work_dir"]) / cast(str, self.conf["env_name"]),
            desc="directory assigned to the tox environment",
        )
        self.conf.add_config(
            keys=["env_tmp_dir", "envtmpdir"],
            of_type=Path,
            default=lambda conf, name: cast(Path, conf.core["work_dir"]) / cast(str, self.conf["env_name"]) / "tmp",
            desc="a folder that is always reset at the start of the run",
        )

        def set_env_post_process(values: Dict[str, str], config: Config) -> Dict[str, str]:
            env = self.default_set_env()
            env.update(values)
            return env

        self.conf.add_config(
            keys=["set_env", "setenv"],
            of_type=Dict[str, str],
            default={},
            desc="environment variables to set when running commands in the tox environment",
            post_process=set_env_post_process,
        )

        def pass_env_post_process(values: List[str], config: Config) -> List[str]:
            values.extend(self.default_pass_env())
            return sorted(list({k: None for k in values}.keys()))

        self.conf.add_config(
            keys=["pass_env", "passenv"],
            of_type=List[str],
            default=[],
            desc="environment variables to pass on to the tox environment",
            post_process=pass_env_post_process,
        )

    def default_set_env(self) -> Dict[str, str]:
        return {}

    def default_pass_env(self) -> List[str]:
        env = [
            "https_proxy",
            "http_proxy",
            "no_proxy",
        ]
        if sys.platform == "win32":
            env.extend(
                [
                    "TEMP",
                    "TMP",
                ]
            )
        else:
            env.append("TMPDIR")
        return env

    def setup(self) -> None:
        """
        1. env dir exists
        2. contains a runner with the same type.
        """
        env_dir: Path = self.conf["env_dir"]
        conf = {"name": self.conf.name, "type": type(self).__name__}
        try:
            with self._cache.compare(conf, ToxEnv.__name__) as (eq, old):
                try:
                    if eq is True:
                        return
                    # if either the name or type changed and already exists start over
                    self.clean()
                finally:
                    env_dir.mkdir(exist_ok=True, parents=True)
        finally:
            self._handle_env_tmp_dir()

    def _handle_env_tmp_dir(self) -> None:
        """Ensure exists and empty"""
        env_tmp_dir: Path = self.conf["env_tmp_dir"]
        if env_tmp_dir.exists():
            logging.debug("removing %s", env_tmp_dir)
            shutil.rmtree(env_tmp_dir, ignore_errors=True)
        env_tmp_dir.mkdir(parents=True)

    def clean(self) -> None:
        env_dir: Path = self.conf["env_dir"]
        if env_dir.exists():
            logging.info("remove tox env folder %s", env_dir)
            shutil.rmtree(env_dir)
        self._cache.reset()

    @property
    def environment_variables(self) -> Dict[str, str]:
        if self._env_vars is not None:
            return self._env_vars
        result: Dict[str, str] = {}

        pass_env: List[str] = self.conf["pass_env"]
        glob_pass_env = [re.compile(e.replace("*", ".*")) for e in pass_env if "*" in e]
        literal_pass_env = [e for e in pass_env if "*" not in e]
        for env in literal_pass_env:
            if env in os.environ:
                result[env] = os.environ[env]
        if glob_pass_env:
            for env, value in os.environ.items():
                if any(g.match(env) is not None for g in glob_pass_env):
                    result[env] = value
        set_env: Dict[str, str] = self.conf["set_env"]
        result.update(set_env)
        result["PATH"] = os.pathsep.join([str(i) for i in self._paths] + os.environ.get("PATH", "").split(os.pathsep))
        self._env_vars = result
        return result

    def execute(
        self,
        cmd: Sequence[Union[Path, str]],
        allow_stdin: bool,
        show_on_standard: Optional[bool] = None,
        cwd: Optional[Path] = None,
    ) -> Outcome:
        if cwd is None:
            cwd = self.core["tox_root"]
        if show_on_standard is None:
            show_on_standard = self.options.verbosity > 3
        request = ExecuteRequest(cmd, cwd, self.environment_variables, allow_stdin)
        self.logger.warning("%s run => %s$ %s", self.conf["env_name"], request.cwd, request.shell_cmd)
        outcome = self._executor(request=request, show_on_standard=show_on_standard, colored=self.options.colored)
        return outcome

    @staticmethod
    @abstractmethod
    def id() -> str:
        raise NotImplementedError