1# Copyright 2021 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Applies an Environment to the current process."""
15
16import os
17
18# Disable super() warnings since this file must be Python 2 compatible.
19# pylint: disable=super-with-arguments
20
21
22class ApplyVisitor(object):  # pylint: disable=useless-object-inheritance
23    """Applies an Environment to the current process."""
24    def __init__(self, *args, **kwargs):
25        pathsep = kwargs.pop('pathsep', os.pathsep)
26        super(ApplyVisitor, self).__init__(*args, **kwargs)
27        self._pathsep = pathsep
28        self._environ = None
29        self._unapply_steps = None
30
31    def apply(self, env, environ):
32        self._unapply_steps = []
33        try:
34            self._environ = environ
35            env.accept(self)
36        finally:
37            self._environ = None
38
39    def visit_set(self, set):  # pylint: disable=redefined-builtin
40        self._environ[set.name] = set.value
41
42    def visit_clear(self, clear):
43        if clear.name in self._environ:
44            del self._environ[clear.name]
45
46    def visit_remove(self, remove):
47        values = self._environ.get(remove.name, '').split(self._pathsep)
48        norm = os.path.normpath
49        values = [x for x in values if norm(x) != norm(remove.value)]
50        self._environ[remove.name] = self._pathsep.join(values)
51
52    def visit_prepend(self, prepend):
53        self._environ[prepend.name] = self._pathsep.join(
54            (prepend.value, self._environ.get(prepend.name, '')))
55
56    def visit_append(self, append):
57        self._environ[append.name] = self._pathsep.join(
58            (self._environ.get(append.name, ''), append.value))
59
60    def visit_echo(self, echo):
61        pass  # Not relevant for apply.
62
63    def visit_comment(self, comment):
64        pass  # Not relevant for apply.
65
66    def visit_command(self, command):
67        pass  # Not relevant for apply.
68
69    def visit_doctor(self, doctor):
70        pass  # Not relevant for apply.
71
72    def visit_blank_line(self, blank_line):
73        pass  # Not relevant for apply.
74
75    def visit_function(self, function):
76        pass  # Not relevant for apply.
77
78    def visit_hash(self, hash):  # pylint: disable=redefined-builtin
79        pass  # Not relevant for apply.
80