1# Copyright 2021 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://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, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Module for dealing with env vars.""" 15 16import ast 17import os 18 19 20def _eval_value(value_string): 21 """Returns evaluated value.""" 22 try: 23 return ast.literal_eval(value_string) 24 except: # pylint: disable=bare-except 25 # String fallback. 26 return value_string 27 28 29def get(env_var, default_value=None): 30 """Returns an environment variable value.""" 31 value_string = os.getenv(env_var) 32 if value_string is None: 33 return default_value 34 35 return _eval_value(value_string) 36 37 38def get_bool(env_var, default_value=None): 39 """Returns a boolean environment variable value. This is needed because a lot 40 of CIFuzz users specified 'false' for dry-run. So we need to special case 41 this.""" 42 value = get(env_var, default_value) 43 if not isinstance(value, str): 44 return bool(value) 45 46 lower_value = value.lower() 47 allowed_values = {'true', 'false'} 48 if lower_value not in allowed_values: 49 raise Exception(f'Bool env var {env_var} value {value} is invalid. ' 50 f'Must be one of {allowed_values}.') 51 return lower_value == 'true' 52