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