Parse `dist-workspace.toml` for version (#17868)

Extends https://github.com/astral-sh/ruff/pull/17866, using
`dist-workspace.toml` as a source of truth for versions to enable
version retrieval in distributions that are not Git repositories (i.e.,
Python source distributions and source tarballs consumed by Linux
distros).

I retain the Git tag lookup from
https://github.com/astral-sh/ruff/pull/17866 as a fallback — it seems
harmless, but we could drop it to simplify things here.

I confirmed this works from the repository as well as Python source and
binary distributions:

```
❯ uv run --refresh-package ty --reinstall-package ty -q --  ty version
ty 0.0.1-alpha.1+5 (2eadc9e61 2025-05-05)
❯ uv build
...
❯ uvx --from ty@dist/ty-0.0.0a1.tar.gz --no-cache -q -- ty version
ty 0.0.1-alpha.1
❯ uvx --from ty@dist/ty-0.0.0a1-py3-none-macosx_11_0_arm64.whl -q -- ty version
ty 0.0.1-alpha.1
```

Requires https://github.com/astral-sh/ty/pull/36

cc @Gankra and @MichaReiser for review.
This commit is contained in:
Zanie Blue 2025-05-06 07:18:17 -05:00 committed by GitHub
parent f7237e3b69
commit d07eefc408
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 40 additions and 9 deletions

View File

@ -12,12 +12,39 @@ fn main() {
.join("..")
.join("..");
version_info(&workspace_root);
commit_info(&workspace_root);
let target = std::env::var("TARGET").unwrap();
println!("cargo::rustc-env=RUST_HOST_TARGET={target}");
}
/// Retrieve the version from the `dist-workspace.toml` file and set `TY_VERSION`.
fn version_info(workspace_root: &Path) {
let dist_file = workspace_root.join("dist-workspace.toml");
if !dist_file.exists() {
return;
}
println!("cargo:rerun-if-changed={}", dist_file.display());
let dist_file = fs::read_to_string(dist_file);
if let Ok(dist_file) = dist_file {
let lines = dist_file.lines();
for line in lines {
if line.starts_with("version =") {
let (_key, version) = line.split_once('=').unwrap();
println!(
"cargo::rustc-env=TY_VERSION={}",
version.trim().trim_matches('"')
);
break;
}
}
}
}
/// Retrieve commit information from the Git repository.
fn commit_info(workspace_root: &Path) {
// If not in a git repository, do not attempt to retrieve commit information
let git_dir = workspace_root.join(".git");

View File

@ -54,7 +54,10 @@ pub(crate) fn version() -> VersionInfo {
last_tag: option_env_str!("TY_LAST_TAG"),
});
let version = commit_info
// The version is pulled from `dist-workspace.toml` and set by `build.rs`
let version = option_env_str!("TY_VERSION").unwrap_or_else(|| {
// If missing, using the last tag
commit_info
.as_ref()
.and_then(|info| {
info.last_tag.as_ref().map(|tag| {
@ -63,7 +66,8 @@ pub(crate) fn version() -> VersionInfo {
.unwrap_or(tag.clone())
})
})
.unwrap_or("unknown".to_string());
.unwrap_or("unknown".to_string())
});
VersionInfo {
version,