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

Update pep508_rs and pep440_rs #928

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 50 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions rye/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ license = { version = "3.1.1", features = ["offline"] }
minijinja = { version = "2.0.1", features = ["json"] }
once_cell = "1.17.1"
pathdiff = "0.2.1"
pep440_rs = "0.4.0"
pep508_rs = "0.3.0"
pep440_rs = "0.5.0"
pep508_rs = "0.4.2"
pep508_v030 = { version = "0.3.0", package = "pep508_rs" }
regex = "1.8.1"
same-file = "1.0.6"
serde = { version = "1.0.160", features = ["derive"] }
Expand Down
75 changes: 51 additions & 24 deletions rye/src/cli/add.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use std::env;
use std::path::{Path, PathBuf};
use std::path::{Component, PathBuf};
use std::process::{Command, Stdio};
use std::str::FromStr;

use anyhow::{anyhow, bail, Context, Error};
use clap::{Parser, ValueEnum};
use pep440_rs::{Operator, Version, VersionSpecifier, VersionSpecifiers};
use pep508_rs::{Requirement, VersionOrUrl};
use pep440_rs::{Operator, Version, VersionPattern, VersionSpecifier, VersionSpecifiers};
use pep508_rs::{ExtraName, PackageName, Requirement, VerbatimUrl, VersionOrUrl};
use serde::Deserialize;
use url::Url;

use crate::bootstrap::ensure_self_venv;
use crate::config::Config;
Expand Down Expand Up @@ -159,9 +158,11 @@ impl ReqExtras {
// and use ${PROJECT_ROOT} will cause error in hatchling, so force absolute path.
let is_hatchling =
PyProject::discover()?.build_backend() == Some(BuildSystem::Hatchling);
let absolute_url =
VerbatimUrl::from_absolute_path(env::current_dir()?.join(path).to_string_lossy())
.map_err(|_| anyhow!("unable to interpret '{}' as path", path.display()))?;
let file_url = if self.absolute || is_hatchling {
Url::from_file_path(env::current_dir()?.join(path))
.map_err(|_| anyhow!("unable to interpret '{}' as path", path.display()))?
absolute_url
} else {
let base = env::current_dir()?;
let rv = pathdiff::diff_paths(base.join(path), &base).ok_or_else(|| {
Expand All @@ -171,26 +172,50 @@ impl ReqExtras {
path.display()
)
})?;
let mut url = Url::parse("file://")?;
url.set_path(&Path::new("/${PROJECT_ROOT}").join(rv).to_string_lossy());
url
let relative_url = relative_path_to_verbatim_url(rv)?;
absolute_url.with_given(relative_url)
};
req.version_or_url = match req.version_or_url {
Some(_) => bail!("requirement already has a version marker"),
None => Some(VersionOrUrl::Url(file_url)),
};
}
for feature in self.features.iter().flat_map(|x| x.split(',')) {
let feature = feature.trim();
let extras = req.extras.get_or_insert_with(Vec::new);
if !extras.iter().any(|x| x == feature) {
extras.push(feature.into());
let feature = ExtraName::from_str(feature.trim())?;
if !req.extras.iter().any(|x| *x == feature) {
req.extras.push(feature);
}
}
Ok(())
}
}

/// Build a project root relative URL in a string (avoiding restrictions in Url and Path)
fn relative_path_to_verbatim_url(rv: PathBuf) -> Result<String, Error> {
let mut relative_url = String::from("file:///${PROJECT_ROOT}");
for comp in rv.components() {
relative_url.push('/');
match comp {
Component::ParentDir => relative_url.push_str(".."),
Component::Normal(component) => {
if let Some(component_str) = component.to_str() {
relative_url.push_str(component_str)
} else {
bail!("unable to encode url from path {}", rv.display());
}
}
Component::RootDir | Component::CurDir | Component::Prefix(_) => {
bail!(
"unexpected component when encoding url from path {}",
rv.display()
);
}
}
}

Ok(relative_url)
}

/// Adds a Python package to this project.
#[derive(Parser, Debug)]
pub struct Args {
Expand Down Expand Up @@ -399,20 +424,19 @@ fn resolve_requirements_with_unearth(
// use ~= but need to use ==.
match *default_operator {
_ if version.is_local() => Operator::Equal,
Operator::TildeEqual if version.release.len() < 2 => {
Operator::TildeEqual if version.release().len() < 2 => {
Operator::GreaterThanEqual
}
ref other => other.clone(),
other => other,
},
Version::from_str(m.version.as_ref().unwrap())
VersionPattern::from_str(m.version.as_ref().unwrap())
.map_err(|msg| anyhow!("invalid version: {}", msg))?,
false,
)
.map_err(|msg| anyhow!("invalid version specifier: {}", msg))?,
)),
));
}
requirement.name = m.name;
requirement.name = PackageName::new(m.name)?;
Ok(())
}

