Skip to content

Commit b63836f

Browse files
authored
Update algo selection pre-commit hook from within Python (#589)
1 parent b0212c9 commit b63836f

File tree

3 files changed

+44
-20
lines changed

3 files changed

+44
-20
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,9 @@ repos:
2222
hooks:
2323
- id: update-algo-selection-code
2424
name: update algo selection code
25-
entry: bash .tools/create_and_format_algo_selection_code.sh
25+
entry: python .tools/update_algo_selection_hook.py
2626
language: python
27-
files: (src/optimagic/optimizers/.|src/optimagic/algorithms.py|.tools/.)
28-
always_run: false
27+
files: ^(src/optimagic/optimizers/|src/optimagic/algorithms\.py|\.tools/)
2928
require_serial: true
3029
additional_dependencies:
3130
- hatchling

.tools/create_and_format_algo_selection_code.sh

Lines changed: 0 additions & 17 deletions
This file was deleted.

.tools/update_algo_selection_hook.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env python
2+
import subprocess
3+
import sys
4+
from pathlib import Path
5+
from typing import Any
6+
7+
ROOT = Path(__file__).resolve().parents[1]
8+
9+
# sys.executable guarantees we stay inside the pre‑commit venv
10+
PYTHON = [sys.executable]
11+
# "-m" lets us call std‑lib modules (e.g. pip) the same way
12+
PYTHON_MINUS_M = [*PYTHON, "-m"]
13+
14+
15+
def run(cmd: list[str], **kwargs: Any) -> None:
16+
subprocess.check_call(cmd, cwd=ROOT, **kwargs)
17+
18+
19+
def ensure_optimagic_is_locally_installed() -> None:
20+
try:
21+
run(PYTHON_MINUS_M + ["pip", "show", "optimagic"], stdout=subprocess.DEVNULL)
22+
except subprocess.CalledProcessError:
23+
run(PYTHON_MINUS_M + ["pip", "install", "-e", "."])
24+
25+
26+
def main() -> int:
27+
ensure_optimagic_is_locally_installed()
28+
run(PYTHON + [".tools/create_algo_selection_code.py"])
29+
30+
ruff_args = [
31+
"--silent",
32+
"--config",
33+
"pyproject.toml",
34+
"src/optimagic/algorithms.py",
35+
]
36+
run(["ruff", "format", *ruff_args])
37+
run(["ruff", "check", "--fix", *ruff_args])
38+
return 0 # explicit success code
39+
40+
41+
if __name__ == "__main__":
42+
sys.exit(main())

0 commit comments

Comments
 (0)