Add a dedicated struct for source annotations (#3478)

This commit is contained in:
Charlie Marsh 2024-05-09 00:40:35 -04:00 committed by GitHub
parent 8bcb2365bf
commit f16cbfda7e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 177 additions and 149 deletions

View file

@ -1,9 +1,14 @@
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use url::Url;
use pep508_rs::VerbatimUrl;
use uv_fs::Simplified;
use uv_normalize::PackageName;
/// Source of a dependency, e.g., a `-r requirements.txt` file.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SourceAnnotation {
/// A `pyproject.toml` file.
PyProject {
@ -18,16 +23,6 @@ pub enum SourceAnnotation {
Requirement(PathBuf),
}
impl<'de> Deserialize<'de> for SourceAnnotation {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ok(SourceAnnotation::Requirement(PathBuf::from(s)))
}
}
impl std::fmt::Display for SourceAnnotation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
@ -50,3 +45,38 @@ impl std::fmt::Display for SourceAnnotation {
}
}
}
/// A collection of source annotations.
#[derive(Default, Debug, Clone)]
pub struct SourceAnnotations {
packages: BTreeMap<PackageName, BTreeSet<SourceAnnotation>>,
editables: BTreeMap<Url, BTreeSet<SourceAnnotation>>,
}
impl SourceAnnotations {
/// Add a source annotation to the collection for the given package.
pub fn add(&mut self, package: &PackageName, annotation: SourceAnnotation) {
self.packages
.entry(package.clone())
.or_default()
.insert(annotation);
}
/// Add an source annotation to the collection for the given editable.
pub fn add_editable(&mut self, url: &VerbatimUrl, annotation: SourceAnnotation) {
self.editables
.entry(url.to_url())
.or_default()
.insert(annotation);
}
/// Return the source annotations for a given package.
pub fn get(&self, package: &PackageName) -> Option<&BTreeSet<SourceAnnotation>> {
self.packages.get(package)
}
/// Return the source annotations for a given editable.
pub fn get_editable(&self, url: &VerbatimUrl) -> Option<&BTreeSet<SourceAnnotation>> {
self.editables.get(url.raw())
}
}

View file

@ -63,7 +63,7 @@ impl Requirement {
extras: requirement.extras,
marker: requirement.marker,
source,
path: requirement.path,
path: requirement.source,
})
}
}