pycontainer-build 0.4.0__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.
Files changed (54) hide show
  1. pycontainer/__init__.py +2 -0
  2. pycontainer/__main__.py +10 -0
  3. pycontainer/_pip_target.py +202 -0
  4. pycontainer/_venv_closure.py +507 -0
  5. pycontainer/auth.py +302 -0
  6. pycontainer/base_libc.py +264 -0
  7. pycontainer/base_trust.py +440 -0
  8. pycontainer/blob_store.py +78 -0
  9. pycontainer/build_args.py +106 -0
  10. pycontainer/builder.py +2127 -0
  11. pycontainer/cache.py +495 -0
  12. pycontainer/cli.py +708 -0
  13. pycontainer/config.py +552 -0
  14. pycontainer/config_loader.py +297 -0
  15. pycontainer/credentials.py +200 -0
  16. pycontainer/dependencies.py +1663 -0
  17. pycontainer/dependency_cache.py +753 -0
  18. pycontainer/deployment.py +263 -0
  19. pycontainer/devloop.py +159 -0
  20. pycontainer/dockerfile_import.py +666 -0
  21. pycontainer/effective_config.py +233 -0
  22. pycontainer/framework.py +134 -0
  23. pycontainer/fs_utils.py +409 -0
  24. pycontainer/healthcheck.py +102 -0
  25. pycontainer/history.py +293 -0
  26. pycontainer/image_validation.py +933 -0
  27. pycontainer/init_config.py +501 -0
  28. pycontainer/layer_analysis.py +163 -0
  29. pycontainer/local_image.py +997 -0
  30. pycontainer/locked_artifacts.py +187 -0
  31. pycontainer/lockfiles.py +1656 -0
  32. pycontainer/metadata.py +46 -0
  33. pycontainer/oci.py +159 -0
  34. pycontainer/project.py +183 -0
  35. pycontainer/registry_cleanup.py +304 -0
  36. pycontainer/registry_client.py +1863 -0
  37. pycontainer/registry_mirrors.py +119 -0
  38. pycontainer/release_notes.py +80 -0
  39. pycontainer/sbom.py +164 -0
  40. pycontainer/scanning.py +474 -0
  41. pycontainer/security.py +507 -0
  42. pycontainer/signing.py +252 -0
  43. pycontainer/squash.py +366 -0
  44. pycontainer/system_install.py +284 -0
  45. pycontainer/system_packages.py +381 -0
  46. pycontainer/tags.py +101 -0
  47. pycontainer/trust_notation.py +505 -0
  48. pycontainer/venv_markers.py +153 -0
  49. pycontainer_build-0.4.0.dist-info/METADATA +1587 -0
  50. pycontainer_build-0.4.0.dist-info/RECORD +54 -0
  51. pycontainer_build-0.4.0.dist-info/WHEEL +5 -0
  52. pycontainer_build-0.4.0.dist-info/entry_points.txt +3 -0
  53. pycontainer_build-0.4.0.dist-info/licenses/LICENSE +21 -0
  54. pycontainer_build-0.4.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2 @@
