Skip to content
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
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/uv-cache-info/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,5 @@ walkdir = { workspace = true }

[dev-dependencies]
anyhow = { workspace = true }
insta = { workspace = true }
tempfile = { workspace = true }
259 changes: 254 additions & 5 deletions crates/uv-cache-info/src/cache_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ use std::borrow::Cow;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::Deserialize;
use serde::de::{
IgnoredAny, MapAccess, SeqAccess, Visitor,
value::{MapAccessDeserializer, SeqAccessDeserializer},
};
use serde::{Deserialize, Deserializer};
use tracing::{debug, info_span, warn};

use uv_fs::{Simplified, created_time};
Expand Down Expand Up @@ -337,9 +341,12 @@ struct ToolUv {
cache_keys: Option<Vec<CacheKey>>,
}

#[derive(Debug, Clone, serde::Deserialize)]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(untagged, rename_all = "kebab-case", deny_unknown_fields)]
#[cfg_attr(
feature = "schemars",
schemars(untagged, rename_all = "kebab-case", deny_unknown_fields)
)]
pub enum CacheKey {
/// Ex) `"Cargo.lock"` or `"**/*.toml"`
Path(Cow<'static, str>),
Expand All @@ -353,14 +360,136 @@ pub enum CacheKey {
Environment { env: String },
}

#[derive(Debug, Clone, serde::Deserialize)]
impl<'de> Deserialize<'de> for CacheKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
File,
Dir,
Git,
Env,
}

struct CacheKeyVisitor;

impl<'de> Visitor<'de> for CacheKeyVisitor {
type Value = CacheKey;

fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a path or a cache key table")
}

fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(CacheKey::Path(Cow::Owned(value.to_owned())))
}

fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(CacheKey::Path(Cow::Owned(value)))
}

fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let value = match map.next_key()? {
Some(Field::File) => CacheKey::File {
file: map.next_value()?,
},
Some(Field::Dir) => CacheKey::Directory {
dir: map.next_value()?,
},
Some(Field::Git) => CacheKey::Git {
git: map.next_value()?,
},
Some(Field::Env) => CacheKey::Environment {
env: map.next_value()?,
},
None => return Err(serde::de::Error::custom("empty cache key table")),
};
if map.next_key::<IgnoredAny>()?.is_some() {
return Err(serde::de::Error::custom("extra cache key field"));
}
Ok(value)
}
}

deserializer.deserialize_any(CacheKeyVisitor).map_err(|_| {
serde::de::Error::custom("data did not match any variant of untagged enum CacheKey")
})
}
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(untagged, rename_all = "kebab-case", deny_unknown_fields)]
#[cfg_attr(
feature = "schemars",
schemars(untagged, rename_all = "kebab-case", deny_unknown_fields)
)]
pub enum GitPattern {
Bool(bool),
Set(GitSet),
}

impl<'de> Deserialize<'de> for GitPattern {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct GitPatternVisitor;

impl<'de> Visitor<'de> for GitPatternVisitor {
type Value = GitPattern;

fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a boolean or a Git cache key table")
}

fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(GitPattern::Bool(value))
}

fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
GitSet::deserialize(MapAccessDeserializer::new(map)).map(GitPattern::Set)
}

fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let git = GitSet::deserialize(SeqAccessDeserializer::new(&mut sequence))?;
if sequence.next_element::<IgnoredAny>()?.is_some() {
return Err(serde::de::Error::custom("extra Git cache field"));
}
Ok(GitPattern::Set(git))
}
}

deserializer
.deserialize_any(GitPatternVisitor)
Comment on lines +483 to +484

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve sequence-form Git patterns during direct dispatch

The former untagged Set(GitSet) decoder accepts cache-keys = [{ git = [true, false] }] through Serde’s sequence representation of structs; shipped uv 0.13.1 also accepts this input. Although undocumented, this form now fails because the visitor has no visit_seq. For a local dependency, CacheInfo::from_directory silently replaces failed configuration with default keys, so subsequent Git-only changes stop invalidating cached wheels. Add visit_seq forwarding to GitSet::deserialize through SeqAccessDeserializer, with a focused compatibility snapshot, to keep this optimization behavior-preserving.

.map_err(|_| {
serde::de::Error::custom(
"data did not match any variant of untagged enum GitPattern",
)
})
}
}

#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
Expand All @@ -377,6 +506,126 @@ enum DirectoryTimestamp {
Inode(u64),
}

#[cfg(test)]
mod tests {
use super::{CacheKey, GitPattern, PyProjectToml};

#[test]
fn cache_key_forms() -> Result<(), toml::de::Error> {
let project: PyProjectToml = toml::from_str(
r#"
[tool.uv]
cache-keys = [
"Cargo.lock",
{ file = "**/*.toml" },
{ dir = "src" },
{ git = true },
{ git = { commit = true, tags = false } },
{ git = {} },
{ env = "UV_CACHE_INFO" },
]
"#,
)?;
insta::assert_debug_snapshot!(project, @r#"
PyProjectToml {
tool: Some(
Tool {
uv: Some(
ToolUv {
cache_keys: Some(
[
Path(
"Cargo.lock",
),
File {
file: "**/*.toml",
},
Directory {
dir: "src",
},
Git {
git: Bool(
true,
),
},
Git {
git: Set(
GitSet {
commit: Some(
true,
),
tags: Some(
false,
),
},
),
},
Git {
git: Set(
GitSet {
commit: None,
tags: None,
},
),
},
Environment {
env: "UV_CACHE_INFO",
},
],
),
},
),
},
),
}
"#);
Ok(())
}

#[test]
fn cache_key_git_sequence() -> Result<(), toml::de::Error> {
let key: CacheKey = toml::from_str("git = [true, false]")?;
insta::assert_debug_snapshot!(key, @r#"
Git {
git: Set(
GitSet {
commit: Some(
true,
),
tags: Some(
false,
),
},
),
}
"#);
Ok(())
}

#[test]
fn cache_key_git_sequence_extra_field() {
insta::assert_snapshot!(toml::from_str::<CacheKey>("git = [true, false, true]").unwrap_err(), @"data did not match any variant of untagged enum CacheKey");
}

#[test]
fn cache_key_extra_field() {
insta::assert_snapshot!(toml::from_str::<CacheKey>(r#"
file = "Cargo.lock"
env = "UV_CACHE_INFO"
"#).unwrap_err(), @"data did not match any variant of untagged enum CacheKey");
}

#[test]
fn cache_key_invalid_git() {
insta::assert_snapshot!(toml::from_str::<CacheKey>("git = { commit = 42 }").unwrap_err(), @"data did not match any variant of untagged enum CacheKey");
}

#[test]
fn git_pattern_unknown_field() {
insta::assert_snapshot!(toml::from_str::<GitPattern>("unknown = true").unwrap_err(), @"data did not match any variant of untagged enum GitPattern");
}
}

#[cfg(all(test, unix))]
mod tests_unix {
use anyhow::Result;
Expand Down
Loading