Skip to content

Commit c9e612f

Browse files
authored
Merge pull request #76 from python-project-templates/tkp/hf
Bugfix for CLI overriding, add skip option, add disable ccache option for CLI
2 parents 9acd528 + d34c424 commit c9e612f

File tree

4 files changed

+114
-37
lines changed

4 files changed

+114
-37
lines changed

README.md

Lines changed: 81 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -97,17 +97,89 @@ hatch-build \
9797
--libraries.0.include-dirs cpp,another-dir
9898
```
9999

100-
### Environment Variables
100+
This CLI is aware of your `pyproject.toml`-configured setup.
101+
To display help for this, run (note the passthrough `--`):
102+
103+
```bash
104+
hatch-build -- --help
105+
```
101106

102-
`hatch-cpp` will respect standard environment variables for compiler control.
107+
For example, for the `test_project_basic` in this project's `tests` folder:
108+
109+
```raw
110+
hatch-build --hooks-only -- --help
111+
[sdist]
112+
113+
[wheel]
114+
[2025-11-11T17:31:06-0500][p2a][WARNING]: Only dicts with str, int, float, bool, or enum values are supported - field `cmake_env_args` got value type typing.Dict[str, str]
115+
usage: hatch-build-extras-model [-h] [--verbose] [--name NAME] [--libraries.0.name LIBRARIES.0.NAME]
116+
[--libraries.0.sources.0 LIBRARIES.0.SOURCES.0] [--libraries.0.sources LIBRARIES.0.SOURCES]
117+
[--libraries.0.language LIBRARIES.0.LANGUAGE] [--libraries.0.binding LIBRARIES.0.BINDING]
118+
[--libraries.0.std LIBRARIES.0.STD] [--libraries.0.include-dirs.0 LIBRARIES.0.INCLUDE_DIRS.0]
119+
[--libraries.0.include-dirs LIBRARIES.0.INCLUDE_DIRS]
120+
[--libraries.0.library-dirs LIBRARIES.0.LIBRARY_DIRS]
121+
[--libraries.0.libraries LIBRARIES.0.LIBRARIES]
122+
[--libraries.0.extra-compile-args LIBRARIES.0.EXTRA_COMPILE_ARGS]
123+
[--libraries.0.extra-link-args LIBRARIES.0.EXTRA_LINK_ARGS]
124+
[--libraries.0.extra-objects LIBRARIES.0.EXTRA_OBJECTS]
125+
[--libraries.0.define-macros LIBRARIES.0.DEFINE_MACROS]
126+
[--libraries.0.undef-macros LIBRARIES.0.UNDEF_MACROS]
127+
[--libraries.0.export-symbols LIBRARIES.0.EXPORT_SYMBOLS]
128+
[--libraries.0.depends LIBRARIES.0.DEPENDS]
129+
[--libraries.0.py-limited-api LIBRARIES.0.PY_LIMITED_API] [--cmake.root CMAKE.ROOT]
130+
[--cmake.build CMAKE.BUILD] [--cmake.install CMAKE.INSTALL]
131+
[--cmake.cmake-arg-prefix CMAKE.CMAKE_ARG_PREFIX] [--cmake.cmake-args CMAKE.CMAKE_ARGS]
132+
[--cmake.include-flags CMAKE.INCLUDE_FLAGS] [--platform.cc PLATFORM.CC]
133+
[--platform.cxx PLATFORM.CXX] [--platform.ld PLATFORM.LD] [--platform.platform PLATFORM.PLATFORM]
134+
[--platform.toolchain PLATFORM.TOOLCHAIN] [--platform.disable-ccache] [--vcpkg.vcpkg VCPKG.VCPKG]
135+
[--vcpkg.vcpkg-root VCPKG.VCPKG_ROOT] [--vcpkg.vcpkg-repo VCPKG.VCPKG_REPO]
136+
[--vcpkg.vcpkg-triplet VCPKG.VCPKG_TRIPLET] [--build-type BUILD_TYPE] [--commands COMMANDS]
137+
138+
options:
139+
-h, --help show this help message and exit
140+
--verbose
141+
--name NAME
142+
--libraries.0.name LIBRARIES.0.NAME
143+
--libraries.0.sources.0 LIBRARIES.0.SOURCES.0
144+
--libraries.0.sources LIBRARIES.0.SOURCES
145+
--libraries.0.language LIBRARIES.0.LANGUAGE
146+
--libraries.0.binding LIBRARIES.0.BINDING
147+
--libraries.0.std LIBRARIES.0.STD
148+
--libraries.0.include-dirs.0 LIBRARIES.0.INCLUDE_DIRS.0
149+
--libraries.0.include-dirs LIBRARIES.0.INCLUDE_DIRS
150+
--libraries.0.library-dirs LIBRARIES.0.LIBRARY_DIRS
151+
--libraries.0.libraries LIBRARIES.0.LIBRARIES
152+
--libraries.0.extra-compile-args LIBRARIES.0.EXTRA_COMPILE_ARGS
153+
--libraries.0.extra-link-args LIBRARIES.0.EXTRA_LINK_ARGS
154+
--libraries.0.extra-objects LIBRARIES.0.EXTRA_OBJECTS
155+
--libraries.0.define-macros LIBRARIES.0.DEFINE_MACROS
156+
--libraries.0.undef-macros LIBRARIES.0.UNDEF_MACROS
157+
--libraries.0.export-symbols LIBRARIES.0.EXPORT_SYMBOLS
158+
--libraries.0.depends LIBRARIES.0.DEPENDS
159+
--libraries.0.py-limited-api LIBRARIES.0.PY_LIMITED_API
160+
--cmake.root CMAKE.ROOT
161+
--cmake.build CMAKE.BUILD
162+
--cmake.install CMAKE.INSTALL
163+
--cmake.cmake-arg-prefix CMAKE.CMAKE_ARG_PREFIX
164+
--cmake.cmake-args CMAKE.CMAKE_ARGS
165+
--cmake.include-flags CMAKE.INCLUDE_FLAGS
166+
--platform.cc PLATFORM.CC
167+
--platform.cxx PLATFORM.CXX
168+
--platform.ld PLATFORM.LD
169+
--platform.platform PLATFORM.PLATFORM
170+
--platform.toolchain PLATFORM.TOOLCHAIN
171+
--platform.disable-ccache
172+
--vcpkg.vcpkg VCPKG.VCPKG
173+
--vcpkg.vcpkg-root VCPKG.VCPKG_ROOT
174+
--vcpkg.vcpkg-repo VCPKG.VCPKG_REPO
175+
--vcpkg.vcpkg-triplet VCPKG.VCPKG_TRIPLET
176+
--build-type BUILD_TYPE
177+
--commands COMMANDS
178+
```
179+
180+
### Environment Variables
103181

104-
| Name | Default | Description |
105-
| :------------------------- | :------ | :-------------------- |
106-
| `CC` | | C Compiler override |
107-
| `CXX` | | C++ Compiler override |
108-
| `LD` | | Linker override |
109-
| `HATCH_CPP_PLATFORM` | | Platform to build |
110-
| `HATCH_CPP_DISABLE_CCACHE` | | Disable CCache usage |
182+
`hatch-cpp` will respect standard environment variables for compiler control, e.g. `CC`, `CXX`, `LD`, `CMAKE_GENERATOR`, `OSX_DEPLOYMENT_TARGET`, etc.
111183

112184
> [!NOTE]
113185
> This library was generated using [copier](https://copier.readthedocs.io/en/stable/) from the [Base Python Project Template repository](https://github.com/python-project-templates/base).

hatch_cpp/config.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
from __future__ import annotations
22

3-
from logging import getLogger
43
from os import system as system_call
54
from pathlib import Path
65
from typing import List, Optional
76

7+
from pkn import getSimpleLogger
88
from pydantic import BaseModel, Field, model_validator
99

1010
from .toolchains import BuildType, HatchCppCmakeConfiguration, HatchCppLibrary, HatchCppPlatform, HatchCppVcpkgConfiguration, Toolchain
@@ -15,13 +15,14 @@
1515
)
1616

1717

18-
_log = getLogger(__name__)
18+
log = getSimpleLogger("hatch_cpp")
1919

2020

2121
class HatchCppBuildConfig(BaseModel):
2222
"""Build config values for Hatch C++ Builder."""
2323

2424
verbose: Optional[bool] = Field(default=False)
25+
skip: Optional[bool] = Field(default=False)
2526
name: Optional[str] = Field(default=None)
2627
libraries: List[HatchCppLibrary] = Field(default_factory=list)
2728
cmake: Optional[HatchCppCmakeConfiguration] = Field(default=None)
@@ -76,7 +77,7 @@ def generate(self):
7677

7778
if "vanilla" in self._active_toolchains:
7879
if "vcpkg" in self._active_toolchains:
79-
_log.warning("vcpkg toolchain is active; ensure that your compiler is configured to use vcpkg includes and libs.")
80+
log.warning("vcpkg toolchain is active; ensure that your compiler is configured to use vcpkg includes and libs.")
8081

8182
for library in self.libraries:
8283
compile_flags = self.platform.get_compile_flags(library, self.build_type)

hatch_cpp/plugin.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
from __future__ import annotations
22

3-
from logging import getLogger
4-
from os import getenv
53
from pathlib import Path
64
from platform import machine as platform_machine
75
from sys import platform as sys_platform, version_info
@@ -10,7 +8,7 @@
108
from hatch_build import parse_extra_args_model
119
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
1210

13-
from .config import HatchCppBuildConfig, HatchCppBuildPlan
11+
from .config import HatchCppBuildConfig, HatchCppBuildPlan, log
1412
from .utils import import_string
1513

1614
__all__ = ("HatchCppBuildHook",)
@@ -20,7 +18,7 @@ class HatchCppBuildHook(BuildHookInterface[HatchCppBuildConfig]):
2018
"""The hatch-cpp build hook."""
2119

2220
PLUGIN_NAME = "hatch-cpp"
23-
_logger = getLogger(__name__)
21+
_logger = log
2422

2523
def initialize(self, version: str, build_data: dict[str, Any]) -> None:
2624
"""Initialize the plugin."""
@@ -35,12 +33,6 @@ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
3533
self._logger.info("ignoring target name %s", self.target_name)
3634
return
3735

38-
# Skip if SKIP_HATCH_CPP is set
39-
# TODO: Support CLI once https://github.com/pypa/hatch/pull/1743
40-
if getenv("SKIP_HATCH_CPP"):
41-
self._logger.info("Skipping the build hook since SKIP_HATCH_CPP was set")
42-
return
43-
4436
# Get build config class or use default
4537
build_config_class = import_string(self.config["build-config-class"]) if "build-config-class" in self.config else HatchCppBuildConfig
4638

@@ -60,10 +52,14 @@ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
6052
build_plan.generate()
6153

6254
# Log commands if in verbose mode
63-
if config.verbose:
55+
if build_plan.verbose:
6456
for command in build_plan.commands:
6557
self._logger.warning(command)
6658

59+
if build_plan.skip:
60+
self._logger.warning("Skipping build")
61+
return
62+
6763
# Execute build plan
6864
build_plan.execute()
6965

@@ -114,4 +110,4 @@ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
114110
build_data["force_include"][str(path)] = str(path)
115111

116112
for path in build_data["force_include"]:
117-
self._logger.warning(f"Force include: {path}")
113+
self._logger.info(f"Force include: {path}")

hatch_cpp/toolchains/common.py

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -96,40 +96,48 @@ class HatchCppPlatform(BaseModel):
9696
ld: str
9797
platform: Platform
9898
toolchain: CompilerToolchain
99+
disable_ccache: bool = False
99100

100101
@staticmethod
101102
def default() -> HatchCppPlatform:
102-
platform = environ.get("HATCH_CPP_PLATFORM", sys_platform)
103-
CC = environ.get("CC", PlatformDefaults[platform]["CC"])
104-
CXX = environ.get("CXX", PlatformDefaults[platform]["CXX"])
105-
LD = environ.get("LD", PlatformDefaults[platform]["LD"])
103+
CC = environ.get("CC", PlatformDefaults[sys_platform]["CC"])
104+
CXX = environ.get("CXX", PlatformDefaults[sys_platform]["CXX"])
105+
LD = environ.get("LD", PlatformDefaults[sys_platform]["LD"])
106106
if "gcc" in CC and "g++" in CXX:
107107
toolchain = "gcc"
108108
elif "clang" in CC and "clang++" in CXX:
109109
toolchain = "clang"
110110
elif "cl" in CC and "cl" in CXX:
111111
toolchain = "msvc"
112112
# Fallback to platform defaults
113-
elif platform == "linux":
113+
elif sys_platform == "linux":
114114
toolchain = "gcc"
115-
elif platform == "darwin":
115+
elif sys_platform == "darwin":
116116
toolchain = "clang"
117-
elif platform == "win32":
117+
elif sys_platform == "win32":
118118
toolchain = "msvc"
119119
else:
120120
toolchain = "gcc"
121121

122-
# Customizations
123-
if which("ccache") and not environ.get("HATCH_CPP_DISABLE_CCACHE"):
124-
CC = f"ccache {CC}"
125-
CXX = f"ccache {CXX}"
126-
122+
# TODO:
127123
# https://github.com/rui314/mold/issues/647
128124
# if which("ld.mold"):
129125
# LD = which("ld.mold")
130126
# elif which("ld.lld"):
131127
# LD = which("ld.lld")
132-
return HatchCppPlatform(cc=CC, cxx=CXX, ld=LD, platform=platform, toolchain=toolchain)
128+
return HatchCppPlatform(cc=CC, cxx=CXX, ld=LD, platform=sys_platform, toolchain=toolchain)
129+
130+
@model_validator(mode="wrap")
131+
@classmethod
132+
def validate_model(cls, data, handler):
133+
model = handler(data)
134+
if which("ccache") and not model.disable_ccache:
135+
if model.toolchain in ["gcc", "clang"]:
136+
if not model.cc.startswith("ccache "):
137+
model.cc = f"ccache {model.cc}"
138+
if not model.cxx.startswith("ccache "):
139+
model.cxx = f"ccache {model.cxx}"
140+
return model
133141

134142
@staticmethod
135143
def platform_for_toolchain(toolchain: CompilerToolchain) -> HatchCppPlatform:

0 commit comments

Comments
 (0)