Use dynamic dispatch to simplify reporters (#10086)

## Summary

Sort of undecided on this. These are already stored as `dyn Reporter` in
each struct, so we're already using dynamic dispatch in that sense. But
all the methods take `impl Reporter`. This is sometimes nice (the
callsites are simpler?), but it also means that in practice, you often
_can't_ pass `None` to these methods that accept `Option<impl
Reporter>`, because Rust can't infer the generic type.

Anyway, this adds more consistency and simplifies the setup by using
`Arc<dyn Reporter>` everywhere.
This commit is contained in:
Charlie Marsh 2025-01-06 12:04:00 -05:00 committed by GitHub
parent 54b9e8ff82
commit 66a603b6c4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 117 additions and 74 deletions

View file

@ -44,7 +44,7 @@ impl GitResolver {
url: &GitUrl,
client: ClientWithMiddleware,
cache: PathBuf,
reporter: Option<impl Reporter + 'static>,
reporter: Option<Arc<dyn Reporter>>,
) -> Result<GitSha, GitResolverError> {
debug!("Resolving source distribution from Git: {url}");
@ -88,7 +88,7 @@ impl GitResolver {
url: &GitUrl,
client: ClientWithMiddleware,
cache: PathBuf,
reporter: Option<impl Reporter + 'static>,
reporter: Option<Arc<dyn Reporter>>,
) -> Result<Fetch, GitResolverError> {
debug!("Fetching source distribution from Git: {url}");
@ -138,7 +138,7 @@ impl GitResolver {
/// For example, given a Git dependency with a reference to a branch or tag, return a URL
/// with a precise reference to the current commit of that branch or tag.
///
/// This method takes into account various normalizations that are independent from the Git
/// This method takes into account various normalizations that are independent of the Git
/// layer. For example: removing `#subdirectory=pkg_dir`-like fragments, and removing `git+`
/// prefix kinds.
///

View file

@ -4,6 +4,7 @@
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::Result;
use reqwest_middleware::ClientWithMiddleware;
@ -24,11 +25,11 @@ pub struct GitSource {
/// The path to the Git source database.
cache: PathBuf,
/// The reporter to use for this source.
reporter: Option<Box<dyn Reporter>>,
reporter: Option<Arc<dyn Reporter>>,
}
impl GitSource {
/// Initialize a new Git source.
/// Initialize a [`GitSource`] with the given Git URL, HTTP client, and cache path.
pub fn new(
git: GitUrl,
client: impl Into<ClientWithMiddleware>,
@ -42,11 +43,11 @@ impl GitSource {
}
}
/// Set the [`Reporter`] to use for this `GIt` source.
/// Set the [`Reporter`] to use for the [`GitSource`].
#[must_use]
pub fn with_reporter(self, reporter: impl Reporter + 'static) -> Self {
pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
Self {
reporter: Some(Box::new(reporter)),
reporter: Some(reporter),
..self
}
}