Repository: pyodide/pyodide

Issue:
Detecting Pyodide, at build time
## 📚 Documentation

The current documentation reads:

To detect Pyodide, at build time use,

```
import os

if "PYODIDE" in os.environ:
    # building for Pyodide
```

This used to work on my computer using pyodide-build v0.21.

When I tried it using pyodide-build v0.22 however, the test `if "PYODIDE" in os.environ` returned false.

Inspecting my `os.environ`, I changed the test to `if ("PYODIDE_ROOT" in os.environ):`, and my setup.py detects when the code is being built with pyodide.

This lead me to believe the docs needed updating. However, searching the pyodide repo, I saw `if "PYODIDE" in os.environ` in the following patch file: https://github.com/pyodide/pyodide/blob/main/packages/Pillow/patches/0001-Enable-image-formats.patch

So I'm not really sure anymore ...


Discussion:
For in-tree build the PYODIDE env variable is still [set here](https://github.com/pyodide/pyodide/blob/main/Makefile.envs#L45) and also set in [get_bash_runner](https://github.com/pyodide/pyodide/blob/main/pyodide-build/pyodide_build/buildpkg.py#L120), so that should work.

For out of tree builds with `pyodide build` it  does indeed looks like it's not set . The Makefile.env shipped in   `xbuildenv-0.22.0.tar.bz2 ` is never loaded, unless I'm missing something.  Maybe @hoodmane could confirm.

 If that's true, we could add it [here](https://github.com/pyodide/pyodide/blob/3c92574c57e8a57d5e2b081e9a19b01cfc9b3745/pyodide-build/pyodide_build/out_of_tree/build.py#L19) I think:
```py
env_vars = os.environ.copy()
env_vars['PYODIDE'] = 1

build_env_ctx = pypabuild.get_build_env(
        ...,
        env=env_vars
)
```


I think we should extract these lines:
https://github.com/pyodide/pyodide/blob/main/pyodide-build/pyodide_build/buildpkg.py#L119-L133
into a separate function in `common.py`. Or at least whatever part of it should be shared with `pyodide build`.

Resolving patch:
diff --git a/pyodide-build/pyodide_build/buildpkg.py b/pyodide-build/pyodide_build/buildpkg.py
--- a/pyodide-build/pyodide_build/buildpkg.py
+++ b/pyodide-build/pyodide_build/buildpkg.py
@@ -27,11 +27,11 @@
 
 from . import common, pypabuild
 from .common import (
-    BUILD_VARS,
     chdir,
     exit_with_stdio,
     find_matching_wheels,
     find_missing_executables,
+    set_build_environment,
 )
 from .io import MetaConfig, _BuildSpec, _SourceSpec
 from .logger import logger
@@ -117,20 +117,8 @@ def __exit__(
 @contextmanager
 def get_bash_runner() -> Iterator[BashRunnerWithSharedEnvironment]:
     PYODIDE_ROOT = os.environ["PYODIDE_ROOT"]
-    env = {key: os.environ[key] for key in BUILD_VARS} | {"PYODIDE": "1"}
-    if "PYODIDE_JOBS" in os.environ:
-        env["PYODIDE_JOBS"] = os.environ["PYODIDE_JOBS"]
-
-    env["PKG_CONFIG_PATH"] = env["WASM_PKG_CONFIG_PATH"]
-    if "PKG_CONFIG_PATH" in os.environ:
-        env["PKG_CONFIG_PATH"] += f":{os.environ['PKG_CONFIG_PATH']}"
-
-    tools_dir = Path(__file__).parent / "tools"
-
-    env["CMAKE_TOOLCHAIN_FILE"] = str(
-        tools_dir / "cmake/Modules/Platform/Emscripten.cmake"
-    )
-    env["PYO3_CONFIG_FILE"] = str(tools_dir / "pyo3_config.ini")
+    env: dict[str, str] = {}
+    set_build_environment(env)
 
     with BashRunnerWithSharedEnvironment(env=env) as b:
         b.run(f"source {PYODIDE_ROOT}/pyodide_env.sh", stderr=subprocess.DEVNULL)
diff --git a/pyodide-build/pyodide_build/common.py b/pyodide-build/pyodide_build/common.py
--- a/pyodide-build/pyodide_build/common.py
+++ b/pyodide-build/pyodide_build/common.py
@@ -459,3 +459,25 @@ def chdir(new_dir: Path) -> Generator[None, None, None]:
         yield
     finally:
         os.chdir(orig_dir)
+
+
+def set_build_environment(env: dict[str, str]) -> None:
+    """Assign build environment variables to env.
+
+    Sets common environment between in tree and out of tree package builds.
+    """
+    env.update({key: os.environ[key] for key in BUILD_VARS})
+    env["PYODIDE"] = "1"
+    if "PYODIDE_JOBS" in os.environ:
+        env["PYODIDE_JOBS"] = os.environ["PYODIDE_JOBS"]
+
+    env["PKG_CONFIG_PATH"] = env["WASM_PKG_CONFIG_PATH"]
+    if "PKG_CONFIG_PATH" in os.environ:
+        env["PKG_CONFIG_PATH"] += f":{os.environ['PKG_CONFIG_PATH']}"
+
+    tools_dir = Path(__file__).parent / "tools"
+
+    env["CMAKE_TOOLCHAIN_FILE"] = str(
+        tools_dir / "cmake/Modules/Platform/Emscripten.cmake"
+    )
+    env["PYO3_CONFIG_FILE"] = str(tools_dir / "pyo3_config.ini")
diff --git a/pyodide-build/pyodide_build/out_of_tree/build.py b/pyodide-build/pyodide_build/out_of_tree/build.py
--- a/pyodide-build/pyodide_build/out_of_tree/build.py
+++ b/pyodide-build/pyodide_build/out_of_tree/build.py
@@ -14,9 +14,11 @@ def run(exports: Any, args: list[str], outdir: Path | None = None) -> Path:
     cxxflags += f" {os.environ.get('CXXFLAGS', '')}"
     ldflags = common.get_make_flag("SIDE_MODULE_LDFLAGS")
     ldflags += f" {os.environ.get('LDFLAGS', '')}"
+    env = os.environ.copy()
+    common.set_build_environment(env)
 
     build_env_ctx = pypabuild.get_build_env(
-        env=os.environ.copy(),
+        env=env,
         pkgname="",
         cflags=cflags,
         cxxflags=cxxflags,


Test patch: