kellerlab-pre-commit-hooks 0.2.1__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KellerLabs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: kellerlab-pre-commit-hooks
3
+ Version: 0.2.1
4
+ Summary: Reusable pre-commit hooks for OpenSCAD projects
5
+ Author-email: Patrick Pötz <kellervater@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/kellerlabs/pre-commit-hooks
8
+ Project-URL: Repository, https://github.com/kellerlabs/pre-commit-hooks
9
+ Project-URL: Issues, https://github.com/kellerlabs/pre-commit-hooks/issues
10
+ Project-URL: Changelog, https://github.com/kellerlabs/pre-commit-hooks/blob/main/CHANGELOG.md
11
+ Keywords: pre-commit,openscad,image-optimization,scadm
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Classifier: Topic :: Utilities
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: scadm>=0.6.0
24
+ Requires-Dist: Pillow>=11.0.0
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # 🔧 Pre-commit Hooks
30
+
31
+ Reusable [pre-commit](https://pre-commit.com/) hooks for OpenSCAD projects.
32
+
33
+ Published on PyPI as [`kellerlab-pre-commit-hooks`](https://pypi.org/project/kellerlab-pre-commit-hooks/).
34
+
35
+ ## 📌 What
36
+
37
+ Two hooks for OpenSCAD-based 3D printing projects:
38
+
39
+ | Hook | Description |
40
+ |------|-------------|
41
+ | `flatten-validate` | Runs `scadm flatten --all` and fails if flattened files have uncommitted changes |
42
+ | `optimize-images` | Resizes oversized JPEGs, compresses them, and strips EXIF data (privacy) |
43
+
44
+ ## 🔧 Usage
45
+
46
+ Add to your `.pre-commit-config.yaml`:
47
+
48
+ ```yaml
49
+ - repo: https://github.com/kellerlabs/pre-commit-hooks
50
+ rev: v0.1.0 # use latest tag
51
+ hooks:
52
+ - id: flatten-validate
53
+ - id: optimize-images
54
+ ```
55
+
56
+ ### `flatten-validate`
57
+
58
+ Flattens OpenSCAD files via [scadm](https://pypi.org/project/scadm/) and validates that the output is committed. Reads flatten config from `scadm.json` automatically.
59
+
60
+ ```yaml
61
+ - id: flatten-validate
62
+ # Override trigger pattern (default: always_run)
63
+ always_run: false
64
+ files: '^(scadm\.json|models/.*\.scad)'
65
+ ```
66
+
67
+ **Options:**
68
+
69
+ | Arg | Default | Description |
70
+ |-----|---------|-------------|
71
+ | `--flatten-dir` | Read from `scadm.json` | Override flatten output dirs (list of paths/globs) |
72
+
73
+ ### `optimize-images`
74
+
75
+ Resizes JPEGs exceeding max width, compresses to target quality, and strips EXIF metadata (removes GPS coordinates from real-life photos).
76
+
77
+ ```yaml
78
+ - id: optimize-images
79
+ args: [--max-width=1920, --quality=85]
80
+ ```
81
+
82
+ **Options:**
83
+
84
+ | Arg | Default | Description |
85
+ |-----|---------|-------------|
86
+ | `--max-width` | `1920` | Maximum image width in pixels |
87
+ | `--quality` | `85` | JPEG compression quality (1-95) |
88
+
89
+ Both hooks **fail when files are modified**, printing instructions to `git add` the changes. Re-run `git commit` after staging.
90
+
91
+ ## 🏗️ Used In
92
+
93
+ - [kellerlabs/homeracker](https://github.com/kellerlabs/homeracker) — HomeRacker Core
94
+ - [kellerlabs/homeracker-exclusive](https://github.com/kellerlabs/homeracker-exclusive) — HomeRacker MakerWorld models
95
+
96
+ ## 🤝 Contributing
97
+
98
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
99
+
100
+ ## 📜 License
101
+
102
+ MIT
@@ -0,0 +1,74 @@
1
+ # 🔧 Pre-commit Hooks
2
+
3
+ Reusable [pre-commit](https://pre-commit.com/) hooks for OpenSCAD projects.
4
+
5
+ Published on PyPI as [`kellerlab-pre-commit-hooks`](https://pypi.org/project/kellerlab-pre-commit-hooks/).
6
+
7
+ ## 📌 What
8
+
9
+ Two hooks for OpenSCAD-based 3D printing projects:
10
+
11
+ | Hook | Description |
12
+ |------|-------------|
13
+ | `flatten-validate` | Runs `scadm flatten --all` and fails if flattened files have uncommitted changes |
14
+ | `optimize-images` | Resizes oversized JPEGs, compresses them, and strips EXIF data (privacy) |
15
+
16
+ ## 🔧 Usage
17
+
18
+ Add to your `.pre-commit-config.yaml`:
19
+
20
+ ```yaml
21
+ - repo: https://github.com/kellerlabs/pre-commit-hooks
22
+ rev: v0.1.0 # use latest tag
23
+ hooks:
24
+ - id: flatten-validate
25
+ - id: optimize-images
26
+ ```
27
+
28
+ ### `flatten-validate`
29
+
30
+ Flattens OpenSCAD files via [scadm](https://pypi.org/project/scadm/) and validates that the output is committed. Reads flatten config from `scadm.json` automatically.
31
+
32
+ ```yaml
33
+ - id: flatten-validate
34
+ # Override trigger pattern (default: always_run)
35
+ always_run: false
36
+ files: '^(scadm\.json|models/.*\.scad)'
37
+ ```
38
+
39
+ **Options:**
40
+
41
+ | Arg | Default | Description |
42
+ |-----|---------|-------------|
43
+ | `--flatten-dir` | Read from `scadm.json` | Override flatten output dirs (list of paths/globs) |
44
+
45
+ ### `optimize-images`
46
+
47
+ Resizes JPEGs exceeding max width, compresses to target quality, and strips EXIF metadata (removes GPS coordinates from real-life photos).
48
+
49
+ ```yaml
50
+ - id: optimize-images
51
+ args: [--max-width=1920, --quality=85]
52
+ ```
53
+
54
+ **Options:**
55
+
56
+ | Arg | Default | Description |
57
+ |-----|---------|-------------|
58
+ | `--max-width` | `1920` | Maximum image width in pixels |
59
+ | `--quality` | `85` | JPEG compression quality (1-95) |
60
+
61
+ Both hooks **fail when files are modified**, printing instructions to `git add` the changes. Re-run `git commit` after staging.
62
+
63
+ ## 🏗️ Used In
64
+
65
+ - [kellerlabs/homeracker](https://github.com/kellerlabs/homeracker) — HomeRacker Core
66
+ - [kellerlabs/homeracker-exclusive](https://github.com/kellerlabs/homeracker-exclusive) — HomeRacker MakerWorld models
67
+
68
+ ## 🤝 Contributing
69
+
70
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
71
+
72
+ ## 📜 License
73
+
74
+ MIT
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kellerlab-pre-commit-hooks"
7
+ version = "0.2.1"
8
+ description = "Reusable pre-commit hooks for OpenSCAD projects"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ authors = [
13
+ {name = "Patrick Pötz", email = "kellervater@gmail.com"}
14
+ ]
15
+ keywords = ["pre-commit", "openscad", "image-optimization", "scadm"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Software Development :: Quality Assurance",
24
+ "Topic :: Utilities",
25
+ ]
26
+ dependencies = [
27
+ "scadm>=0.6.0",
28
+ "Pillow>=11.0.0",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ test = [
33
+ "pytest",
34
+ ]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/kellerlabs/pre-commit-hooks"
38
+ Repository = "https://github.com/kellerlabs/pre-commit-hooks"
39
+ Issues = "https://github.com/kellerlabs/pre-commit-hooks/issues"
40
+ Changelog = "https://github.com/kellerlabs/pre-commit-hooks/blob/main/CHANGELOG.md"
41
+
42
+ [project.scripts]
43
+ flatten-validate = "pre_commit_hooks.flatten_validate:main"
44
+ optimize-images = "pre_commit_hooks.optimize_images:main"
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
48
+ include = ["pre_commit_hooks*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: kellerlab-pre-commit-hooks
3
+ Version: 0.2.1
4
+ Summary: Reusable pre-commit hooks for OpenSCAD projects
5
+ Author-email: Patrick Pötz <kellervater@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/kellerlabs/pre-commit-hooks
8
+ Project-URL: Repository, https://github.com/kellerlabs/pre-commit-hooks
9
+ Project-URL: Issues, https://github.com/kellerlabs/pre-commit-hooks/issues
10
+ Project-URL: Changelog, https://github.com/kellerlabs/pre-commit-hooks/blob/main/CHANGELOG.md
11
+ Keywords: pre-commit,openscad,image-optimization,scadm
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Classifier: Topic :: Utilities
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: scadm>=0.6.0
24
+ Requires-Dist: Pillow>=11.0.0
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # 🔧 Pre-commit Hooks
30
+
31
+ Reusable [pre-commit](https://pre-commit.com/) hooks for OpenSCAD projects.
32
+
33
+ Published on PyPI as [`kellerlab-pre-commit-hooks`](https://pypi.org/project/kellerlab-pre-commit-hooks/).
34
+
35
+ ## 📌 What
36
+
37
+ Two hooks for OpenSCAD-based 3D printing projects:
38
+
39
+ | Hook | Description |
40
+ |------|-------------|
41
+ | `flatten-validate` | Runs `scadm flatten --all` and fails if flattened files have uncommitted changes |
42
+ | `optimize-images` | Resizes oversized JPEGs, compresses them, and strips EXIF data (privacy) |
43
+
44
+ ## 🔧 Usage
45
+
46
+ Add to your `.pre-commit-config.yaml`:
47
+
48
+ ```yaml
49
+ - repo: https://github.com/kellerlabs/pre-commit-hooks
50
+ rev: v0.1.0 # use latest tag
51
+ hooks:
52
+ - id: flatten-validate
53
+ - id: optimize-images
54
+ ```
55
+
56
+ ### `flatten-validate`
57
+
58
+ Flattens OpenSCAD files via [scadm](https://pypi.org/project/scadm/) and validates that the output is committed. Reads flatten config from `scadm.json` automatically.
59
+
60
+ ```yaml
61
+ - id: flatten-validate
62
+ # Override trigger pattern (default: always_run)
63
+ always_run: false
64
+ files: '^(scadm\.json|models/.*\.scad)'
65
+ ```
66
+
67
+ **Options:**
68
+
69
+ | Arg | Default | Description |
70
+ |-----|---------|-------------|
71
+ | `--flatten-dir` | Read from `scadm.json` | Override flatten output dirs (list of paths/globs) |
72
+
73
+ ### `optimize-images`
74
+
75
+ Resizes JPEGs exceeding max width, compresses to target quality, and strips EXIF metadata (removes GPS coordinates from real-life photos).
76
+
77
+ ```yaml
78
+ - id: optimize-images
79
+ args: [--max-width=1920, --quality=85]
80
+ ```
81
+
82
+ **Options:**
83
+
84
+ | Arg | Default | Description |
85
+ |-----|---------|-------------|
86
+ | `--max-width` | `1920` | Maximum image width in pixels |
87
+ | `--quality` | `85` | JPEG compression quality (1-95) |
88
+
89
+ Both hooks **fail when files are modified**, printing instructions to `git add` the changes. Re-run `git commit` after staging.
90
+
91
+ ## 🏗️ Used In
92
+
93
+ - [kellerlabs/homeracker](https://github.com/kellerlabs/homeracker) — HomeRacker Core
94
+ - [kellerlabs/homeracker-exclusive](https://github.com/kellerlabs/homeracker-exclusive) — HomeRacker MakerWorld models
95
+
96
+ ## 🤝 Contributing
97
+
98
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
99
+
100
+ ## 📜 License
101
+
102
+ MIT
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/kellerlab_pre_commit_hooks.egg-info/PKG-INFO
5
+ src/kellerlab_pre_commit_hooks.egg-info/SOURCES.txt
6
+ src/kellerlab_pre_commit_hooks.egg-info/dependency_links.txt
7
+ src/kellerlab_pre_commit_hooks.egg-info/entry_points.txt
8
+ src/kellerlab_pre_commit_hooks.egg-info/requires.txt
9
+ src/kellerlab_pre_commit_hooks.egg-info/top_level.txt
10
+ src/pre_commit_hooks/__init__.py
11
+ src/pre_commit_hooks/flatten_validate.py
12
+ src/pre_commit_hooks/optimize_images.py
13
+ tests/test_flatten_validate.py
14
+ tests/test_optimize_images.py
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ flatten-validate = pre_commit_hooks.flatten_validate:main
3
+ optimize-images = pre_commit_hooks.optimize_images:main
@@ -0,0 +1,5 @@
1
+ scadm>=0.6.0
2
+ Pillow>=11.0.0
3
+
4
+ [test]
5
+ pytest
@@ -0,0 +1,3 @@
1
+ """Reusable pre-commit hooks for OpenSCAD projects."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,135 @@
1
+ """Pre-commit hook: flatten OpenSCAD files and validate they are committed."""
2
+
3
+ import argparse
4
+ import json
5
+ import shlex
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+
11
+ def _read_flatten_dirs():
12
+ """Read flatten destination dirs from scadm.json.
13
+
14
+ Returns:
15
+ List of destination directory paths from the flatten config,
16
+ or empty list if scadm.json is missing or has no flatten key.
17
+ """
18
+ scadm_json = Path("scadm.json")
19
+ if not scadm_json.exists():
20
+ print("WARNING: scadm.json not found, skipping flatten dir validation")
21
+ return []
22
+
23
+ with open(scadm_json, encoding="utf-8") as f:
24
+ config = json.load(f)
25
+
26
+ flatten_entries = config.get("flatten", [])
27
+ if not flatten_entries:
28
+ print("WARNING: No 'flatten' entries in scadm.json")
29
+ return []
30
+
31
+ return [entry["dest"] for entry in flatten_entries if "dest" in entry]
32
+
33
+
34
+ def _git_modified(paths):
35
+ """Get modified tracked files (not staged) under the given paths.
36
+
37
+ Args:
38
+ paths: List of directory paths to check.
39
+
40
+ Returns:
41
+ List of modified file paths.
42
+
43
+ Raises:
44
+ SystemExit: If git diff fails.
45
+ """
46
+ if not paths:
47
+ return []
48
+ result = subprocess.run(
49
+ ["git", "diff", "--name-only", "--"] + paths,
50
+ capture_output=True,
51
+ text=True,
52
+ check=False,
53
+ )
54
+ if result.returncode != 0:
55
+ print(f"ERROR: git diff failed: {result.stderr.strip()}")
56
+ sys.exit(1)
57
+ return [line for line in result.stdout.strip().split("\n") if line]
58
+
59
+
60
+ def _git_untracked(paths):
61
+ """Get untracked files under the given paths.
62
+
63
+ Args:
64
+ paths: List of directory paths to check.
65
+
66
+ Returns:
67
+ List of untracked file paths.
68
+
69
+ Raises:
70
+ SystemExit: If git ls-files fails.
71
+ """
72
+ if not paths:
73
+ return []
74
+ result = subprocess.run(
75
+ ["git", "ls-files", "--others", "--exclude-standard", "--"] + paths,
76
+ capture_output=True,
77
+ text=True,
78
+ check=False,
79
+ )
80
+ if result.returncode != 0:
81
+ print(f"ERROR: git ls-files failed: {result.stderr.strip()}")
82
+ sys.exit(1)
83
+ return [line for line in result.stdout.strip().split("\n") if line]
84
+
85
+
86
+ def main():
87
+ """Entry point for the flatten-validate pre-commit hook."""
88
+ parser = argparse.ArgumentParser(description="Validate flattened OpenSCAD exports are committed.")
89
+ parser.add_argument(
90
+ "--flatten-dir",
91
+ nargs="+",
92
+ default=None,
93
+ help="Override flatten destination dirs (default: read from scadm.json).",
94
+ )
95
+ args = parser.parse_args()
96
+
97
+ flatten_dirs = args.flatten_dir if args.flatten_dir else _read_flatten_dirs()
98
+
99
+ # Run scadm flatten
100
+ result = subprocess.run(["scadm", "flatten", "--all"], check=False)
101
+ if result.returncode != 0:
102
+ print("ERROR: scadm flatten --all failed")
103
+ return 1
104
+
105
+ if not flatten_dirs:
106
+ print("✓ No flatten directories to validate")
107
+ return 0
108
+
109
+ modified = _git_modified(flatten_dirs)
110
+ untracked = _git_untracked(flatten_dirs)
111
+
112
+ if modified or untracked:
113
+ print("")
114
+ print("ERROR: Flattened files have uncommitted/unstaged changes")
115
+ print("")
116
+ if modified:
117
+ print("Modified files (not staged):")
118
+ for f in modified:
119
+ print(f" {f}")
120
+ if untracked:
121
+ print("Untracked files:")
122
+ for f in untracked:
123
+ print(f" {f}")
124
+ dirs = " ".join(shlex.quote(d) for d in flatten_dirs)
125
+ print("")
126
+ print("Run the following to stage them:")
127
+ print(f" git add {dirs}")
128
+ return 1
129
+
130
+ print("✓ All flattened files are committed")
131
+ return 0
132
+
133
+
134
+ if __name__ == "__main__":
135
+ sys.exit(main())
@@ -0,0 +1,88 @@
1
+ """Pre-commit hook: resize and compress JPEG images."""
2
+
3
+ import argparse
4
+ import shlex
5
+ import sys
6
+
7
+ from PIL import Image, ImageOps
8
+
9
+
10
+ def _optimize_file(filepath, max_width, quality):
11
+ """Resize, compress, and strip EXIF from a single JPEG file.
12
+
13
+ Args:
14
+ filepath: Path to the JPEG file.
15
+ max_width: Maximum allowed width in pixels.
16
+ quality: JPEG compression quality (1-95).
17
+
18
+ Returns:
19
+ True if the file was modified, False otherwise.
20
+ """
21
+ with Image.open(filepath) as img:
22
+ # Apply EXIF orientation before checking size
23
+ img = ImageOps.exif_transpose(img)
24
+ width, height = img.size
25
+ needs_resize = width > max_width
26
+ has_exif = bool(img.info.get("exif"))
27
+
28
+ if not needs_resize and not has_exif:
29
+ return False
30
+
31
+ if needs_resize:
32
+ ratio = max_width / width
33
+ new_height = max(1, round(height * ratio))
34
+ new_size = (max_width, new_height)
35
+ img = img.resize(new_size, Image.LANCZOS)
36
+
37
+ if img.mode in ("RGBA", "P"):
38
+ img = img.convert("RGB")
39
+ img.save(filepath, "JPEG", quality=quality, optimize=True)
40
+
41
+ return True
42
+
43
+
44
+ def main():
45
+ """Entry point for the optimize-images pre-commit hook."""
46
+ parser = argparse.ArgumentParser(description="Resize and compress JPEG images.")
47
+ parser.add_argument("filenames", nargs="*", help="JPEG files to check.")
48
+ parser.add_argument(
49
+ "--max-width",
50
+ type=int,
51
+ default=1920,
52
+ help="Maximum image width in pixels (default: 1920).",
53
+ )
54
+ parser.add_argument(
55
+ "--quality",
56
+ type=int,
57
+ default=85,
58
+ help="JPEG compression quality 1-95 (default: 85).",
59
+ )
60
+ args = parser.parse_args()
61
+
62
+ modified = []
63
+ failed = False
64
+ for filepath in args.filenames:
65
+ try:
66
+ if _optimize_file(filepath, args.max_width, args.quality):
67
+ modified.append(filepath)
68
+ except Exception as exc: # pylint: disable=broad-exception-caught
69
+ print(f"ERROR: Failed to process {filepath}: {exc}")
70
+ failed = True
71
+
72
+ if modified:
73
+ quoted = " ".join(shlex.quote(f) for f in modified)
74
+ print("")
75
+ print("Images were resized/compressed by this hook:")
76
+ print("")
77
+ for f in modified:
78
+ print(f" {f}")
79
+ print("")
80
+ print("Run the following to stage the optimized files:")
81
+ print(f" git add {quoted}")
82
+ return 1
83
+
84
+ return 1 if failed else 0
85
+
86
+
87
+ if __name__ == "__main__":
88
+ sys.exit(main())
@@ -0,0 +1,124 @@
1
+ """Tests for flatten_validate hook."""
2
+
3
+ import json
4
+ from unittest import mock
5
+
6
+ import pytest
7
+
8
+ from pre_commit_hooks.flatten_validate import main
9
+
10
+
11
+ @pytest.fixture()
12
+ def scadm_json(tmp_path, monkeypatch):
13
+ """Create a temporary scadm.json and chdir to it."""
14
+ monkeypatch.chdir(tmp_path)
15
+ config = {
16
+ "flatten": [
17
+ {"src": "models/core/parts", "dest": "models/core/flattened"},
18
+ {"src": "models/foot/parts", "dest": "models/foot/flattened"},
19
+ ]
20
+ }
21
+ (tmp_path / "scadm.json").write_text(json.dumps(config))
22
+ return tmp_path
23
+
24
+
25
+ def _mock_run(returncode=0, stdout="", stderr=""):
26
+ """Create a mock subprocess result."""
27
+ result = mock.MagicMock()
28
+ result.returncode = returncode
29
+ result.stdout = stdout
30
+ result.stderr = stderr
31
+ return result
32
+
33
+
34
+ @pytest.mark.usefixtures("scadm_json")
35
+ class TestFlattenValidate:
36
+ """Tests for the flatten-validate hook."""
37
+
38
+ @mock.patch("pre_commit_hooks.flatten_validate.subprocess.run")
39
+ def test_all_clean(self, mock_run):
40
+ """Hook passes when all flattened files are committed."""
41
+ mock_run.side_effect = [
42
+ _mock_run(0), # scadm flatten --all
43
+ _mock_run(0, stdout=""), # git diff
44
+ _mock_run(0, stdout=""), # git ls-files
45
+ ]
46
+ with mock.patch("sys.argv", ["flatten-validate"]):
47
+ assert main() == 0
48
+
49
+ @mock.patch("pre_commit_hooks.flatten_validate.subprocess.run")
50
+ def test_modified_files(self, mock_run):
51
+ """Hook fails when flattened files have unstaged changes."""
52
+ mock_run.side_effect = [
53
+ _mock_run(0), # scadm flatten --all
54
+ _mock_run(0, stdout="models/core/flattened/foo.scad"), # git diff
55
+ _mock_run(0, stdout=""), # git ls-files
56
+ ]
57
+ with mock.patch("sys.argv", ["flatten-validate"]):
58
+ assert main() == 1
59
+
60
+ @mock.patch("pre_commit_hooks.flatten_validate.subprocess.run")
61
+ def test_untracked_files(self, mock_run):
62
+ """Hook fails when there are untracked flattened files."""
63
+ mock_run.side_effect = [
64
+ _mock_run(0), # scadm flatten --all
65
+ _mock_run(0, stdout=""), # git diff
66
+ _mock_run(0, stdout="models/foot/flattened/bar.scad"), # git ls-files
67
+ ]
68
+ with mock.patch("sys.argv", ["flatten-validate"]):
69
+ assert main() == 1
70
+
71
+ @mock.patch("pre_commit_hooks.flatten_validate.subprocess.run")
72
+ def test_scadm_failure(self, mock_run):
73
+ """Hook fails when scadm flatten returns non-zero."""
74
+ mock_run.return_value = _mock_run(1)
75
+ with mock.patch("sys.argv", ["flatten-validate"]):
76
+ assert main() == 1
77
+
78
+ @mock.patch("pre_commit_hooks.flatten_validate.subprocess.run")
79
+ def test_missing_scadm_json(self, mock_run, tmp_path, monkeypatch):
80
+ """Hook warns and runs scadm when scadm.json is missing."""
81
+ monkeypatch.chdir(tmp_path)
82
+ mock_run.return_value = _mock_run(0)
83
+ with mock.patch("sys.argv", ["flatten-validate"]):
84
+ assert main() == 0
85
+
86
+ @mock.patch("pre_commit_hooks.flatten_validate.subprocess.run")
87
+ def test_flatten_dir_override(self, mock_run, tmp_path, monkeypatch):
88
+ """--flatten-dir overrides scadm.json discovery."""
89
+ monkeypatch.chdir(tmp_path)
90
+ mock_run.side_effect = [
91
+ _mock_run(0), # scadm flatten --all
92
+ _mock_run(0, stdout=""), # git diff
93
+ _mock_run(0, stdout=""), # git ls-files
94
+ ]
95
+ with mock.patch("sys.argv", ["flatten-validate", "--flatten-dir", "custom/out"]):
96
+ assert main() == 0
97
+ # Verify git commands used our custom dir
98
+ diff_call = mock_run.call_args_list[1]
99
+ assert "custom/out" in diff_call[0][0]
100
+
101
+ @mock.patch("pre_commit_hooks.flatten_validate.subprocess.run")
102
+ def test_git_diff_failure(self, mock_run):
103
+ """Hook exits when git diff fails."""
104
+ mock_run.side_effect = [
105
+ _mock_run(0), # scadm flatten --all
106
+ _mock_run(128, stderr="fatal: not a git repository"), # git diff
107
+ ]
108
+ with mock.patch("sys.argv", ["flatten-validate"]):
109
+ with pytest.raises(SystemExit) as exc_info:
110
+ main()
111
+ assert exc_info.value.code == 1
112
+
113
+ @mock.patch("pre_commit_hooks.flatten_validate.subprocess.run")
114
+ def test_git_ls_files_failure(self, mock_run):
115
+ """Hook exits when git ls-files fails."""
116
+ mock_run.side_effect = [
117
+ _mock_run(0), # scadm flatten --all
118
+ _mock_run(0, stdout=""), # git diff
119
+ _mock_run(128, stderr="fatal: not a git repository"), # git ls-files
120
+ ]
121
+ with mock.patch("sys.argv", ["flatten-validate"]):
122
+ with pytest.raises(SystemExit) as exc_info:
123
+ main()
124
+ assert exc_info.value.code == 1
@@ -0,0 +1,132 @@
1
+ """Tests for optimize_images hook."""
2
+
3
+ from unittest import mock
4
+
5
+ from PIL import Image
6
+
7
+ from pre_commit_hooks.optimize_images import main
8
+
9
+
10
+ def _create_jpeg(path, width, height, exif=False):
11
+ """Create a test JPEG file.
12
+
13
+ Args:
14
+ path: File path to write.
15
+ width: Image width in pixels.
16
+ height: Image height in pixels.
17
+ exif: If True, embed a fake EXIF marker.
18
+ """
19
+ img = Image.new("RGB", (width, height), color="red")
20
+ if exif:
21
+ # Minimal EXIF with a GPS IFD pointer (privacy test)
22
+ # EXIF header: Exif\x00\x00 + TIFF header (little-endian)
23
+ exif_bytes = b"Exif\x00\x00II\x2a\x00\x08\x00\x00\x00\x00\x00\x00\x00"
24
+ img.info["exif"] = exif_bytes
25
+ img.save(str(path), "JPEG", quality=95, exif=exif_bytes)
26
+ else:
27
+ img.save(str(path), "JPEG", quality=95)
28
+
29
+
30
+ class TestOptimizeImages:
31
+ """Tests for the optimize-images hook."""
32
+
33
+ def test_large_image_resized(self, tmp_path):
34
+ """Images wider than max-width are resized."""
35
+ img_path = tmp_path / "large.jpg"
36
+ _create_jpeg(img_path, 3000, 2000)
37
+
38
+ with mock.patch("sys.argv", ["optimize-images", "--max-width=1920", str(img_path)]):
39
+ result = main()
40
+
41
+ assert result == 1 # hook fails because file was modified
42
+ with Image.open(img_path) as img:
43
+ assert img.size[0] == 1920
44
+ assert img.size[1] == 1280 # proportional
45
+
46
+ def test_small_image_untouched(self, tmp_path):
47
+ """Small images without EXIF are not modified."""
48
+ img_path = tmp_path / "small.jpg"
49
+ _create_jpeg(img_path, 800, 600)
50
+ original_size = img_path.stat().st_size
51
+
52
+ with mock.patch("sys.argv", ["optimize-images", "--max-width=1920", str(img_path)]):
53
+ result = main()
54
+
55
+ assert result == 0 # hook passes
56
+ assert img_path.stat().st_size == original_size
57
+
58
+ def test_exact_width_untouched(self, tmp_path):
59
+ """Images at exactly max-width are not modified."""
60
+ img_path = tmp_path / "exact.jpg"
61
+ _create_jpeg(img_path, 1920, 1080)
62
+
63
+ with mock.patch("sys.argv", ["optimize-images", "--max-width=1920", str(img_path)]):
64
+ result = main()
65
+
66
+ assert result == 0
67
+
68
+ def test_exif_stripped(self, tmp_path):
69
+ """EXIF data is stripped from resized images."""
70
+ img_path = tmp_path / "gps.jpg"
71
+ _create_jpeg(img_path, 3000, 2000, exif=True)
72
+
73
+ with mock.patch("sys.argv", ["optimize-images", "--max-width=1920", str(img_path)]):
74
+ main()
75
+
76
+ with Image.open(img_path) as img:
77
+ assert img.info.get("exif") is None
78
+
79
+ def test_custom_quality(self, tmp_path):
80
+ """Custom quality setting is applied."""
81
+ img_path = tmp_path / "quality.jpg"
82
+ _create_jpeg(img_path, 3000, 2000)
83
+
84
+ with mock.patch("sys.argv", ["optimize-images", "--quality=50", "--max-width=1920", str(img_path)]):
85
+ result = main()
86
+
87
+ assert result == 1
88
+ with Image.open(img_path) as img:
89
+ assert img.size[0] == 1920
90
+
91
+ def test_multiple_files(self, tmp_path):
92
+ """Multiple files are processed; only oversized ones are modified."""
93
+ large = tmp_path / "large.jpg"
94
+ small = tmp_path / "small.jpg"
95
+ _create_jpeg(large, 4000, 3000)
96
+ _create_jpeg(small, 800, 600)
97
+ small_size = small.stat().st_size
98
+
99
+ with mock.patch("sys.argv", ["optimize-images", "--max-width=1920", str(large), str(small)]):
100
+ result = main()
101
+
102
+ assert result == 1 # large was modified
103
+ with Image.open(large) as img:
104
+ assert img.size[0] == 1920
105
+ assert small.stat().st_size == small_size
106
+
107
+ def test_no_files(self):
108
+ """Hook passes when no files are provided."""
109
+ with mock.patch("sys.argv", ["optimize-images"]):
110
+ assert main() == 0
111
+
112
+ def test_exif_stripped_small_image(self, tmp_path):
113
+ """EXIF data is stripped even when image is within max-width."""
114
+ img_path = tmp_path / "small_exif.jpg"
115
+ _create_jpeg(img_path, 800, 600, exif=True)
116
+
117
+ with mock.patch("sys.argv", ["optimize-images", "--max-width=1920", str(img_path)]):
118
+ result = main()
119
+
120
+ assert result == 1 # file was modified (EXIF stripped)
121
+ with Image.open(img_path) as img:
122
+ assert img.info.get("exif") is None
123
+
124
+ def test_error_causes_failure(self, tmp_path):
125
+ """Hook fails when processing a file raises an exception."""
126
+ bad_path = tmp_path / "not_a_jpeg.jpg"
127
+ bad_path.write_text("not an image")
128
+
129
+ with mock.patch("sys.argv", ["optimize-images", str(bad_path)]):
130
+ result = main()
131
+
132
+ assert result == 1