Merge branch 'main' into 15397-remove-obsolete-apis
[arvados.git] / sdk / python / arvados / config.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 # config.py - configuration settings and global variables for Arvados clients
6 #
7 # Arvados configuration settings are taken from $HOME/.config/arvados.
8 # Environment variables override settings in the config file.
9
10 import os
11 import re
12
13 from typing import (
14     Callable,
15     Iterable,
16     Union,
17 )
18
19 from . import util
20
21 _settings = None
22 default_config_file = ''
23 """.. WARNING: Deprecated
24    Default configuration initialization now searches for the "default"
25    configuration in several places. This value no longer has any effect.
26 """
27
28 KEEP_BLOCK_SIZE = 2**26
29 EMPTY_BLOCK_LOCATOR = 'd41d8cd98f00b204e9800998ecf8427e+0'
30
31 def initialize(
32         config_file: Union[
33             str,
34             os.PathLike,
35             Callable[[str], Iterable[os.PathLike]],
36         ]=util._BaseDirectories('CONFIG').search,
37 ) -> None:
38     global _settings
39     _settings = {}
40
41     if callable(config_file):
42         search_paths = iter(config_file('settings.conf'))
43         config_file = next(search_paths, '')
44
45     # load the specified config file if available
46     try:
47         _settings = load(config_file)
48     except IOError:
49         pass
50
51     # override any settings with environment vars
52     for var in os.environ:
53         if var.startswith('ARVADOS_'):
54             _settings[var] = os.environ[var]
55
56 def load(config_file):
57     cfg = {}
58     with open(config_file, "r") as f:
59         for config_line in f:
60             if re.match(r'^\s*(?:#|$)', config_line):
61                 continue
62             var, val = config_line.rstrip().split('=', 2)
63             cfg[var] = val
64     return cfg
65
66 def flag_is_true(key, d=None):
67     if d is None:
68         d = settings()
69     return d.get(key, '').lower() in set(['1', 't', 'true', 'y', 'yes'])
70
71 def get(key, default_val=None):
72     return settings().get(key, default_val)
73
74 def settings():
75     if _settings is None:
76         initialize()
77     return _settings