Expand Down Expand Up @@ -494,22 +518,25 @@ fn resolve_requirements_with_uv(
for spec in specs.iter() {
let op = match *default_operator {
_ if spec.version().is_local() => Operator::Equal,
Operator::TildeEqual if spec.version().release.len() < 2 => {
Operator::TildeEqual if spec.version().release().len() < 2 => {
Operator::GreaterThanEqual
}
ref other => other.clone(),
other => other,
};
new_specs.push(
VersionSpecifier::new(op, spec.version().clone(), false)
.map_err(|msg| anyhow!("invalid version specifier: {}", msg))?,
VersionSpecifier::new(
op,
VersionPattern::verbatim(spec.version().clone()),
)
.map_err(|msg| anyhow!("invalid version specifier: {}", msg))?,
);
}
new_specs
}));
}
}
if let Some(old_extras) = &req.extras {
new_req.extras = Some(old_extras.clone());
if !req.extras.is_empty() {
new_req.extras.clone_from(&req.extras);
}
*req = new_req;
}
Expand Down
6 changes: 3 additions & 3 deletions rye/src/cli/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ use crate::platform::{
use crate::pyproject::BuildSystem;
use crate::sources::py::PythonVersionRequest;
use crate::utils::{
copy_dir, escape_string, format_requirement, get_venv_python_bin, is_inside_git_work_tree,
CommandOutput, CopyDirOptions, IoPathContext,
copy_dir, escape_string, format_requirement, format_requirement_v030, get_venv_python_bin,
is_inside_git_work_tree, CommandOutput, CopyDirOptions, IoPathContext,
};

/// Initialize a new or existing Python project with Rye.
Expand Down Expand Up @@ -701,7 +701,7 @@ fn import_requirements_file(
data.requirements.iter().for_each(|x| {
requirements
.entry(x.requirement.name.to_string())
.or_insert(format_requirement(&x.requirement).to_string());
.or_insert(format_requirement_v030(&x.requirement).to_string());
});
Ok(())
}
4 changes: 2 additions & 2 deletions rye/src/cli/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use same_file::is_same_file;
use crate::config::Config;
use crate::consts::VENV_BIN;
use crate::lock::KeyringProvider;
use crate::pyproject::{locate_projects, normalize_package_name, DependencyKind, PyProject};
use crate::pyproject::{locate_projects, DependencyKind, PyProject};
use crate::sync::autosync;
use crate::utils::{CommandOutput, QuietExit};

Expand Down Expand Up @@ -145,7 +145,7 @@ fn has_pytest_dependency(projects: &[PyProject]) -> Result<bool, Error> {
.chain(project.iter_dependencies(DependencyKind::Normal))
{
if let Ok(req) = dep.expand(|name| std::env::var(name).ok()) {
if normalize_package_name(&req.name) == "pytest" {
if req.name.as_ref() == "pytest" {
return Ok(true);
}
}
Expand Down
25 changes: 13 additions & 12 deletions rye/src/cli/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,35 +42,36 @@ pub fn execute(cmd: Args) -> Result<(), Error> {
}
}
None => {
let mut version = pyproject_toml.version()?;
let version = pyproject_toml.version()?;
match cmd.bump {
Some(bump) => bump_version(&mut version, bump, &mut pyproject_toml)?,
Some(bump) => bump_version(version, bump, &mut pyproject_toml)?,
None => echo!("{}", version),
}
}
}
Ok(())
}

fn bump_version(version: &mut Version, bump: Bump, pyproject: &mut PyProject) -> Result<(), Error> {
fn bump_version(mut version: Version, bump: Bump, pyproject: &mut PyProject) -> Result<(), Error> {
if version.is_post() {
version.post = None;
version = version.with_post(None);
}
if version.is_dev() {
version.dev = None;
version = version.with_dev(None);
warn!("dev version will be bumped to release version");
} else {
let mut release = version.release().to_vec();
let index = bump as usize;
if version.release.get(index).is_none() {
version.release.resize(index + 1, 0);
}
version.release[index] += 1;
for i in index + 1..version.release.len() {
version.release[i] = 0;
if release.get(index).is_none() {
release.resize(index + 1, 0);
}
release[index] += 1;
release[index + 1..].fill(0);

version = version.with_release(release);
}

pyproject.set_version(version);
pyproject.set_version(&version);
pyproject.save().unwrap();

echo!("version bumped to {}", version);
Expand Down
Loading