Skip to content

Commit af272df

Browse files
authored
Merge pull request #260 from davidhewitt/deprecate-native
clarify semantics of `rustc_flags`, deprecate `native`
2 parents 3f97179 + 83edfce commit af272df

File tree

3 files changed

+74
-70
lines changed

3 files changed

+74
-70
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
- Errors while calling `cargo metadata` are now reported back to the user [#254](https://github.com/PyO3/setuptools-rust/pull/254)
1515
- `quiet` option will now suppress output of `cargo metadata`. [#256](https://github.com/PyO3/setuptools-rust/pull/256)
1616
- `setuptools-rust` will now match `cargo` behavior of not setting `--target` when the selected target is the rust host. [#258](https://github.com/PyO3/setuptools-rust/pull/258)
17+
- Deprecate `native` option of `RustExtension`. [#258](https://github.com/PyO3/setuptools-rust/pull/258)
1718

1819
### Fixed
1920
- If the sysconfig for `BLDSHARED` has no flags, `setuptools-rust` won't crash anymore. [#241](https://github.com/PyO3/setuptools-rust/pull/241)

setuptools_rust/build.py

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -148,21 +148,21 @@ def build_extension(
148148
ext=ext, target_triple=target_triple, release=not debug, quiet=quiet
149149
)
150150

151+
rustflags = []
152+
153+
if linker is not None:
154+
rustflags.extend(["-C", "linker=" + linker])
155+
151156
if ext._uses_exec_binding():
152157
command = [self.cargo, "build", "--manifest-path", ext.path, *cargo_args]
153158

154159
else:
155160
rustc_args = [
156161
"--crate-type",
157162
"cdylib",
163+
*ext.rustc_flags,
158164
]
159165

160-
if ext.rustc_flags is not None:
161-
rustc_args.extend(ext.rustc_flags)
162-
163-
if linker is not None:
164-
rustc_args.extend(["-C", "linker=" + linker])
165-
166166
# OSX requires special linker arguments
167167
if sys.platform == "darwin":
168168
ext_basename = os.path.basename(self.get_dylib_ext_path(ext, ext.name))
@@ -173,24 +173,12 @@ def build_extension(
173173
]
174174
)
175175

176-
if ext.native:
177-
rustc_args.extend(["-C", "target-cpu=native"])
178-
179176
# Tell musl targets not to statically link libc. See
180177
# https://github.com/rust-lang/rust/issues/59302 for details.
181178
if rustc_cfgs.get("target_env") == "musl":
182179
# This must go in the env otherwise rustc will refuse to build
183180
# the cdylib, see https://github.com/rust-lang/cargo/issues/10143
184-
MUSL_FLAGS = "-C target-feature=-crt-static"
185-
rustflags = env.get("RUSTFLAGS")
186-
if rustflags is not None:
187-
env["RUSTFLAGS"] = f"{rustflags} {MUSL_FLAGS}"
188-
else:
189-
env["RUSTFLAGS"] = MUSL_FLAGS
190-
191-
# Include this in the command-line anyway, so that when verbose
192-
# logging enabled the user will see that this flag is in use.
193-
rustc_args.extend(MUSL_FLAGS.split())
181+
rustflags.append("-Ctarget-feature=-crt-static")
194182

195183
command = [
196184
self.cargo,
@@ -203,6 +191,17 @@ def build_extension(
203191
*rustc_args,
204192
]
205193

194+
if rustflags:
195+
existing_rustflags = env.get("RUSTFLAGS")
196+
if existing_rustflags is not None:
197+
rustflags.append(existing_rustflags)
198+
new_rustflags = " ".join(rustflags)
199+
env["RUSTFLAGS"] = new_rustflags
200+
201+
# print RUSTFLAGS being added before the command
202+
if not quiet:
203+
print(f"[RUSTFLAGS={new_rustflags}]", end=" ", file=sys.stderr)
204+
206205
if not quiet:
207206
print(" ".join(command), file=sys.stderr)
208207

setuptools_rust/extension.py

Lines changed: 55 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import warnings
66
from distutils.errors import DistutilsSetupError
77
from enum import IntEnum, auto
8-
from typing import Any, Dict, List, NewType, Optional, Union
8+
from typing import Any, Dict, List, NewType, Optional, Sequence, Union
99

1010
from semantic_version import SimpleSpec
1111
from typing_extensions import Literal
@@ -77,8 +77,10 @@ class RustExtension:
7777
`the Cargo Book <https://doc.rust-lang.org/cargo/commands/cargo-build.html#manifest-options>`_.
7878
For example, ``cargo_manifest_args=["--locked"]`` will require
7979
``Cargo.lock`` files are up to date.
80-
features: A list of Cargo features to also build.
81-
rustc_flags: A list of additional flags passed to rustc.
80+
features: Cargo `--features` to add to the build.
81+
rustc_flags: A list of additional flags passed to `cargo rustc`. These
82+
only affect the final artifact, usually you should set the
83+
`RUSTFLAGS` environment variable.
8284
rust_version: Minimum Rust compiler version required for this
8385
extension.
8486
quiet: Suppress Cargo's output.
@@ -88,9 +90,10 @@ class RustExtension:
8890
and ``wheel`` builds will be release.
8991
binding: Informs ``setuptools_rust`` which Python binding is in use.
9092
strip: Strip symbols from final file. Does nothing for debug build.
93+
native: Build extension or executable with ``-Ctarget-cpu=native``
94+
(deprecated, set environment variable RUSTFLAGS=-Ctarget-cpu=native).
9195
script: Generate console script for executable if ``Binding.Exec`` is
92-
used.
93-
native: Build extension or executable with ``--target-cpu=native``.
96+
used (deprecated, just use ``RustBin`` instead).
9497
optional: If it is true, a build failure in the extension will not
9598
abort the build process, and instead simply not install the failing
9699
extension.
@@ -117,10 +120,10 @@ def __init__(
117120
self,
118121
target: Union[str, Dict[str, str]],
119122
path: str = "Cargo.toml",
120-
args: Optional[List[str]] = None,
121-
cargo_manifest_args: Optional[List[str]] = None,
122-
features: Optional[List[str]] = None,
123-
rustc_flags: Optional[List[str]] = None,
123+
args: Optional[Sequence[str]] = (),
124+
cargo_manifest_args: Optional[Sequence[str]] = (),
125+
features: Optional[Sequence[str]] = (),
126+
rustc_flags: Optional[Sequence[str]] = (),
124127
rust_version: Optional[str] = None,
125128
quiet: bool = False,
126129
debug: Optional[bool] = None,
@@ -139,33 +142,34 @@ def __init__(
139142

140143
self.name = name
141144
self.target = target
142-
self.args = args
143-
self.cargo_manifest_args = cargo_manifest_args
144-
self.rustc_flags = rustc_flags
145-
self.binding = binding
145+
self.path = os.path.relpath(path) # relative path to Cargo manifest file
146+
self.args = tuple(args or ())
147+
self.cargo_manifest_args = tuple(cargo_manifest_args or ())
148+
self.features = tuple(features or ())
149+
self.rustc_flags = tuple(rustc_flags or ())
146150
self.rust_version = rust_version
147151
self.quiet = quiet
148152
self.debug = debug
153+
self.binding = binding
149154
self.strip = strip
150155
self.script = script
151-
self.native = native
152156
self.optional = optional
153157
self.py_limited_api = py_limited_api
154158

155-
if features is None:
156-
features = []
157-
158-
self.features = [s.strip() for s in features]
159-
160-
# get relative path to Cargo manifest file
161-
path = os.path.relpath(path)
162-
self.path = path
163-
164159
self._cargo_metadata: Optional[_CargoMetadata] = None
165160

161+
if native:
162+
warnings.warn(
163+
"`native` is deprecated, set RUSTFLAGS=-Ctarget-cpu=native instead.",
164+
DeprecationWarning,
165+
)
166+
# match old behaviour of only setting flag for top-level crate;
167+
# setting for `rustflags` is strictly better
168+
self.rustc_flags = (*self.rustc_flags, "-Ctarget-cpu=native")
169+
166170
if binding == Binding.Exec and script:
167171
warnings.warn(
168-
"'Binding.Exec' with 'script=True' is deprecated, use 'RustBin' instead.",
172+
"`Binding.Exec` with `script=True` is deprecated, use `RustBin` instead.",
169173
DeprecationWarning,
170174
)
171175

@@ -189,21 +193,22 @@ def get_rust_version(self) -> Optional[SimpleSpec]: # type: ignore[no-any-unimp
189193
)
190194

191195
def get_cargo_profile(self) -> Optional[str]:
192-
args = self.args or []
193196
try:
194-
index = args.index("--profile")
195-
return args[index + 1]
197+
index = self.args.index("--profile")
198+
return self.args[index + 1]
196199
except ValueError:
197200
pass
198201
except IndexError:
199-
raise DistutilsSetupError("Can not parse cargo profile from %s", args)
202+
raise DistutilsSetupError("Can not parse cargo profile from %s", self.args)
200203

201204
# Handle `--profile=<profile>`
202-
profile_args = [p for p in args if p.startswith("--profile=")]
205+
profile_args = [p for p in self.args if p.startswith("--profile=")]
203206
if profile_args:
204207
profile = profile_args[0].split("=", 1)[1]
205208
if not profile:
206-
raise DistutilsSetupError("Can not parse cargo profile from %s", args)
209+
raise DistutilsSetupError(
210+
"Can not parse cargo profile from %s", self.args
211+
)
207212
return profile
208213
else:
209214
return None
@@ -280,46 +285,45 @@ class RustBin(RustExtension):
280285
`the Cargo Book <https://doc.rust-lang.org/cargo/commands/cargo-build.html#manifest-options>`_.
281286
For example, ``cargo_manifest_args=["--locked"]`` will require
282287
``Cargo.lock`` files are up to date.
283-
features: A list of Cargo features to also build.
284-
rustc_flags: A list of additional flags passed to rustc.
285-
rust_version: Minimum Rust compiler version required for this
286-
extension.
288+
features: Cargo `--features` to add to the build.
289+
rust_version: Minimum Rust compiler version required for this bin.
287290
quiet: Suppress Cargo's output.
288291
debug: Controls whether ``--debug`` or ``--release`` is passed to
289292
Cargo. If set to `None` (the default) then build type is
290293
automatic: ``inplace`` build will be a debug build, ``install``
291294
and ``wheel`` builds will be release.
292295
strip: Strip symbols from final file. Does nothing for debug build.
293-
native: Build extension or executable with ``--target-cpu=native``.
296+
optional: If it is true, a build failure in the bin will not
297+
abort the build process, and instead simply not install the failing
298+
bin.
294299
"""
295300

296301
def __init__(
297302
self,
298-
target: str,
303+
target: Union[str, Dict[str, str]],
299304
path: str = "Cargo.toml",
300-
args: Optional[List[str]] = None,
301-
cargo_manifest_args: Optional[List[str]] = None,
302-
features: Optional[List[str]] = None,
303-
rustc_flags: Optional[List[str]] = None,
305+
args: Optional[Sequence[str]] = (),
306+
cargo_manifest_args: Optional[Sequence[str]] = (),
307+
features: Optional[Sequence[str]] = (),
304308
rust_version: Optional[str] = None,
305309
quiet: bool = False,
306310
debug: Optional[bool] = None,
307311
strip: Strip = Strip.No,
308-
native: bool = False,
312+
optional: bool = False,
309313
):
310314
super().__init__(
311-
target,
312-
path,
313-
args,
314-
cargo_manifest_args,
315-
features,
316-
rustc_flags,
317-
rust_version,
318-
quiet,
319-
debug,
315+
target=target,
316+
path=path,
317+
args=args,
318+
cargo_manifest_args=cargo_manifest_args,
319+
features=features,
320+
rust_version=rust_version,
321+
quiet=quiet,
322+
debug=debug,
320323
binding=Binding.Exec,
324+
optional=optional,
321325
strip=strip,
322-
native=native,
326+
py_limited_api=False,
323327
)
324328

325329
def entry_points(self) -> List[str]:

0 commit comments

Comments
 (0)