diff --git a/src/cargo/util/toml/mod.rs b/src/cargo/util/toml/mod.rs index ab96cdd03b0..55e14974ebd 100644 --- a/src/cargo/util/toml/mod.rs +++ b/src/cargo/util/toml/mod.rs @@ -17,6 +17,7 @@ use cargo_util_schemas::manifest::{RustVersion, StringOrBool}; use itertools::Itertools; use lazycell::LazyCell; use pathdiff::diff_paths; +use semver::Version; use toml_edit::ImDocument; use url::Url; @@ -566,7 +567,16 @@ fn normalize_package_toml<'a>( .clone() .map(|value| field_inherit_with(value, "version", || inherit()?.version())) .transpose()? - .map(manifest::InheritableField::Value), + .map(manifest::InheritableField::Value) + .or_else(|| { + let suggestion = std::env::var("CARGO_SUGGESTED_PKG_VERSION") else { + return None; + }; + let version = Version::parse(&suggestion.unwrap()) else { + return None; + }; + Some(manifest::InheritableField::Value(version.unwrap())) + }), authors: original_package .authors .clone() diff --git a/src/doc/src/reference/manifest.md b/src/doc/src/reference/manifest.md index 5026c9f40a3..3203e4db09d 100644 --- a/src/doc/src/reference/manifest.md +++ b/src/doc/src/reference/manifest.md @@ -111,8 +111,11 @@ so versions are considered considered [compatible](semver.md) if their left-most See the [Resolver] chapter for more information on how Cargo uses versions to resolve dependencies. -This field is optional and defaults to `0.0.0`. The field is required for publishing packages. +This field is optional. It defaults to the value of the `CARGO_SUGGESTED_PKG_VERSION` +environment variable. If the variable is not set or the value is invalid, +it defaults to `0.0.0`. The field is required for publishing packages. +> **MSRV:** Before 1.86, this field defaulted to `0.0.0` > **MSRV:** Before 1.75, this field was required [SemVer]: https://semver.org diff --git a/tests/testsuite/build.rs b/tests/testsuite/build.rs index 5b5ad0dfc3c..690a6738587 100644 --- a/tests/testsuite/build.rs +++ b/tests/testsuite/build.rs @@ -2890,6 +2890,57 @@ fn staticlib_rlib_and_bin() { p.cargo("build -v").run(); } +#[cargo_test] +fn suggested_pkg_version() { + let p = project() + .file( + "Cargo.toml", + r#" + [package] + name = "ver" + "#, + ) + .file( + "src/main.rs", + r#" + static VERSION: &'static str = env!("CARGO_PKG_VERSION"); + + fn main() { + println!("{}", VERSION); + } + "#, + ) + .build(); + + p.cargo("build -v").run(); + p.process(&p.bin("ver")) + .with_stdout_data(str![[r#" +0.0.0 + +"#]]) + .run(); + + p.cargo("build -v") + .env("CARGO_SUGGESTED_PKG_VERSION", "X.Y.Z") + .run(); + p.process(&p.bin("ver")) + .with_stdout_data(str![[r#" +0.0.0 + +"#]]) + .run(); + + p.cargo("build -v") + .env("CARGO_SUGGESTED_PKG_VERSION", "1.2.3") + .run(); + p.process(&p.bin("ver")) + .with_stdout_data(str![[r#" +1.2.3 + +"#]]) + .run(); +} + #[cargo_test] fn opt_out_of_bin() { let p = project()