Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Version command can show dynamic version #355

Merged
merged 4 commits into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ that were not yet released.

_Unreleased_

- The `version` command can show dynamic versions now. #355

- `rye add` now properly checks some incompatible argument combinations. #347

- There is now more toolchain validation. This better supports cases where
Expand Down
1 change: 1 addition & 0 deletions rye/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ zip = { version = "0.6.5", features = ["deflate"], default-features = false }
self-replace = "1.3.2"
configparser = "3.0.2"
monotrail-utils = { git = "https://github.com/konstin/poc-monotrail", version = "0.0.1" }
python-pkginfo = { version = "0.5.6", features = ["serde"] }

[target."cfg(windows)".dependencies]
winapi = { version = "0.3.9", default-features = false, features = [] }
16 changes: 12 additions & 4 deletions rye/src/cli/version.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::str::FromStr;

use crate::pyproject::PyProject;
use anyhow::{anyhow, Error};
use anyhow::{anyhow, bail, Error};
use clap::{Parser, ValueEnum};
use pep440_rs::Version;

Expand All @@ -28,10 +28,18 @@ pub fn execute(cmd: Args) -> Result<(), Error> {
Some(version) => {
let version =
Version::from_str(&version).map_err(|msg| anyhow!("invalid version: {}", msg))?;
pyproject_toml.set_version(&version);
pyproject_toml.save()?;
if pyproject_toml
.dynamic()
.unwrap()
.contains(&"version".to_string())
{
bail!("unsupported set dynamic version");
} else {
pyproject_toml.set_version(&version);
pyproject_toml.save()?;

echo!("version set to {}", version);
echo!("version set to {}", version);
}
}
None => {
let mut version = pyproject_toml.version()?;
Expand Down
82 changes: 66 additions & 16 deletions rye/src/pyproject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,48 @@ use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::process::{Command, Stdio};
use std::str::FromStr;
use std::sync::Arc;

use crate::bootstrap::ensure_self_venv;
use crate::config::Config;
use crate::consts::VENV_BIN;
use crate::platform::{get_python_version_request_from_pyenv_pin, list_known_toolchains};
use crate::sources::{get_download_url, matches_version, PythonVersion, PythonVersionRequest};
use crate::sync::VenvMarker;
use crate::utils::CommandOutput;
use crate::utils::{
escape_string, expand_env_vars, format_requirement, get_short_executable_name, is_executable,
reformat_toml_array_multiline,
};
use anyhow::{anyhow, bail, Context, Error};
use globset::GlobBuilder;
use once_cell::sync::Lazy;
use pep440_rs::{Operator, Version, VersionSpecifiers};
use pep508_rs::Requirement;
use python_pkginfo::Metadata;
use regex::Regex;
use serde::Serialize;
use toml_edit::{Array, Document, Formatted, Item, Table, TableLike, Value};
use url::Url;
static NORMALIZATION_SPLIT_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[-_.]+").unwrap());

use crate::config::Config;
use crate::consts::VENV_BIN;
use crate::platform::{get_python_version_request_from_pyenv_pin, list_known_toolchains};
use crate::sources::{get_download_url, matches_version, PythonVersion, PythonVersionRequest};
use crate::sync::VenvMarker;
use crate::utils::{
expand_env_vars, format_requirement, get_short_executable_name, is_executable,
reformat_toml_array_multiline,
};
const PROJECT_METADATA_SCRIPT: &str = r#"
import json
import sys

static NORMALIZATION_SPLIT_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[-_.]+").unwrap());
from build import BuildBackendException
from build.util import project_wheel_metadata

source_dir = sys.argv[1]
try:
metadata = project_wheel_metadata(source_dir).json
except BuildBackendException:
metadata = {}

print(json.dumps(metadata))
"#;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum DependencyKind<'a> {
Expand Down Expand Up @@ -710,18 +727,40 @@ impl PyProject {
.ok_or_else(|| anyhow!("project from '{}' has no name", self.root_path().display()))
}

/// Returns the dynamic field.
pub fn dynamic(&self) -> Option<Vec<String>> {
let mut dv = Vec::new();
if let Some(dynamic) = self
.doc
.get("project")
.and_then(|x| x.get("dynamic"))
.and_then(|x| x.as_array())
{
for d in dynamic {
dv.push(escape_string(d.to_string()));
}
}
Some(dv)
}

/// Returns the version.
pub fn version(&mut self) -> Result<Version, Error> {
let version = self
let mut version = self
.doc
.get("project")
.and_then(|x| x.get("version"))
.and_then(|x| x.as_str());
.map(|x| x.to_string());
if let Some(dynamic) = self.dynamic() {
if dynamic.contains(&"version".to_string()) {
if let Ok(metadata) = get_project_metadata(&self.root_path()) {
version = Some(metadata.version);
};
};
};

match version {
Some(version) => {
Version::from_str(version).map_err(|msg| anyhow!("invalid version: {}", msg))
}
Some(version) => Version::from_str(version.as_str())
.map_err(|msg| anyhow!("invalid version: {}", msg)),
None => {
let version = Version::from_str("0.1.0").unwrap();
self.set_version(&version);
Expand Down Expand Up @@ -1148,6 +1187,17 @@ fn is_rye_managed(doc: &Document) -> bool {
.unwrap_or(false)
}

fn get_project_metadata(path: &Path) -> Result<Metadata, Error> {
let self_venv = ensure_self_venv(CommandOutput::Normal)?;
let mut metadata = Command::new(self_venv.join(VENV_BIN).join("python"));
metadata.arg("-c").arg(PROJECT_METADATA_SCRIPT).arg(path);
let metadata = metadata.stdout(Stdio::piped()).output()?;
if !metadata.status.success() {
let log = String::from_utf8_lossy(&metadata.stderr);
bail!("failed to get project metadata {}", log);
}
serde_json::from_slice(&metadata.stdout).map_err(Into::into)
}
/// Represents expanded sources.
#[derive(Debug, Clone, Serialize)]
pub struct ExpandedSources {
Expand Down