gcc-env 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gcc_env/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """gcc-env: cross-platform GCC/C++ toolchain manager."""
2
+
3
+ __version__ = "0.3.2"
4
+ __all__ = ["__version__"]
gcc_env/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ from __future__ import annotations
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
gcc_env/activation.py ADDED
@@ -0,0 +1,444 @@
1
+ """Build environment variables and shell activation snippets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shlex
7
+ from pathlib import Path
8
+ from typing import NoReturn
9
+
10
+ from .envs import Environment
11
+ from .errors import UsageError
12
+ from .state import MANAGED_VARS
13
+ from .util import hex_quote_ps, shell_basename
14
+
15
+ # Exported so prompt frameworks that recompute PS1 themselves (starship,
16
+ # oh-my-zsh, powerlevel10k) can show the active environment via
17
+ # "$GE_PROMPT_MODIFIER" instead of relying on the PS1 prefix we prepend.
18
+ PROMPT_MODIFIER_VAR = "GE_PROMPT_MODIFIER"
19
+
20
+ # Markers of the *current* activation. They are never restored from a
21
+ # snapshot: the shell hook forwards them into the ``ge`` process (possibly
22
+ # empty), so a snapshot may carry them, but deactivation must always clear
23
+ # them rather than export a stale value back into the shell.
24
+ _NEVER_RESTORE = frozenset({"GE_SESSION", "GE_ACTIVE"})
25
+
26
+ # Variables that describe the toolchain, in a stable display order.
27
+ _EXPORT_ORDER = [
28
+ "GE_ROOT",
29
+ "GE_ENV",
30
+ "GE_GCC_VERSION",
31
+ "GE_RUNTIME",
32
+ "CONDA_PREFIX",
33
+ "CONDA_DEFAULT_ENV",
34
+ "VIRTUAL_ENV",
35
+ "VIRTUAL_ENV_PROMPT",
36
+ "CC",
37
+ "CXX",
38
+ "CPP",
39
+ "AR",
40
+ "AS",
41
+ "LD",
42
+ "NM",
43
+ "RANLIB",
44
+ "OBJDUMP",
45
+ "READELF",
46
+ "STRIP",
47
+ "CMAKE_PREFIX_PATH",
48
+ "PKG_CONFIG_PATH",
49
+ "LIBRARY_PATH",
50
+ "LD_LIBRARY_PATH",
51
+ "DYLD_FALLBACK_LIBRARY_PATH",
52
+ "CONDA_BUILD_SYSROOT",
53
+ "PATH",
54
+ ]
55
+
56
+
57
+ def _dedupe_paths(entries: list[str], *, windows: bool) -> list[str]:
58
+ result: list[str] = []
59
+ seen: set[str] = set()
60
+ for entry in entries:
61
+ if not entry:
62
+ continue
63
+ key = os.path.normcase(os.path.normpath(entry)) if windows else entry
64
+ if key in seen:
65
+ continue
66
+ seen.add(key)
67
+ result.append(entry)
68
+ return result
69
+
70
+
71
+ def _prepend(existing: str | None, entries: list[str], *, windows: bool) -> str:
72
+ parts = [str(entry) for entry in entries if entry]
73
+ if existing:
74
+ parts.extend(existing.split(os.pathsep))
75
+ return os.pathsep.join(_dedupe_paths(parts, windows=windows))
76
+
77
+
78
+ def _is_within(path: str, root: Path) -> bool:
79
+ try:
80
+ candidate = os.path.abspath(path)
81
+ base = os.path.abspath(str(root))
82
+ return os.path.commonpath([candidate, base]) == base
83
+ except (OSError, ValueError):
84
+ return False
85
+
86
+
87
+ def _strip_previous_env(base_env: dict[str, str]) -> None:
88
+ """Remove paths from a previously activated ge environment.
89
+
90
+ This makes repeated `eval "$(ge activate ...)"` switch cleanly instead of
91
+ leaving an older toolchain behind the new one in PATH/LD_LIBRARY_PATH.
92
+ """
93
+ old_name = base_env.get("GE_ENV")
94
+ old_root = base_env.get("GE_ROOT")
95
+ if not old_name or not old_root:
96
+ return
97
+ old_env_dir = Path(old_root) / "envs" / old_name
98
+ for variable in (
99
+ "PATH",
100
+ "LD_LIBRARY_PATH",
101
+ "DYLD_FALLBACK_LIBRARY_PATH",
102
+ "LIBRARY_PATH",
103
+ "CMAKE_PREFIX_PATH",
104
+ "PKG_CONFIG_PATH",
105
+ ):
106
+ value = base_env.get(variable)
107
+ if not value:
108
+ continue
109
+ parts = value.split(os.pathsep)
110
+ kept = [part for part in parts if part and not _is_within(part, old_env_dir)]
111
+ if kept:
112
+ base_env[variable] = os.pathsep.join(kept)
113
+ else:
114
+ base_env.pop(variable, None)
115
+ base_env.pop("VIRTUAL_ENV", None)
116
+ base_env.pop("VIRTUAL_ENV_PROMPT", None)
117
+
118
+
119
+ def toolchain_env(env: Environment, *, base: dict[str, str] | None = None) -> dict[str, str]:
120
+ base_env = dict(os.environ if base is None else base)
121
+ windows = env.config.platform.is_windows
122
+ prefix = env.conda_prefix
123
+ _strip_previous_env(base_env)
124
+
125
+ bin_dirs: list[Path] = []
126
+ if env.shim_dir.is_dir():
127
+ bin_dirs.append(env.shim_dir)
128
+ if env.python_enabled:
129
+ venv_bin = env.venv_bin()
130
+ if venv_bin:
131
+ bin_dirs.append(venv_bin)
132
+ if windows:
133
+ bin_dirs.extend(
134
+ [
135
+ prefix / "Library" / "bin",
136
+ prefix / "Library" / "mingw-w64" / "bin",
137
+ prefix / "Library" / "usr" / "bin",
138
+ prefix / "bin",
139
+ prefix / "Scripts",
140
+ ]
141
+ )
142
+ else:
143
+ bin_dirs.append(prefix / "bin")
144
+ bin_dirs.append(env.config.bin_dir)
145
+
146
+ path_value = _prepend(
147
+ base_env.get("PATH"),
148
+ [str(path) for path in bin_dirs if path.is_dir()],
149
+ windows=windows,
150
+ )
151
+ base_env["PATH"] = path_value
152
+
153
+ if windows:
154
+ prefix_paths = [prefix / "Library" / "lib", prefix / "Library" / "bin"]
155
+ else:
156
+ prefix_paths = [prefix / "lib", prefix / "lib64"]
157
+
158
+ cma_prefix = [str(prefix)]
159
+ if env.sysroot:
160
+ cma_prefix.append(str(env.sysroot / "usr"))
161
+ base_env["CMAKE_PREFIX_PATH"] = _prepend(
162
+ base_env.get("CMAKE_PREFIX_PATH"), cma_prefix, windows=windows
163
+ )
164
+
165
+ pkgconfig = [str(prefix / "lib" / "pkgconfig"), str(prefix / "share" / "pkgconfig")]
166
+ if env.sysroot:
167
+ pkgconfig.append(str(env.sysroot / "usr" / "lib" / "pkgconfig"))
168
+ base_env["PKG_CONFIG_PATH"] = _prepend(
169
+ base_env.get("PKG_CONFIG_PATH"), pkgconfig, windows=windows
170
+ )
171
+
172
+ library_path = [str(path) for path in prefix_paths if path.is_dir()]
173
+ base_env["LIBRARY_PATH"] = _prepend(base_env.get("LIBRARY_PATH"), library_path, windows=windows)
174
+ if not windows:
175
+ base_env["LD_LIBRARY_PATH"] = _prepend(
176
+ base_env.get("LD_LIBRARY_PATH"), library_path, windows=windows
177
+ )
178
+ if env.config.platform.is_macos:
179
+ base_env["DYLD_FALLBACK_LIBRARY_PATH"] = _prepend(
180
+ base_env.get("DYLD_FALLBACK_LIBRARY_PATH"), library_path, windows=windows
181
+ )
182
+
183
+ base_env["GE_ROOT"] = str(env.config.root)
184
+ base_env["GE_ENV"] = env.name
185
+ base_env["GE_GCC_VERSION"] = env.gcc_version
186
+ base_env["GE_RUNTIME"] = env.runtime
187
+ base_env["CONDA_PREFIX"] = str(prefix)
188
+ base_env["CONDA_DEFAULT_ENV"] = env.name
189
+ base_env["CC"] = str(env.cc)
190
+ base_env["CXX"] = str(env.cxx)
191
+ for name, path in env.gcc_tools.items():
192
+ key = name.upper()
193
+ if key in {"AR", "AS", "LD", "NM", "RANLIB", "OBJDUMP", "READELF", "STRIP"}:
194
+ base_env[key] = str(path)
195
+ if env.sysroot and env.config.platform.is_linux:
196
+ base_env["CONDA_BUILD_SYSROOT"] = str(env.sysroot)
197
+
198
+ if env.python_enabled:
199
+ base_env["VIRTUAL_ENV"] = str(env.venv_dir)
200
+ base_env["VIRTUAL_ENV_PROMPT"] = f"({env.name}) "
201
+ base_env.pop("PYTHONHOME", None)
202
+ else:
203
+ base_env.pop("VIRTUAL_ENV", None)
204
+ base_env.pop("VIRTUAL_ENV_PROMPT", None)
205
+ return base_env
206
+
207
+
208
+ def _posix_quote(value: str) -> str:
209
+ return shlex.quote(value)
210
+
211
+
212
+ def _fish_quote(value: str) -> str:
213
+ return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
214
+
215
+
216
+ def _unsupported_shell(shell: str) -> NoReturn:
217
+ raise UsageError(
218
+ f"unsupported shell: {shell}",
219
+ hint="Supported shells: bash, zsh, fish, powershell, cmd. "
220
+ "See 'ge shell-init --help' and 'ge activate --help'.",
221
+ )
222
+
223
+
224
+ def activation_script(
225
+ env: Environment,
226
+ *,
227
+ shell: str,
228
+ base: dict[str, str] | None = None,
229
+ session: str | None = None,
230
+ export_session: bool | None = None,
231
+ ) -> str:
232
+ """Render the shell code that activates *env* in the current shell.
233
+
234
+ ``session`` names the snapshot written by ``save_snapshot`` so that a later
235
+ ``ge deactivate`` can find it. How it reaches that later ``ge`` process
236
+ depends on the integration mode:
237
+
238
+ * **Hook mode** (the ``ge()`` wrapper is installed, so this process sees
239
+ ``GE_SHELL``): the wrapper injects ``GE_SESSION=<shell pid>`` into every
240
+ ``ge`` call, so the script must not export it. An exported value would
241
+ leak into subshells, tmux panes, IDE terminals and ``nohup``, which would
242
+ then share - and pop - the parent shell's snapshot. For the same reason
243
+ ``GE_ACTIVE`` becomes a plain, non-exported shell variable that the
244
+ wrapper forwards explicitly.
245
+ * **Eval mode** (``eval "$(ge activate ...)"``): nothing re-injects the
246
+ session, so it is exported; leaking into child shells is the known
247
+ limitation of this fallback.
248
+
249
+ ``export_session`` forces either behaviour; by default the mode is derived
250
+ from the presence of ``GE_SHELL``.
251
+ """
252
+ values = toolchain_env(env, base=base)
253
+ shell = shell_basename(shell)
254
+ if shell in {"sh", "dash", "ksh"}:
255
+ shell = "bash"
256
+ if export_session is None:
257
+ export_session = "GE_SHELL" not in os.environ
258
+ prompt_modifier = f"({env.name}) "
259
+
260
+ if shell in {"bash", "zsh"}:
261
+ lines = [f"# gcc-env: {env.name} (GCC {env.gcc_version})"]
262
+ for key in _EXPORT_ORDER:
263
+ if key in values:
264
+ lines.append(f"export {key}={_posix_quote(values[key])}")
265
+ elif key in {"VIRTUAL_ENV", "VIRTUAL_ENV_PROMPT"}:
266
+ lines.append(f"unset {key}")
267
+ lines.append(f"export {PROMPT_MODIFIER_VAR}={_posix_quote(prompt_modifier)}")
268
+ if session and export_session:
269
+ lines.append(f"export GE_SESSION={_posix_quote(session)}")
270
+ # No `export`: the hook forwards GE_ACTIVE itself, and a child shell
271
+ # (bash, tmux pane, IDE terminal) must not inherit our activation.
272
+ lines.append("GE_ACTIVE=1")
273
+ lines.extend(
274
+ [
275
+ 'if [ -z "${GE_ORIG_PS1+x}" ]; then',
276
+ ' GE_ORIG_PS1="${PS1-}"',
277
+ "fi",
278
+ f'PS1="({env.name}) ${{GE_ORIG_PS1}}"',
279
+ ]
280
+ )
281
+ lines.append("hash -r 2>/dev/null || true")
282
+ return "\n".join(lines) + "\n"
283
+
284
+ if shell == "fish":
285
+ lines = [f"# gcc-env: {env.name} (GCC {env.gcc_version})"]
286
+ for key in _EXPORT_ORDER:
287
+ if key not in values:
288
+ if key in {"VIRTUAL_ENV", "VIRTUAL_ENV_PROMPT"}:
289
+ lines.append(f"set -e {key}")
290
+ continue
291
+ if key == "PATH":
292
+ parts = values[key].split(os.pathsep)
293
+ joined = " ".join(_fish_quote(part) for part in parts if part)
294
+ lines.append(f"set -gx PATH {joined}")
295
+ else:
296
+ lines.append(f"set -gx {key} {_fish_quote(values[key])}")
297
+ lines.append(f"set -gx {PROMPT_MODIFIER_VAR} {_fish_quote(prompt_modifier)}")
298
+ if session and export_session:
299
+ lines.append(f"set -gx GE_SESSION {_fish_quote(session)}")
300
+ lines.append("set -g GE_ACTIVE 1")
301
+ lines.extend(
302
+ [
303
+ "if not functions -q __ge_original_prompt",
304
+ " functions -c fish_prompt __ge_original_prompt",
305
+ "end",
306
+ "function fish_prompt",
307
+ f" printf '%s' {_fish_quote(f'({env.name}) ')}",
308
+ " __ge_original_prompt",
309
+ "end",
310
+ ]
311
+ )
312
+ return "\n".join(lines) + "\n"
313
+
314
+ if shell in {"powershell", "pwsh"}:
315
+ lines = [f"# gcc-env: {env.name} (GCC {env.gcc_version})"]
316
+ for key in _EXPORT_ORDER:
317
+ if key in values:
318
+ lines.append(f"$env:{key} = {hex_quote_ps(values[key])}")
319
+ elif key in {"VIRTUAL_ENV", "VIRTUAL_ENV_PROMPT"}:
320
+ lines.append(f"Remove-Item Env:{key} -ErrorAction SilentlyContinue")
321
+ lines.append(f"$env:{PROMPT_MODIFIER_VAR} = {hex_quote_ps(prompt_modifier)}")
322
+ if session and export_session:
323
+ lines.append(f"$env:GE_SESSION = {hex_quote_ps(session)}")
324
+ # Not an env variable: the hook forwards it from this global instead.
325
+ lines.append("$global:__ge_active = 1")
326
+ lines.extend(
327
+ [
328
+ "if (-not $global:__ge_original_prompt) {",
329
+ " $global:__ge_original_prompt = $function:prompt",
330
+ "}",
331
+ "function global:prompt {",
332
+ " $base = & $global:__ge_original_prompt",
333
+ f" {hex_quote_ps(f'({env.name}) ')} + $base",
334
+ "}",
335
+ ]
336
+ )
337
+ return "\n".join(lines) + "\n"
338
+
339
+ if shell in {"cmd", "cmd.exe"}:
340
+ lines = [f"@rem gcc-env: {env.name} (GCC {env.gcc_version})"]
341
+ for key in _EXPORT_ORDER:
342
+ if key in values:
343
+ lines.append(f'set "{key}={values[key]}"')
344
+ elif key in {"VIRTUAL_ENV", "VIRTUAL_ENV_PROMPT"}:
345
+ lines.append(f'set "{key}="')
346
+ lines.append(f'set "{PROMPT_MODIFIER_VAR}={prompt_modifier}"')
347
+ if session and export_session:
348
+ lines.append(f'set "GE_SESSION={session}"')
349
+ lines.append('set "GE_ACTIVE=1"')
350
+ return "\r\n".join(lines) + "\r\n"
351
+
352
+ _unsupported_shell(shell)
353
+
354
+
355
+ def deactivation_script(snapshot: dict[str, str], *, shell: str) -> str:
356
+ """Generate shell code that restores a state snapshot."""
357
+ shell = shell_basename(shell)
358
+ if shell in {"sh", "dash", "ksh"}:
359
+ shell = "bash"
360
+ values = dict(snapshot)
361
+ if "PATH" not in values:
362
+ values["PATH"] = os.defpath
363
+
364
+ if shell in {"bash", "zsh"}:
365
+ lines = ["# gcc-env: deactivated"]
366
+ for key in MANAGED_VARS:
367
+ if key in values and key not in _NEVER_RESTORE:
368
+ lines.append(f"export {key}={_posix_quote(values[key])}")
369
+ else:
370
+ lines.append(f"unset {key}")
371
+ lines.extend(
372
+ [
373
+ 'if [ -n "${GE_ORIG_PS1+x}" ]; then',
374
+ ' PS1="$GE_ORIG_PS1"',
375
+ " unset GE_ORIG_PS1",
376
+ "fi",
377
+ ]
378
+ )
379
+ lines.append("hash -r 2>/dev/null || true")
380
+ return "\n".join(lines) + "\n"
381
+
382
+ if shell == "fish":
383
+ lines = ["# gcc-env: deactivated"]
384
+ for key in MANAGED_VARS:
385
+ if key not in values or key in _NEVER_RESTORE:
386
+ lines.append(f"set -e {key}")
387
+ elif key == "PATH":
388
+ parts = values[key].split(os.pathsep)
389
+ joined = " ".join(_fish_quote(part) for part in parts if part)
390
+ lines.append(f"set -gx PATH {joined}")
391
+ else:
392
+ lines.append(f"set -gx {key} {_fish_quote(values[key])}")
393
+ lines.extend(
394
+ [
395
+ "if functions -q __ge_original_prompt",
396
+ " functions -c __ge_original_prompt fish_prompt",
397
+ " functions -e __ge_original_prompt",
398
+ "end",
399
+ ]
400
+ )
401
+ return "\n".join(lines) + "\n"
402
+
403
+ if shell in {"powershell", "pwsh"}:
404
+ # `Remove-Variable` needs -Scope Global: the hook evals this script
405
+ # inside the ge() function, whose local scope is not the global one.
406
+ lines = [
407
+ "# gcc-env: deactivated",
408
+ "Remove-Variable __ge_active -Scope Global -ErrorAction SilentlyContinue",
409
+ ]
410
+ for key in MANAGED_VARS:
411
+ if key in values and key not in _NEVER_RESTORE:
412
+ lines.append(f"$env:{key} = {hex_quote_ps(values[key])}")
413
+ else:
414
+ lines.append(f"Remove-Item Env:{key} -ErrorAction SilentlyContinue")
415
+ lines.extend(
416
+ [
417
+ "if ($global:__ge_original_prompt) {",
418
+ " Set-Item -Path Function:\\global:prompt -Value $global:__ge_original_prompt",
419
+ " Remove-Variable __ge_original_prompt -Scope Global "
420
+ "-ErrorAction SilentlyContinue",
421
+ "}",
422
+ ]
423
+ )
424
+ return "\n".join(lines) + "\n"
425
+
426
+ if shell in {"cmd", "cmd.exe"}:
427
+ lines = ["@rem gcc-env: deactivated"]
428
+ for key in MANAGED_VARS:
429
+ if key in values and key not in _NEVER_RESTORE:
430
+ lines.append(f'set "{key}={values[key]}"')
431
+ else:
432
+ lines.append(f'set "{key}="')
433
+ return "\r\n".join(lines) + "\r\n"
434
+
435
+ _unsupported_shell(shell)
436
+
437
+
438
+ def shell_environment(env: Environment) -> dict[str, str]:
439
+ """Environment for ge run/ge shell/compiler wrappers."""
440
+ return toolchain_env(env)
441
+
442
+
443
+ def prompt_label(env: Environment) -> str:
444
+ return f"ge:{env.name} gcc-{env.gcc_version}"