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 self._unapply_steps = [] 34 try: 35 self._environ = environ 36 env.accept(self) 37 finally: 38 self._environ = None 39 40 def visit_set(self, set): # pylint: disable=redefined-builtin 41 self._environ[set.name] = set.value 42 43 def visit_clear(self, clear): 44 if clear.name in self._environ: 45 del self._environ[clear.name] 46 47 def visit_remove(self, remove): 48 values = self._environ.get(remove.name, '').split(self._pathsep) 49 norm = os.path.normpath 50 values = [x for x in values if norm(x) != norm(remove.value)] 51 self._environ[remove.name] = self._pathsep.join(values) 52 53 def visit_prepend(self, prepend): 54 self._environ[prepend.name] = self._pathsep.join( 55 (prepend.value, self._environ.get(prepend.name, '')) 56 ) 57 58 def visit_append(self, append): 59 self._environ[append.name] = self._pathsep.join( 60 (self._environ.get(append.name, ''), append.value) 61 ) 62 63 def visit_echo(self, echo): 64 pass # Not relevant for apply. 65 66 def visit_comment(self, comment): 67 pass # Not relevant for apply. 68 69 def visit_command(self, command): 70 pass # Not relevant for apply. 71 72 def visit_doctor(self, doctor): 73 pass # Not relevant for apply. 74 75 def visit_blank_line(self, blank_line): 76 pass # Not relevant for apply. 77 78 def visit_function(self, function): 79 pass # Not relevant for apply. 80 81 def visit_hash(self, hash): # pylint: disable=redefined-builtin 82 pass # Not relevant for apply. 83