fix: make main_module work with precompiling (#4403)

Executables using `main_module` and `pyc_collection = "include_pyc"`
fail during analysis. This failure is due to the fact that the bytecode
collection handling expects a main file reference in the source to
bytecode map, but `main_module` explicitly does not have this because
module entrypoints are resolved at runtime.

Python's import machinery resolves module entrypoints at runtime and
supports bytecode loading, so in that case there's no file entry point
to find during analysis. Limit the analysis-time entrypoint substitution
to file-based entrypoints.

---------

Co-authored-by: Richard Levasseur <richardlev@gmail.com>
diff --git a/news/main-module-precompile.fixed.md b/news/main-module-precompile.fixed.md
new file mode 100644
index 0000000..5585c3d
--- /dev/null
+++ b/news/main-module-precompile.fixed.md
@@ -0,0 +1,2 @@
+Fixed using `main_module` with `pyc_collection = "include_pyc"`
+in executables.
diff --git a/python/private/py_executable.bzl b/python/private/py_executable.bzl
index e8240da..3498c88 100644
--- a/python/private/py_executable.bzl
+++ b/python/private/py_executable.bzl
@@ -1227,7 +1227,9 @@
 
     # Sourceless precompiled builds omit the main py file from outputs, so
     # main has to be pointed to the precompiled main instead.
-    if (main_py not in precompile_result.keep_srcs and
+    # NOTE: main_py is None when main_module is used
+    if (main_py != None and
+        main_py not in precompile_result.keep_srcs and
         PycCollectionAttr.is_pyc_collection_enabled(ctx)):
         main_py = precompile_result.py_to_pyc_map[main_py]
 
diff --git a/tests/bootstrap_impls/BUILD.bazel b/tests/bootstrap_impls/BUILD.bazel
index f8f3b68..f5c8c1f 100644
--- a/tests/bootstrap_impls/BUILD.bazel
+++ b/tests/bootstrap_impls/BUILD.bazel
@@ -192,6 +192,17 @@
     target_compatible_with = SUPPORTS_BOOTSTRAP_SCRIPT,
 )
 
+py_reconfig_test(
+    name = "main_module_precompiled_test",
+    srcs = ["main_module.py"],
+    bootstrap_impl = "script",
+    imports = ["."],
+    main_module = "tests.bootstrap_impls.main_module",
+    precompile = "enabled",
+    pyc_collection = "include_pyc",
+    target_compatible_with = SUPPORTS_BOOTSTRAP_SCRIPT,
+)
+
 sh_py_run_test(
     name = "inherit_pythonsafepath_env_test",
     bootstrap_impl = "script",