Debian Codegraph @

thirdparty/folly/build/fbcode_builder/getdeps/envfuncs.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 #
3 # This source code is licensed under the MIT license found in the
4 # LICENSE file in the root directory of this source tree.
5
6 import os
7 import shlex
8 import sys
9 from typing import Optional
10
11
12 class Env(object):
13 def __init__(self, src=None) -> None:
14 self._dict = {}
15 if src is None:
16 self.update(os.environ)
17 else:
18 self.update(src)
19
20 def update(self, src) -> None:
21 for k, v in src.items():
22 self.set(k, v)
23
24 def copy(self) -> "Env":
25 return Env(self._dict)
26
27 def _key(self, key):
28 # The `str` cast may not appear to be needed, but without it we run
29 # into issues when passing the environment to subprocess. The main
30 # issue is that in python2 `os.environ` (which is the initial source
31 # of data for the environment) uses byte based strings, but this
32 # project uses `unicode_literals`. `subprocess` will raise an error
33 # if the environment that it is passed has a mixture of byte and
34 # unicode strings.
35 # It is simplest to force everything to be `str` for the sake of
36 # consistency.
37 key = str(key)
38 if sys.platform.startswith("win"):
39 # Windows env var names are case insensitive but case preserving.
40 # An implementation of PAR files on windows gets confused if
41 # the env block contains keys with conflicting case, so make a
42 # pass over the contents to remove any.
43 # While this O(n) scan is technically expensive and gross, it
44 # is practically not a problem because the volume of calls is
45 # relatively low and the cost of manipulating the env is dwarfed
46 # by the cost of spawning a process on windows. In addition,
47 # since the processes that we run are expensive anyway, this
48 # overhead is not the worst thing to worry about.
49 for k in list(self._dict.keys()):
50 if str(k).lower() == key.lower():
51 return k
52 elif key in self._dict:
53 return key
54 return None
55
56 def get(self, key, defval=None):
57 key = self._key(key)
58 if key is None:
59 return defval
60 return self._dict[key]
61
62 def __getitem__(self, key):
63 val = self.get(key)
64 if key is None:
65 raise KeyError(key)
66 return val
67
68 def unset(self, key) -> None:
69 if key is None:
70 raise KeyError("attempting to unset env[None]")
71
72 key = self._key(key)
73 if key:
74 del self._dict[key]
75
76 def __delitem__(self, key) -> None:
77 self.unset(key)
78
79 def __repr__(self):
80 return repr(self._dict)
81
82 def set(self, key, value) -> None:
83 if key is None:
84 raise KeyError("attempting to assign env[None] = %r" % value)
85
86 if value is None:
87 raise ValueError("attempting to assign env[%s] = None" % key)
88
89 # The `str` conversion is important to avoid triggering errors
90 # with subprocess if we pass in a unicode value; see commentary
91 # in the `_key` method.
92 key = str(key)
93 value = str(value)
94
95 # The `unset` call is necessary on windows where the keys are
96 # case insensitive. Since this dict is case sensitive, simply
97 # assigning the value to the new key is not sufficient to remove
98 # the old value. The `unset` call knows how to match keys and
99 # remove any potential duplicates.
100 self.unset(key)
101 self._dict[key] = value
102
103 def __setitem__(self, key, value) -> None:
104 self.set(key, value)
105
106 def __iter__(self):
107 return self._dict.__iter__()
108
109 def __len__(self) -> int:
110 return len(self._dict)
111
112 def keys(self):
113 return self._dict.keys()
114
115 def values(self):
116 return self._dict.values()
117
118 def items(self):
119 return self._dict.items()
120
121
122 def add_path_entry(
123 env, name, item, append: bool = True, separator: str = os.pathsep
124 ) -> None:
125 """Cause `item` to be added to the path style env var named
126 `name` held in the `env` dict. `append` specifies whether
127 the item is added to the end (the default) or should be
128 prepended if `name` already exists."""
129 val = env.get(name, "")
130 if len(val) > 0:
131 val = val.split(separator)
132 else:
133 val = []
134 if append:
135 val.append(item)
136 else:
137 val.insert(0, item)
138 env.set(name, separator.join(val))
139
140
141 def add_flag(env, name, flag: str, append: bool = True) -> None:
142 """Cause `flag` to be added to the CXXFLAGS-style env var named
143 `name` held in the `env` dict. `append` specifies whether the
144 flag is added to the end (the default) or should be prepended if
145 `name` already exists."""
146 val = shlex.split(env.get(name, ""))
147 if append:
148 val.append(flag)
149 else:
150 val.insert(0, flag)
151 env.set(name, " ".join(val))
152
153
154 _path_search_cache = {}
155 _not_found = object()
156
157
158 def tpx_path() -> str:
159 return "xplat/testinfra/tpx/ctp.tpx"
160
161
162 def path_search(env, exename: str, defval: Optional[str] = None) -> Optional[str]:
163 """Search for exename in the PATH specified in env.
164 exename is eg: `ninja` and this function knows to append a .exe
165 to the end on windows.
166 Returns the path to the exe if found, or None if either no
167 PATH is set in env or no executable is found."""
168
169 path = env.get("PATH", None)
170 if path is None:
171 return defval
172
173 # The project hash computation code searches for C++ compilers (g++, clang, etc)
174 # repeatedly. Cache the result so we don't end up searching for these over and over
175 # again.
176 cache_key = (path, exename)
177 result = _path_search_cache.get(cache_key, _not_found)
178 if result is _not_found:
179 result = _perform_path_search(path, exename)
180 _path_search_cache[cache_key] = result
181 return result
182
183
184 def _perform_path_search(path, exename: str) -> Optional[str]:
185 is_win = sys.platform.startswith("win")
186 if is_win:
187 exename = "%s.exe" % exename
188
189 for bindir in path.split(os.pathsep):
190 full_name = os.path.join(bindir, exename)
191 if os.path.exists(full_name) and os.path.isfile(full_name):
192 if not is_win and not os.access(full_name, os.X_OK):
193 continue
194 return full_name
195
196 return None