1
+ from .config import BuildConfig
2
+ from .builder import ImageBuilder
@@ -0,0 +1,10 @@
1
+ """Support ``python -m pycontainer`` and ``uv run -m pycontainer``."""
2
+ import sys
3
+
4
+ from pycontainer.cli import main
5
+
6
+
7
+ if __name__ == "__main__":
8
+ # argparse would otherwise report the program as "__main__.py".
9
+ sys.argv[0] = "pycontainer"
10
+ main()
@@ -0,0 +1,202 @@
1
+ """Run pip with environment markers evaluated for the target image.
2
+
3
+ This file is executed as ``python -c <source> <config-json> <pip args...>``
4
+ by ``dependencies.install_requirements``; it is not imported by the package.
5
+ pip selects wheels with ``--platform``/``--python-version`` but evaluates
6
+ markers against the build host, so every marker evaluation (requirements-file
7
+ roots, extras and transitive ``Requires-Dist``) is forced through the target
8
+ environment here. Markers that reference a variable whose target value is
9
+ unknown fail the install instead of falling back to host values. Host pip
10
+ configuration (environment and config files) is filtered to index and
11
+ authentication keys so it cannot change target selection options.
12
+ """
13
+ import sys
14
+
15
+ if __name__ == "__main__" and sys.path and sys.path[0] == "":
16
+ # Keep build-context modules from shadowing the installer's imports.
17
+ del sys.path[0]
18
+
19
+ import json
20
+ import os
21
+ import runpy
22
+
23
+ MARKER_ERROR_EXIT = 86
24
+ PATCH_ERROR_EXIT = 87
25
+ SNAPSHOT_ERROR_EXIT = 88
26
+
27
+
28
+ class TargetMarkerError(Exception):
29
+ pass
30
+
31
+
32
+ def _variables(markers):
33
+ names = []
34
+ for item in markers:
35
+ if isinstance(item, list):
36
+ names.extend(_variables(item))
37
+ elif isinstance(item, tuple) and len(item) == 3:
38
+ for node in item:
39
+ if type(node).__name__ == "Variable":
40
+ names.append(node.value)
41
+ elif type(node).__name__ not in {"Value", "Op"}:
42
+ raise TargetMarkerError("unrecognized marker structure")
43
+ elif item not in {"and", "or"}:
44
+ raise TargetMarkerError("unrecognized marker structure")
45
+ return names
46
+
47
+
48
+ def _pin_pip_configuration(allowed_keys):
49
+ """Ignore pip config-file and environment keys that could change target options."""
50
+ from pip._internal.cli import parser
51
+ from pip._internal.commands import create_command
52
+
53
+ original_items = parser.ConfigOptionParser._get_ordered_configuration_items
54
+
55
+ def configuration_items(self):
56
+ for key, value in original_items(self):
57
+ if key.replace("_", "-").lower() in allowed_keys:
58
+ yield key, value
59
+
60
+ parser.ConfigOptionParser._get_ordered_configuration_items = configuration_items
61
+
62
+ probes = {"PIP_PLATFORM": "pycontainer-self-test", "PIP_TIMEOUT": "123"}
63
+ # Hide other host PIP_* values (aliases such as PIP_DEFAULT_TIMEOUT) during the probe.
64
+ saved = {
65
+ name: value
66
+ for name, value in os.environ.items()
67
+ if name.upper().startswith(("PIP_", "_PIP_")) and name.upper() != "PIP_CONFIG_FILE"
68
+ }
69
+ for name in saved:
70
+ del os.environ[name]
71
+ os.environ.update(probes)
72
+ try:
73
+ options, _ = create_command("install").parse_args([])
74
+ finally:
75
+ for name in probes:
76
+ os.environ.pop(name, None)
77
+ os.environ.update(saved)
78
+ if options.platforms or options.timeout != 123:
79
+ raise TargetMarkerError("pip configuration pinning self-test failed")
80
+
81
+
82
+ def _freeze_pip_configuration(snapshot):
83
+ from pip._internal.cli import parser
84
+ from pip._internal.commands import create_command
85
+ from pip._internal.configuration import Configuration
86
+
87
+ original_items = parser.ConfigOptionParser._get_ordered_configuration_items
88
+ shape_probe = Configuration(isolated=False)
89
+ shape_probe.get_environ_vars = lambda: [("timeout", "123")]
90
+ shape_probe._load_environment_vars()
91
+ probe_values = [value for _, value in shape_probe.items()]
92
+ if probe_values == ["123"]:
93
+ flattened = {}
94
+ for values in snapshot["configuration"]:
95
+ flattened.update(values)
96
+ frozen_items = tuple(flattened.items())
97
+ elif probe_values == [{":env:.timeout": "123"}]:
98
+ frozen_items = tuple(enumerate(snapshot["configuration"]))
99
+ else:
100
+ raise TargetMarkerError("unsupported pip configuration shape")
101
+
102
+ class FrozenConfiguration:
103
+ def items(self):
104
+ return iter(frozen_items)
105
+
106
+ def configuration_items(self):
107
+ configuration = self.config
108
+ self.config = FrozenConfiguration()
109
+ try:
110
+ yield from original_items(self)
111
+ finally:
112
+ self.config = configuration
113
+
114
+ parser.ConfigOptionParser._get_ordered_configuration_items = configuration_items
115
+ probe = create_command("install").parser
116
+ probe.config.load()
117
+ if list(probe._get_ordered_configuration_items()) != [
118
+ tuple(item) for item in snapshot["ordered"]
119
+ ]:
120
+ raise TargetMarkerError("pip configuration snapshot self-test failed")
121
+
122
+
123
+ def main():
124
+ config = json.loads(sys.argv[1])
125
+ pip_args = sys.argv[2:]
126
+ environment = config["environment"]
127
+ allowed = set(environment) | {"extra"}
128
+ violations = []
129
+
130
+ try:
131
+ from pip._vendor.packaging import markers
132
+ from pip._vendor.packaging.requirements import Requirement
133
+
134
+ original_evaluate = markers.Marker.evaluate
135
+ original_default_environment = markers.default_environment
136
+
137
+ def default_environment():
138
+ # Unknown keys keep host values for completeness; markers that use them are rejected.
139
+ values = dict(original_default_environment())
140
+ values.update(environment)
141
+ return values
142
+
143
+ def evaluate(self, environment_override=None, *args, **kwargs):
144
+ try:
145
+ referenced = _variables(self._markers)
146
+ except (AttributeError, TypeError, TargetMarkerError) as exc:
147
+ violations.append(f"{self}: cannot inspect marker ({exc})")
148
+ raise TargetMarkerError(str(self)) from exc
149
+ unknown = sorted(set(referenced) - allowed)
150
+ if unknown:
151
+ violations.append(f"{self}: unknown target value for {', '.join(unknown)}")
152
+ raise TargetMarkerError(str(self))
153
+ effective = dict(environment_override or {})
154
+ effective.update(environment)
155
+ effective.setdefault("extra", "")
156
+ return original_evaluate(self, effective, *args, **kwargs)
157
+
158
+ markers.Marker.evaluate = evaluate
159
+ markers.default_environment = default_environment
160
+
161
+ machine = environment["platform_machine"]
162
+ other = "aarch64" if machine == "x86_64" else "x86_64"
163
+ version = environment["python_version"]
164
+ matching = Requirement(
165
+ f'x; platform_machine == "{machine}" and sys_platform == "linux" '
166
+ f'and python_version == "{version}"'
167
+ )
168
+ opposite = Requirement(f'x; platform_machine == "{other}"')
169
+ if not matching.marker.evaluate({"extra": ""}) or opposite.marker.evaluate(
170
+ {"extra": ""}
171
+ ):
172
+ raise TargetMarkerError("target marker self-test failed")
173
+
174
+ _pin_pip_configuration(set(config["allowed_config_keys"]))
175
+ if "configuration_snapshot" in config:
176
+ try:
177
+ with open(config["configuration_snapshot"], encoding="utf-8") as source:
178
+ _freeze_pip_configuration(json.load(source))
179
+ except (OSError, ValueError, TypeError, KeyError, AttributeError, ImportError, TargetMarkerError):
180
+ with open(config["error_file"], "w", encoding="utf-8") as error_file:
181
+ error_file.write("pip configuration snapshot could not be verified\n")
182
+ sys.exit(SNAPSHOT_ERROR_EXIT)
183
+ except Exception as exc:
184
+ with open(config["error_file"], "w", encoding="utf-8") as error_file:
185
+ error_file.write(f"pip could not be pinned to the target: {exc}\n")
186
+ sys.exit(PATCH_ERROR_EXIT)
187
+
188
+ sys.argv = ["pip", *pip_args]
189
+ try:
190
+ runpy.run_module("pip", run_name="__main__", alter_sys=True)
191
+ code = 0
192
+ except SystemExit as exc:
193
+ code = exc.code
194
+ if violations:
195
+ with open(config["error_file"], "w", encoding="utf-8") as error_file:
196
+ error_file.write("\n".join(dict.fromkeys(violations)) + "\n")
197
+ sys.exit(MARKER_ERROR_EXIT)
198
+ sys.exit(code)
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()