repro-lambda 0.1.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.
@@ -0,0 +1,3 @@
1
+ """repro-lambda — reproducible AWS Lambda packaging outside Terraform."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,6 @@
1
+ """Allow `python -m repro_lambda ...` invocation."""
2
+
3
+ from repro_lambda.cli import app
4
+
5
+ if __name__ == "__main__":
6
+ app()
repro_lambda/build.py ADDED
@@ -0,0 +1,141 @@
1
+ """Orchestrate stage -> hash -> probe -> build -> upload -> catalog for one lambda."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import enum
6
+ import tempfile
7
+ from dataclasses import dataclass
8
+ from datetime import UTC, datetime
9
+ from pathlib import Path
10
+
11
+ from repro_lambda import __version__
12
+ from repro_lambda.catalog import Catalog, CatalogEntry
13
+ from repro_lambda.docker_runner import build_python_lambda
14
+ from repro_lambda.hasher import compute_content_hash
15
+ from repro_lambda.manifest import BuilderConfig, LambdaSpec
16
+ from repro_lambda.s3_uploader import S3Uploader, UploadResult
17
+ from repro_lambda.source_stager import stage_source
18
+
19
+
20
+ class BuildResult(enum.Enum):
21
+ CACHE_HIT = "cache_hit"
22
+ BUILT_AND_UPLOADED = "built_and_uploaded"
23
+ DRY_RUN = "dry_run"
24
+
25
+
26
+ @dataclass
27
+ class BuildOutcome:
28
+ outcome: BuildResult
29
+ sha256: str
30
+ bucket_key: str
31
+
32
+
33
+ def _bucket_for(spec: LambdaSpec, base_bucket: str) -> str:
34
+ if spec.region == "us-east-1":
35
+ return f"{base_bucket}-us-east-1"
36
+ return base_bucket
37
+
38
+
39
+ def compute_sha_for(
40
+ *,
41
+ repo_root: Path,
42
+ spec: LambdaSpec,
43
+ builder: BuilderConfig,
44
+ ) -> str:
45
+ """Stage source and compute the content hash; tempdir disposed on exit."""
46
+ with tempfile.TemporaryDirectory(prefix="repro-lambda-") as td:
47
+ stage_dir = Path(td)
48
+ stage_source(
49
+ repo_root=repo_root,
50
+ source_dir=spec.source_dir,
51
+ builder=builder,
52
+ stage_dir=stage_dir,
53
+ )
54
+ lock_path = repo_root / spec.resolved_requirements_lock
55
+ if not lock_path.exists():
56
+ raise FileNotFoundError(f"requirements lock not found: {lock_path}")
57
+ return compute_content_hash(
58
+ staged_source_root=stage_dir / "source",
59
+ requirements_lock=lock_path,
60
+ spec=spec,
61
+ base_image=builder.base_image_python,
62
+ builder_version=__version__,
63
+ )
64
+
65
+
66
+ def build_one(
67
+ *,
68
+ repo_root: Path,
69
+ spec: LambdaSpec,
70
+ builder: BuilderConfig,
71
+ bucket: str,
72
+ catalog: Catalog,
73
+ source_commit: str,
74
+ dry_run: bool = False,
75
+ ) -> BuildOutcome:
76
+ """Build one lambda end-to-end. Returns BuildOutcome with sha + cache verdict."""
77
+ target_bucket = _bucket_for(spec, bucket)
78
+
79
+ with tempfile.TemporaryDirectory(prefix="repro-lambda-") as td:
80
+ stage_dir = Path(td)
81
+ stage_source(
82
+ repo_root=repo_root,
83
+ source_dir=spec.source_dir,
84
+ builder=builder,
85
+ stage_dir=stage_dir,
86
+ )
87
+ lock_path = repo_root / spec.resolved_requirements_lock
88
+ sha = compute_content_hash(
89
+ staged_source_root=stage_dir / "source",
90
+ requirements_lock=lock_path,
91
+ spec=spec,
92
+ base_image=builder.base_image_python,
93
+ builder_version=__version__,
94
+ )
95
+ bucket_key = f"lambdas/{spec.logical_name}/{sha}.zip"
96
+
97
+ if dry_run:
98
+ return BuildOutcome(BuildResult.DRY_RUN, sha, bucket_key)
99
+
100
+ uploader = S3Uploader(region=spec.region)
101
+ if uploader.exists(bucket=target_bucket, key=bucket_key):
102
+ _record(catalog, spec, sha, source_commit, builder)
103
+ return BuildOutcome(BuildResult.CACHE_HIT, sha, bucket_key)
104
+
105
+ out_zip = stage_dir / "lambda.zip"
106
+ (stage_dir / "requirements.lock").write_bytes(lock_path.read_bytes())
107
+ build_python_lambda(
108
+ stage_dir=stage_dir,
109
+ out_zip=out_zip,
110
+ base_image=builder.base_image_python,
111
+ arch=spec.arch,
112
+ python_version=spec.runtime.removeprefix("python"),
113
+ )
114
+
115
+ result = uploader.upload(bucket=target_bucket, key=bucket_key, body_path=out_zip)
116
+ assert result in {UploadResult.UPLOADED, UploadResult.ALREADY_PRESENT}
117
+
118
+ _record(catalog, spec, sha, source_commit, builder)
119
+ return BuildOutcome(BuildResult.BUILT_AND_UPLOADED, sha, bucket_key)
120
+
121
+
122
+ def _record(
123
+ catalog: Catalog,
124
+ spec: LambdaSpec,
125
+ sha: str,
126
+ source_commit: str,
127
+ builder: BuilderConfig,
128
+ ) -> None:
129
+ catalog.record(
130
+ spec.logical_name,
131
+ CatalogEntry(
132
+ sha256=sha,
133
+ source_commit=source_commit,
134
+ runtime=spec.runtime,
135
+ arch=spec.arch,
136
+ region=spec.region,
137
+ builder_version=__version__,
138
+ base_image_digest=builder.base_image_python.split("@", 1)[-1],
139
+ built_at=datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
140
+ ),
141
+ )
@@ -0,0 +1,71 @@
1
+ """builds/catalog.json — bounded per-lambda build history committed to source repo."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import asdict, dataclass, field
7
+ from pathlib import Path
8
+
9
+ SCHEMA_VERSION = 1
10
+ MAX_HISTORY = 10
11
+
12
+
13
+ @dataclass
14
+ class CatalogEntry:
15
+ sha256: str
16
+ source_commit: str
17
+ runtime: str
18
+ arch: str
19
+ region: str
20
+ builder_version: str
21
+ base_image_digest: str
22
+ built_at: str # ISO-8601 UTC, e.g. "2026-05-27T09:30:00Z"
23
+
24
+
25
+ @dataclass
26
+ class LambdaCatalog:
27
+ current: str
28
+ history: list[CatalogEntry] = field(default_factory=list)
29
+
30
+
31
+ @dataclass
32
+ class Catalog:
33
+ lambdas: dict[str, LambdaCatalog]
34
+
35
+ def record(self, logical_name: str, entry: CatalogEntry) -> None:
36
+ lc = self.lambdas.get(logical_name)
37
+ if lc is None:
38
+ self.lambdas[logical_name] = LambdaCatalog(current=entry.sha256, history=[entry])
39
+ return
40
+ if lc.current == entry.sha256:
41
+ return
42
+ lc.history.insert(0, entry)
43
+ lc.current = entry.sha256
44
+ lc.history = lc.history[:MAX_HISTORY]
45
+
46
+ def save(self, path: Path) -> None:
47
+ path.parent.mkdir(parents=True, exist_ok=True)
48
+ payload = {
49
+ "schema_version": SCHEMA_VERSION,
50
+ "lambdas": {
51
+ name: {
52
+ "current": lc.current,
53
+ "history": [asdict(e) for e in lc.history],
54
+ }
55
+ for name, lc in self.lambdas.items()
56
+ },
57
+ }
58
+ path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
59
+
60
+
61
+ def load_catalog(path: Path) -> Catalog:
62
+ if not path.exists():
63
+ return Catalog(lambdas={})
64
+ raw = json.loads(path.read_text())
65
+ if raw.get("schema_version") != SCHEMA_VERSION:
66
+ raise ValueError(f"{path}: unsupported schema_version {raw.get('schema_version')!r}")
67
+ lambdas: dict[str, LambdaCatalog] = {}
68
+ for name, lc in raw.get("lambdas", {}).items():
69
+ history = [CatalogEntry(**e) for e in lc.get("history", [])]
70
+ lambdas[name] = LambdaCatalog(current=lc["current"], history=history)
71
+ return Catalog(lambdas=lambdas)
repro_lambda/cli.py ADDED
@@ -0,0 +1,219 @@
1
+ """repro-lambda CLI entrypoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+ from typing import Annotated
8
+
9
+ import typer
10
+
11
+ from repro_lambda import __version__
12
+
13
+ app = typer.Typer(
14
+ name="repro-lambda",
15
+ help="Build reproducible AWS Lambda packages outside Terraform.",
16
+ no_args_is_help=True,
17
+ )
18
+
19
+
20
+ ARCH_TO_UV_PLATFORM = {
21
+ "arm64": "aarch64-manylinux_2_28",
22
+ "x86_64": "x86_64-manylinux_2_28",
23
+ }
24
+
25
+
26
+ def _version_callback(value: bool) -> None:
27
+ if value:
28
+ typer.echo(__version__)
29
+ raise typer.Exit()
30
+
31
+
32
+ @app.callback()
33
+ def main(
34
+ version: Annotated[
35
+ bool,
36
+ typer.Option(
37
+ "--version",
38
+ help="Show version and exit.",
39
+ callback=_version_callback,
40
+ is_eager=True,
41
+ ),
42
+ ] = False,
43
+ ) -> None:
44
+ """Top-level callback. The --version flag is the only global option."""
45
+ _ = version
46
+
47
+
48
+ @app.command()
49
+ def build(
50
+ target: Annotated[str, typer.Argument(help="Lambda logical_name or 'all'.")] = "all",
51
+ manifest: Annotated[
52
+ Path,
53
+ typer.Option("--manifest", "-m", help="Path to lambdas.toml."),
54
+ ] = Path("lambdas.toml"),
55
+ bucket: Annotated[
56
+ str,
57
+ typer.Option(
58
+ "--bucket",
59
+ envvar="REPRO_LAMBDA_BUCKET",
60
+ help="Base S3 bucket name (us-east-1 variant auto-derived).",
61
+ ),
62
+ ] = "",
63
+ verify: Annotated[bool, typer.Option("--verify")] = False,
64
+ dry_run: Annotated[bool, typer.Option("--dry-run")] = False,
65
+ allow_dirty: Annotated[bool, typer.Option("--allow-dirty")] = False,
66
+ ) -> None:
67
+ """Build one lambda (or all) per manifest and upload to S3."""
68
+ import json
69
+
70
+ from repro_lambda.build import build_one
71
+ from repro_lambda.catalog import load_catalog
72
+ from repro_lambda.git_guard import DirtyWorktreeError, ensure_clean_worktree
73
+ from repro_lambda.manifest import load_manifest
74
+
75
+ repo_root = manifest.parent.resolve()
76
+ parsed = load_manifest(manifest)
77
+
78
+ selected = (
79
+ parsed.lambdas
80
+ if target == "all"
81
+ else [s for s in parsed.lambdas if s.logical_name == target]
82
+ )
83
+ if not selected:
84
+ typer.echo(f"no lambda named {target!r} in {manifest}", err=True)
85
+ raise typer.Exit(2)
86
+
87
+ if not dry_run and not bucket:
88
+ typer.echo(
89
+ "--bucket or REPRO_LAMBDA_BUCKET env var is required for non-dry-run",
90
+ err=True,
91
+ )
92
+ raise typer.Exit(2)
93
+
94
+ for spec in selected:
95
+ try:
96
+ ensure_clean_worktree(
97
+ repo_root=repo_root,
98
+ source_dir=spec.source_dir,
99
+ allow_dirty=allow_dirty,
100
+ )
101
+ except DirtyWorktreeError as e:
102
+ typer.echo(str(e), err=True)
103
+ raise typer.Exit(2) from e
104
+
105
+ catalog_path = repo_root / "builds" / "catalog.json"
106
+ catalog = load_catalog(catalog_path)
107
+
108
+ try:
109
+ source_commit = subprocess.run(
110
+ ["git", "rev-parse", "HEAD"],
111
+ cwd=repo_root,
112
+ check=True,
113
+ capture_output=True,
114
+ text=True,
115
+ ).stdout.strip()
116
+ except subprocess.CalledProcessError:
117
+ source_commit = "unknown"
118
+
119
+ summary = []
120
+ for spec in selected:
121
+ outcome = build_one(
122
+ repo_root=repo_root,
123
+ spec=spec,
124
+ builder=parsed.builder,
125
+ bucket=bucket or "dry-run",
126
+ catalog=catalog,
127
+ source_commit=source_commit,
128
+ dry_run=dry_run,
129
+ )
130
+ summary.append(
131
+ {
132
+ "logical_name": spec.logical_name,
133
+ "outcome": outcome.outcome.value,
134
+ "sha256": outcome.sha256,
135
+ "bucket_key": outcome.bucket_key,
136
+ }
137
+ )
138
+
139
+ if verify:
140
+ from repro_lambda.verify import ReproducibilityError, verify_reproducible
141
+
142
+ for spec in selected:
143
+ try:
144
+ sha_a, _sha_b = verify_reproducible(
145
+ repo_root=repo_root,
146
+ spec=spec,
147
+ builder=parsed.builder,
148
+ )
149
+ typer.echo(f"verify {spec.logical_name}: reproducible (sha={sha_a})")
150
+ except ReproducibilityError as e:
151
+ typer.echo(f"verify {spec.logical_name}: FAILED — {e}", err=True)
152
+ raise typer.Exit(1) from e
153
+
154
+ if not dry_run:
155
+ catalog.save(catalog_path)
156
+
157
+ typer.echo(json.dumps(summary, indent=2))
158
+
159
+
160
+ @app.command()
161
+ def lock(
162
+ manifest: Annotated[Path, typer.Option("--manifest", "-m")] = Path("lambdas.toml"),
163
+ ) -> None:
164
+ """Regenerate per-arch requirements.${arch}.lock files via `uv pip compile`."""
165
+ from repro_lambda.manifest import load_manifest
166
+
167
+ parsed = load_manifest(manifest)
168
+ repo_root = manifest.parent.resolve()
169
+
170
+ for spec in parsed.lambdas:
171
+ requirements_in = repo_root / spec.source_dir / "requirements.in"
172
+ if not requirements_in.exists():
173
+ typer.echo(f"skip {spec.logical_name}: no {requirements_in}", err=True)
174
+ continue
175
+ lock_path = repo_root / spec.resolved_requirements_lock
176
+ uv_platform = ARCH_TO_UV_PLATFORM[spec.arch]
177
+ py_version = spec.runtime.removeprefix("python")
178
+ cmd = [
179
+ "uv",
180
+ "pip",
181
+ "compile",
182
+ str(requirements_in),
183
+ "--python-version",
184
+ py_version,
185
+ "--python-platform",
186
+ uv_platform,
187
+ "--generate-hashes",
188
+ "-o",
189
+ str(lock_path),
190
+ ]
191
+ result = subprocess.run(cmd, check=False, capture_output=True, text=True)
192
+ if result.returncode != 0:
193
+ typer.echo(f"lock {spec.logical_name} failed: {result.stderr}", err=True)
194
+ raise typer.Exit(result.returncode)
195
+ typer.echo(f"lock {spec.logical_name}: wrote {lock_path}")
196
+
197
+
198
+ @app.command()
199
+ def init() -> None:
200
+ """Scaffold lambdas.toml and CI caller workflow."""
201
+ typer.echo("init stub")
202
+ raise typer.Exit(0)
203
+
204
+
205
+ def _zip_impl(src: Path, out: Path) -> None:
206
+ """Pack a directory into a deterministic zip (used inside container)."""
207
+ from repro_lambda.zip_packager import pack_directory
208
+
209
+ pack_directory(src, out)
210
+
211
+
212
+ @app.command(name="zip")
213
+ def zip_(
214
+ src: Annotated[Path, typer.Option("--src", help="Staged package directory.")],
215
+ out: Annotated[Path, typer.Option("--out", help="Output zip path.")],
216
+ ) -> None:
217
+ """Pack a directory into a deterministic zip (used inside container)."""
218
+ _zip_impl(src, out)
219
+ raise typer.Exit(0)
@@ -0,0 +1,122 @@
1
+ """Run pip install + cleanup + zip inside a digest-pinned Docker container."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ ARCH_TO_DOCKER_PLATFORM: dict[str, str] = {
10
+ "arm64": "linux/arm64",
11
+ "x86_64": "linux/amd64",
12
+ }
13
+
14
+ ARCH_TO_PIP_PLATFORM: dict[str, str] = {
15
+ "arm64": "manylinux_2_28_aarch64",
16
+ "x86_64": "manylinux_2_28_x86_64",
17
+ }
18
+
19
+
20
+ class DockerRunError(RuntimeError):
21
+ pass
22
+
23
+
24
+ _CONTAINER_SCRIPT = r"""
25
+ set -euxo pipefail
26
+ PKG=/build/pkg
27
+ mkdir -p "$PKG"
28
+
29
+ pip install \
30
+ --no-cache-dir --no-compile \
31
+ --require-hashes --only-binary=:all: \
32
+ --platform "$PIP_PLATFORM" \
33
+ --python-version "$PY_VERSION" \
34
+ --implementation cp --abi "cp${PY_VERSION//./}" \
35
+ --target "$PKG" \
36
+ -r /src/requirements.lock
37
+
38
+ find "$PKG" -depth -type d -name "__pycache__" -exec rm -rf {} +
39
+ find "$PKG" -type f -name "*.pyc" -delete
40
+ find "$PKG" -type d -name "*.dist-info" -exec sh -c \
41
+ 'rm -f "$1/RECORD" "$1/INSTALLER" "$1/direct_url.json"' _ {} \;
42
+
43
+ cp -R /src/source/. "$PKG/"
44
+
45
+ python -m repro_lambda zip --src "$PKG" --out /out/lambda.zip
46
+ """
47
+
48
+
49
+ def _builder_module_root() -> Path:
50
+ """Return the on-host directory containing the installed repro_lambda package."""
51
+ import repro_lambda
52
+
53
+ return Path(repro_lambda.__file__).parent.parent
54
+
55
+
56
+ def build_python_lambda(
57
+ *,
58
+ stage_dir: Path,
59
+ out_zip: Path,
60
+ base_image: str,
61
+ arch: str,
62
+ python_version: str,
63
+ ) -> None:
64
+ """
65
+ Docker-run pip install + cleanup + zip in a digest-pinned container, mounting
66
+ the host-staged source and the host-side repro_lambda package read-only.
67
+
68
+ Mounts:
69
+ stage_dir -> /src (ro) must contain source/ + requirements.lock
70
+ builder_root -> /builder (ro) PYTHONPATH so `python -m repro_lambda` resolves
71
+ out_dir(out_zip) -> /out (rw) destination for lambda.zip
72
+ """
73
+ if arch not in ARCH_TO_DOCKER_PLATFORM:
74
+ raise DockerRunError(
75
+ f"unsupported arch {arch!r}; supported: {list(ARCH_TO_DOCKER_PLATFORM)}"
76
+ )
77
+ if shutil.which("docker") is None:
78
+ raise DockerRunError("docker CLI not found on PATH")
79
+
80
+ docker_platform = ARCH_TO_DOCKER_PLATFORM[arch]
81
+ pip_platform = ARCH_TO_PIP_PLATFORM[arch]
82
+
83
+ out_dir = out_zip.parent
84
+ out_dir.mkdir(parents=True, exist_ok=True)
85
+ builder_root = _builder_module_root()
86
+
87
+ cmd = [
88
+ "docker",
89
+ "run",
90
+ "--rm",
91
+ "--platform",
92
+ docker_platform,
93
+ "-v",
94
+ f"{stage_dir}:/src:ro",
95
+ "-v",
96
+ f"{builder_root}:/builder:ro",
97
+ "-v",
98
+ f"{out_dir}:/out",
99
+ "-e",
100
+ "PYTHONPATH=/builder",
101
+ "-e",
102
+ f"PIP_PLATFORM={pip_platform}",
103
+ "-e",
104
+ f"PY_VERSION={python_version}",
105
+ "--entrypoint",
106
+ "bash",
107
+ base_image,
108
+ "-euxc",
109
+ _CONTAINER_SCRIPT,
110
+ ]
111
+
112
+ result = subprocess.run(cmd, capture_output=True, text=True)
113
+ if result.returncode != 0:
114
+ raise DockerRunError(
115
+ f"docker build failed (exit {result.returncode}):\n"
116
+ f"--- stderr ---\n{result.stderr}\n"
117
+ f"--- stdout ---\n{result.stdout}\n"
118
+ )
119
+
120
+ produced = out_dir / "lambda.zip"
121
+ if produced != out_zip:
122
+ produced.rename(out_zip)
@@ -0,0 +1,39 @@
1
+ """Refuse to build with uncommitted tracked changes (unless --allow-dirty)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+
9
+ class DirtyWorktreeError(RuntimeError):
10
+ """Raised when source_dir has uncommitted tracked changes."""
11
+
12
+
13
+ def ensure_clean_worktree(
14
+ *,
15
+ repo_root: Path,
16
+ source_dir: str,
17
+ allow_dirty: bool = False,
18
+ ) -> None:
19
+ if allow_dirty:
20
+ return
21
+ result = subprocess.run(
22
+ [
23
+ "git",
24
+ "status",
25
+ "--porcelain",
26
+ "--untracked-files=no",
27
+ "--",
28
+ source_dir,
29
+ ],
30
+ cwd=repo_root,
31
+ check=True,
32
+ capture_output=True,
33
+ text=True,
34
+ )
35
+ if result.stdout.strip():
36
+ raise DirtyWorktreeError(
37
+ f"Uncommitted changes in {source_dir}:\n{result.stdout}"
38
+ "Commit or pass --allow-dirty for local iteration."
39
+ )
repro_lambda/hasher.py ADDED
@@ -0,0 +1,56 @@
1
+ """Compute the content hash that keys S3 artifacts and decides cache reuse."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from pathlib import Path
7
+
8
+ from repro_lambda.manifest import LambdaSpec
9
+
10
+
11
+ def _sha256_file(path: Path) -> str:
12
+ h = hashlib.sha256()
13
+ with path.open("rb") as f:
14
+ for chunk in iter(lambda: f.read(64 * 1024), b""):
15
+ h.update(chunk)
16
+ return h.hexdigest()
17
+
18
+
19
+ def compute_content_hash(
20
+ staged_source_root: Path,
21
+ requirements_lock: Path,
22
+ spec: LambdaSpec,
23
+ base_image: str,
24
+ builder_version: str,
25
+ ) -> str:
26
+ """
27
+ sha256 over: sorted (relative-path, sha256(content)) tuples for the staged tree
28
+ + sha256(requirements_lock) + spec scalars + base_image + builder_version.
29
+
30
+ Inputs are concatenated with newline separators in a fixed order, then hashed.
31
+ """
32
+ h = hashlib.sha256()
33
+
34
+ files = sorted(p for p in staged_source_root.rglob("*") if p.is_file())
35
+ for f in files:
36
+ rel = f.relative_to(staged_source_root).as_posix()
37
+ h.update(rel.encode("utf-8"))
38
+ h.update(b"\x00")
39
+ h.update(_sha256_file(f).encode("ascii"))
40
+ h.update(b"\n")
41
+
42
+ h.update(b"---\n")
43
+ h.update(_sha256_file(requirements_lock).encode("ascii"))
44
+ h.update(b"\n")
45
+
46
+ h.update(f"runtime={spec.runtime}\n".encode())
47
+ h.update(f"arch={spec.arch}\n".encode())
48
+ h.update(f"handler={spec.handler}\n".encode())
49
+ h.update(f"region={spec.region}\n".encode())
50
+ h.update(f"package_manager={spec.package_manager}\n".encode())
51
+ h.update(f"lambda_at_edge={int(spec.lambda_at_edge)}\n".encode())
52
+ h.update(f"hash_extra={spec.hash_extra}\n".encode())
53
+ h.update(f"base_image={base_image}\n".encode())
54
+ h.update(f"builder_version={builder_version}\n".encode())
55
+
56
+ return h.hexdigest()
@@ -0,0 +1,110 @@
1
+ """Parse and validate lambdas.toml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ SUPPORTED_RUNTIMES = {"python3.11", "python3.12", "python3.13"}
10
+ SUPPORTED_ARCHS: tuple[str, ...] = ("arm64", "x86_64")
11
+ SUPPORTED_PACKAGE_MANAGERS = {"pip"} # v0.1 — Node.js arrives in v0.2
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class LambdaSpec:
16
+ logical_name: str
17
+ source_dir: str
18
+ requirements_lock: str # template with ${arch} placeholder
19
+ runtime: str
20
+ arch: str
21
+ handler: str
22
+ region: str = "eu-west-1"
23
+ package_manager: str = "pip"
24
+ lambda_at_edge: bool = False
25
+ hash_extra: str = ""
26
+
27
+ @property
28
+ def resolved_requirements_lock(self) -> str:
29
+ return self.requirements_lock.replace("${arch}", self.arch)
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class BuilderConfig:
34
+ base_image_python: str
35
+ include_patterns: list[str] = field(default_factory=lambda: ["**/*.py", "**/*.json"])
36
+ exclude_patterns: list[str] = field(
37
+ default_factory=lambda: [
38
+ ".venv/**",
39
+ ".pytest_cache/**",
40
+ "__pycache__/**",
41
+ "*.pyc",
42
+ ".git/**",
43
+ ".env*",
44
+ ]
45
+ )
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Manifest:
50
+ lambdas: list[LambdaSpec]
51
+ builder: BuilderConfig
52
+
53
+
54
+ def load_manifest(path: Path) -> Manifest:
55
+ """Parse lambdas.toml and validate semantic invariants."""
56
+ with path.open("rb") as f:
57
+ raw = tomllib.load(f)
58
+
59
+ if "lambda" not in raw or not raw["lambda"]:
60
+ raise ValueError(f"{path}: must define at least one [[lambda]] entry")
61
+ if "builder" not in raw:
62
+ raise ValueError(f"{path}: missing [builder] section")
63
+
64
+ builder_raw = raw["builder"]
65
+ base_image = builder_raw.get("base_image_python", "")
66
+ if "@sha256:" not in base_image:
67
+ raise ValueError(
68
+ f"{path}: builder.base_image_python must be pinned by digest "
69
+ f"(got {base_image!r}; need image@sha256:<digest>)"
70
+ )
71
+
72
+ defaults = BuilderConfig(base_image_python=base_image)
73
+ builder = BuilderConfig(
74
+ base_image_python=base_image,
75
+ include_patterns=list(builder_raw.get("include_patterns", defaults.include_patterns)),
76
+ exclude_patterns=list(builder_raw.get("exclude_patterns", defaults.exclude_patterns)),
77
+ )
78
+
79
+ lambdas: list[LambdaSpec] = []
80
+ for entry in raw["lambda"]:
81
+ runtime = entry.get("runtime")
82
+ if runtime not in SUPPORTED_RUNTIMES:
83
+ raise ValueError(
84
+ f"{path}: unsupported runtime {runtime!r}; supported: {sorted(SUPPORTED_RUNTIMES)}"
85
+ )
86
+ arch = entry.get("arch")
87
+ if arch not in SUPPORTED_ARCHS:
88
+ raise ValueError(
89
+ f"{path}: unsupported arch {arch!r}; supported: {list(SUPPORTED_ARCHS)}"
90
+ )
91
+ pkg = entry.get("package_manager", "pip")
92
+ if pkg not in SUPPORTED_PACKAGE_MANAGERS:
93
+ raise ValueError(f"{path}: unsupported package_manager {pkg!r}; v0.1 supports pip only")
94
+
95
+ lambdas.append(
96
+ LambdaSpec(
97
+ logical_name=entry["logical_name"],
98
+ source_dir=entry["source_dir"],
99
+ requirements_lock=entry["requirements_lock"],
100
+ runtime=runtime,
101
+ arch=arch,
102
+ handler=entry["handler"],
103
+ region=entry.get("region", "eu-west-1"),
104
+ package_manager=pkg,
105
+ lambda_at_edge=bool(entry.get("lambda_at_edge", False)),
106
+ hash_extra=entry.get("hash_extra", ""),
107
+ )
108
+ )
109
+
110
+ return Manifest(lambdas=lambdas, builder=builder)
@@ -0,0 +1,53 @@
1
+ """Idempotent S3 upload helper that relies on bucket-policy immutability."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import enum
6
+ from pathlib import Path
7
+
8
+ import boto3
9
+ from botocore.exceptions import ClientError
10
+
11
+
12
+ class UploadResult(enum.Enum):
13
+ UPLOADED = "uploaded"
14
+ ALREADY_PRESENT = "already_present"
15
+
16
+
17
+ class S3Uploader:
18
+ def __init__(self, region: str, client=None) -> None:
19
+ self._client = client or boto3.client("s3", region_name=region)
20
+
21
+ def exists(self, *, bucket: str, key: str) -> bool:
22
+ try:
23
+ self._client.head_object(Bucket=bucket, Key=key)
24
+ return True
25
+ except ClientError as e:
26
+ code = e.response.get("Error", {}).get("Code", "")
27
+ if code in ("404", "NoSuchKey", "NotFound"):
28
+ return False
29
+ raise
30
+
31
+ def upload(self, *, bucket: str, key: str, body_path: Path) -> UploadResult:
32
+ """
33
+ PutObject with If-None-Match=*.
34
+
35
+ On 412 PreconditionFailed (key already exists) returns ALREADY_PRESENT.
36
+ Any other error is re-raised.
37
+ """
38
+ body = body_path.read_bytes()
39
+ try:
40
+ self._client.put_object(
41
+ Bucket=bucket,
42
+ Key=key,
43
+ Body=body,
44
+ IfNoneMatch="*",
45
+ ServerSideEncryption="AES256",
46
+ )
47
+ return UploadResult.UPLOADED
48
+ except ClientError as e:
49
+ code = e.response.get("Error", {}).get("Code", "")
50
+ status = e.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
51
+ if code == "PreconditionFailed" or status == 412:
52
+ return UploadResult.ALREADY_PRESENT
53
+ raise
@@ -0,0 +1,68 @@
1
+ """Stage git-tracked source files into a tempdir before container build."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import shutil
7
+ import subprocess
8
+ from pathlib import Path
9
+
10
+ from repro_lambda.manifest import BuilderConfig
11
+
12
+
13
+ def _git_ls_files(repo_root: Path, source_dir: str) -> list[str]:
14
+ """Return paths of all tracked files under source_dir, relative to repo_root."""
15
+ result = subprocess.run(
16
+ ["git", "ls-files", "--cached", "-z", "--", source_dir],
17
+ cwd=repo_root,
18
+ check=True,
19
+ capture_output=True,
20
+ )
21
+ raw = result.stdout.decode("utf-8")
22
+ return [p for p in raw.split("\x00") if p]
23
+
24
+
25
+ def _matches_any(path: str, patterns: list[str]) -> bool:
26
+ return any(fnmatch.fnmatch(path, p) for p in patterns)
27
+
28
+
29
+ def _filter_paths(paths: list[str], include: list[str], exclude: list[str]) -> list[str]:
30
+ kept: list[str] = []
31
+ for p in paths:
32
+ if include and not _matches_any(p, include):
33
+ continue
34
+ if exclude and _matches_any(p, exclude):
35
+ continue
36
+ kept.append(p)
37
+ return kept
38
+
39
+
40
+ def stage_source(
41
+ repo_root: Path,
42
+ source_dir: str,
43
+ builder: BuilderConfig,
44
+ stage_dir: Path,
45
+ ) -> list[str]:
46
+ """
47
+ Copy git-tracked files under source_dir into stage_dir/source/, preserving perms.
48
+
49
+ Returns the sorted list of relative paths (from repo_root) that were staged.
50
+ """
51
+ tracked = _git_ls_files(repo_root, source_dir)
52
+ filtered = _filter_paths(tracked, builder.include_patterns, builder.exclude_patterns)
53
+ filtered.sort()
54
+
55
+ target_root = stage_dir / "source"
56
+ target_root.mkdir(parents=True, exist_ok=True)
57
+
58
+ for rel in filtered:
59
+ src = repo_root / rel
60
+ rel_within_source = Path(rel).relative_to(source_dir)
61
+ dst = target_root / rel_within_source
62
+ dst.parent.mkdir(parents=True, exist_ok=True)
63
+ shutil.copy2(src, dst)
64
+ src_mode = src.stat().st_mode
65
+ if src_mode & 0o111:
66
+ dst.chmod(dst.stat().st_mode | 0o111)
67
+
68
+ return filtered
repro_lambda/verify.py ADDED
@@ -0,0 +1,61 @@
1
+ """Two-pass reproducibility check: build twice in isolated stage dirs, compare sha256."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import tempfile
7
+ from pathlib import Path
8
+
9
+ from repro_lambda.docker_runner import build_python_lambda
10
+ from repro_lambda.manifest import BuilderConfig, LambdaSpec
11
+ from repro_lambda.source_stager import stage_source
12
+
13
+
14
+ class ReproducibilityError(RuntimeError):
15
+ pass
16
+
17
+
18
+ def _sha256(path: Path) -> str:
19
+ h = hashlib.sha256()
20
+ with path.open("rb") as f:
21
+ for chunk in iter(lambda: f.read(64 * 1024), b""):
22
+ h.update(chunk)
23
+ return h.hexdigest()
24
+
25
+
26
+ def verify_reproducible(
27
+ *,
28
+ repo_root: Path,
29
+ spec: LambdaSpec,
30
+ builder: BuilderConfig,
31
+ ) -> tuple[str, str]:
32
+ """
33
+ Run the build twice in independent tempdirs and compare zip sha256.
34
+
35
+ Returns (sha_build_1, sha_build_2) on match. Raises ReproducibilityError on mismatch.
36
+ """
37
+ shas: list[str] = []
38
+ for _ in range(2):
39
+ with tempfile.TemporaryDirectory(prefix="repro-verify-") as td:
40
+ stage_dir = Path(td)
41
+ stage_source(
42
+ repo_root=repo_root,
43
+ source_dir=spec.source_dir,
44
+ builder=builder,
45
+ stage_dir=stage_dir,
46
+ )
47
+ lock_path = repo_root / spec.resolved_requirements_lock
48
+ (stage_dir / "requirements.lock").write_bytes(lock_path.read_bytes())
49
+ out_zip = stage_dir / "lambda.zip"
50
+ build_python_lambda(
51
+ stage_dir=stage_dir,
52
+ out_zip=out_zip,
53
+ base_image=builder.base_image_python,
54
+ arch=spec.arch,
55
+ python_version=spec.runtime.removeprefix("python"),
56
+ )
57
+ shas.append(_sha256(out_zip))
58
+
59
+ if shas[0] != shas[1]:
60
+ raise ReproducibilityError(f"two builds produced different zips: {shas[0]} vs {shas[1]}")
61
+ return shas[0], shas[1]
@@ -0,0 +1,70 @@
1
+ """Pack a staged directory into a byte-reproducible zip."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ from pathlib import Path
7
+ from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
8
+
9
+ _EPOCH = (1980, 1, 1, 0, 0, 0)
10
+
11
+
12
+ def _should_exclude(rel: str, exclude_glob: list[str]) -> bool:
13
+ return any(fnmatch.fnmatch(rel, pat) for pat in exclude_glob)
14
+
15
+
16
+ def _zip_mode(path: Path) -> int:
17
+ src_mode = path.stat().st_mode
18
+ if path.is_dir():
19
+ return 0o755
20
+ if src_mode & 0o111 or path.suffix in {".so", ".node"}:
21
+ return 0o755
22
+ return 0o644
23
+
24
+
25
+ def pack_directory(
26
+ src: Path,
27
+ out: Path,
28
+ *,
29
+ exclude_glob: list[str] | None = None,
30
+ ) -> None:
31
+ """
32
+ Pack `src` recursively into `out` as a deterministic zip.
33
+
34
+ Reproducibility properties set explicitly on every entry:
35
+ - Entries sorted alphabetically by POSIX relpath
36
+ - mtime forced to 1980-01-01 00:00:00
37
+ - Directory entries 0o755; files 0o644 (or 0o755 if executable / .so / .node)
38
+ - create_system = 3 (unix) so external_attr is interpreted as unix mode
39
+
40
+ Uses stdlib zipfile directly because repro_zipfile normalizes external_attr in a
41
+ way that strips per-file mode bits we need to preserve.
42
+ """
43
+ exclude_glob = exclude_glob or []
44
+
45
+ paths: list[Path] = []
46
+ for p in src.rglob("*"):
47
+ rel = p.relative_to(src).as_posix()
48
+ if _should_exclude(rel, exclude_glob):
49
+ continue
50
+ paths.append(p)
51
+
52
+ paths.sort(key=lambda p: p.relative_to(src).as_posix())
53
+
54
+ out.parent.mkdir(parents=True, exist_ok=True)
55
+ with ZipFile(out, "w", compression=ZIP_DEFLATED) as zf:
56
+ for p in paths:
57
+ rel = p.relative_to(src).as_posix()
58
+ zinfo = ZipInfo(
59
+ filename=(rel + "/") if p.is_dir() else rel,
60
+ date_time=_EPOCH,
61
+ )
62
+ zinfo.create_system = 3
63
+ mode = _zip_mode(p)
64
+ zinfo.external_attr = (mode & 0xFFFF) << 16
65
+ if p.is_dir():
66
+ zinfo.external_attr |= 0x10
67
+ data = b""
68
+ else:
69
+ data = p.read_bytes()
70
+ zf.writestr(zinfo, data)
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: repro-lambda
3
+ Version: 0.1.0
4
+ Summary: Build reproducible AWS Lambda packages outside Terraform, optimized for terraform-aws-lambda by serverless.tf.
5
+ Project-URL: Homepage, https://github.com/antonbabenko/repro-lambda
6
+ Project-URL: Repository, https://github.com/antonbabenko/repro-lambda
7
+ Project-URL: Issues, https://github.com/antonbabenko/repro-lambda/issues
8
+ Author-email: Anton Babenko <anton@antonbabenko.com>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: aws,lambda,reproducible-builds,serverless,terraform
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: MacOS :: MacOS X
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Build Tools
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: boto3>=1.34
22
+ Requires-Dist: repro-zipfile>=0.3.1
23
+ Requires-Dist: typer>=0.12
24
+ Provides-Extra: dev
25
+ Requires-Dist: moto[s3]>=5; extra == 'dev'
26
+ Requires-Dist: pre-commit>=3.7; extra == 'dev'
27
+ Requires-Dist: pytest-mock>=3.12; extra == 'dev'
28
+ Requires-Dist: pytest>=8; extra == 'dev'
29
+ Requires-Dist: pyyaml>=6; extra == 'dev'
30
+ Requires-Dist: ruff>=0.5; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # repro-lambda
34
+
35
+ Build reproducible AWS Lambda packages outside Terraform, optimized for
36
+ [terraform-aws-lambda by serverless.tf](https://registry.terraform.io/modules/terraform-aws-modules/lambda/aws/latest).
37
+
38
+ Produces byte-identical zip files across local dev (macOS) and CI (Linux),
39
+ uploads to S3 by content-hash key, and lets Terraform read `s3_existing_package`
40
+ instead of building during `terraform plan`/`apply`.
41
+
42
+ ## Install
43
+
44
+ pip install repro-lambda
45
+
46
+ ## Usage
47
+
48
+ repro-lambda init # scaffold lambdas.toml and CI caller workflow
49
+ repro-lambda lock # regenerate per-arch lockfiles
50
+ repro-lambda build # build all lambdas in lambdas.toml, upload to S3
51
+ repro-lambda build --verify # two-pass byte-reproducibility check
52
+
53
+ See `docs/` for full design.
54
+
55
+ ## Release
56
+
57
+ Releases are tag-driven. To cut v0.1.1:
58
+
59
+ git tag v0.1.1
60
+ git push origin v0.1.1
61
+
62
+ The `publish.yml` workflow uses PyPI Trusted Publishing (OIDC) — no PyPI token
63
+ needed in repo secrets. Configure once via PyPI's "Publishing" panel:
64
+
65
+ - Owner: `antonbabenko`
66
+ - Repository: `repro-lambda`
67
+ - Workflow: `publish.yml`
68
+ - Environment: (leave blank)
@@ -0,0 +1,18 @@
1
+ repro_lambda/__init__.py,sha256=ZkpHpCqz2OfeNOU9veyWfnFUixyLeBt4HJZ2MH8CN8I,99
2
+ repro_lambda/__main__.py,sha256=kj1fmZneM57F0kbNd_wNDyf2RfF3s2-LGyRArkN89eg,125
3
+ repro_lambda/build.py,sha256=LaiiSEzikfefw9AKETHCzXeNMaY6TEm4x0MLi2Cr73k,4466
4
+ repro_lambda/catalog.py,sha256=Gf15RyQqflgnSDCzQ1J7H0SoSI8ClzdNjWQGnYUmgpo,2146
5
+ repro_lambda/cli.py,sha256=na_qWXHtXbhu3w_3LKhVJKYlWAnbHPdFMzMZ_OcRbeE,6545
6
+ repro_lambda/docker_runner.py,sha256=NCPVt-HQqnVEaXlALDOKVgoBJ9-3tZmyesIDmqpFVAE,3287
7
+ repro_lambda/git_guard.py,sha256=qNJ9AiD-OCBrO0EdEvZzAMNDxmoJZBSssxuJaYfEHGw,922
8
+ repro_lambda/hasher.py,sha256=5UuM_fmpUewgbjH50EkEnMt2J6YeavNqITmvE16RBCY,1794
9
+ repro_lambda/manifest.py,sha256=lnMTGAOpsEisZkz4fpUbx_9baxzIiKh11koFsNbL1y0,3642
10
+ repro_lambda/s3_uploader.py,sha256=NgW9YJnODSx7VXfX5oEOsHAuQbLFmEnORx9xvP8Ivy0,1694
11
+ repro_lambda/source_stager.py,sha256=cT4Ln5UAufQ9DzemLFbkU1JCDZKQ9Lx_VU7DtnyvlYY,2035
12
+ repro_lambda/verify.py,sha256=g-NjbHrRXZXRIqlyWM-XlTqpX6_0csw43fXWHMbXBGs,1924
13
+ repro_lambda/zip_packager.py,sha256=IPS0wNgFbGaZumOgnMTfLTRuudik2VYF468HPTPW7RM,2153
14
+ repro_lambda-0.1.0.dist-info/METADATA,sha256=vR-i0w_mbOC7p9RxmNa-BCoB5tJcxwbcOUjPJK79wwU,2555
15
+ repro_lambda-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
16
+ repro_lambda-0.1.0.dist-info/entry_points.txt,sha256=Ttp1Q08jEiPeuPo-kT2aKYM5STM-IPI4AGdXWXjGGRg,54
17
+ repro_lambda-0.1.0.dist-info/licenses/LICENSE,sha256=3Bfccb39fnXN5VkSZh8RemjW03BH4JZkTEQgREhpFNU,9554
18
+ repro_lambda-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ repro-lambda = repro_lambda.cli:app
@@ -0,0 +1,177 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined in Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
25
+ permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or Object
37
+ form, made available under the License, as indicated by a copyright
38
+ notice that is included in or attached to the work (an example is
39
+ provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original Work and any Derivative Works thereof, that is intentionally
51
+ submitted to, or received by, Licensor for inclusion in the Work
52
+ by the copyright owner or by an individual or Legal Entity authorized
53
+ to submit on behalf of the copyright owner. For the purposes of this
54
+ definition, "submitted" means any form of electronic, verbal, or
55
+ written communication sent to the Licensor or its representatives,
56
+ including but not limited to communication on electronic mailing lists,
57
+ source code control systems, and issue tracking systems that are
58
+ managed by, or on behalf of, the Licensor for the purpose of
59
+ discussing and improving the Work, but excluding communication
60
+ that is conspicuously marked or otherwise designated in writing by
61
+ the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean any individual or Legal Entity on behalf
64
+ of whom a Contribution has been received by Licensor and subsequently
65
+ incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file, then any
108
+ Derivative Works that You distribute must include a readable
109
+ copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE from the Work, provided that
121
+ such additional attribution notices cannot be construed as
122
+ modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions of this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contribution.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS