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 19class ApplyVisitor: 20 """Applies an Environment to the current process.""" 21 22 def __init__(self, *args, **kwargs): 23 pathsep = kwargs.pop('pathsep', os.pathsep) 24 super().__init__(*args, **kwargs) 25 self._pathsep = pathsep 26 self._environ = None 27 self._unapply_steps = None 28 29 def apply(self, env, environ): 30 """Apply the given environment to the current process. 31 32 Args: 33 env (environment.Environment): Environment variables to use. 34 environ (dict): Where to set variables. In most cases this should be 35 os.environ. 36 """ 37 self._unapply_steps = [] 38 try: 39 self._environ = environ 40 env.accept(self) 41 finally: 42 self._environ = None 43 44 def visit_set(self, set): # pylint: disable=redefined-builtin 45 self._environ[set.name] = set.value 46 47 def visit_clear(self, clear): 48 if clear.name in self._environ: 49 del self._environ[clear.name] 50 51 def visit_remove(self, remove): 52 values = self._environ.get(remove.name, '').split(self._pathsep) 53 norm = os.path.normpath 54 values = [x for x in values if norm(x) != norm(remove.value)] 55 self._environ[remove.name] = self._pathsep.join(values) 56 57 def visit_prepend(self, prepend): 58 self._environ[prepend.name] = self._pathsep.join( 59 (prepend.value, self._environ.get(prepend.name, '')) 60 ) 61 62 def visit_append(self, append): 63 self._environ[append.name] = self._pathsep.join( 64 (self._environ.get(append.name, ''), append.value) 65 ) 66 67 def visit_echo(self, echo): 68 pass # Not relevant for apply. 69 70 def visit_comment(self, comment): 71 pass # Not relevant for apply. 72 73 def visit_command(self, command): 74 pass # Not relevant for apply. 75 76 def visit_doctor(self, doctor): 77 pass # Not relevant for apply. 78 79 def visit_blank_line(self, blank_line): 80 pass # Not relevant for apply. 81 82 def visit_function(self, function): 83 pass # Not relevant for apply. 84 85 def visit_hash(self, hash): # pylint: disable=redefined-builtin 86 pass # Not relevant for apply. 87