Skip to content

Commit

Permalink
Merge pull request #223 from matts1/sorted
Browse files Browse the repository at this point in the history
Make serialization of packages deterministic.
  • Loading branch information
oli-obk committed Apr 3, 2023
2 parents 2876c37 + 0a73e18 commit 084de02
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/lib.rs
Expand Up @@ -81,7 +81,7 @@
use camino::Utf8PathBuf;
#[cfg(feature = "builder")]
use derive_builder::Builder;
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use std::env;
use std::ffi::OsString;
use std::fmt;
Expand Down Expand Up @@ -109,7 +109,7 @@ pub use messages::{
ArtifactBuilder, ArtifactProfileBuilder, BuildFinishedBuilder, BuildScriptBuilder,
CompilerMessageBuilder,
};
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, Serializer};

mod dependency;
pub mod diagnostic;
Expand Down Expand Up @@ -139,6 +139,18 @@ fn is_null(value: &serde_json::Value) -> bool {
matches!(value, serde_json::Value::Null)
}

/// Helper to ensure that hashmaps serialize in sorted order, to make
/// serialization deterministic.
fn sorted_map<S: Serializer, K: Serialize + Ord, V: Serialize>(
value: &HashMap<K, V>,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
value
.iter()
.collect::<BTreeMap<_, _>>()
.serialize(serializer)
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[non_exhaustive]
Expand Down Expand Up @@ -311,6 +323,7 @@ pub struct Package {
/// Targets provided by the crate (lib, bin, example, test, ...)
pub targets: Vec<Target>,
/// Features provided by the crate, mapped to the features required by that feature.
#[serde(serialize_with = "sorted_map")]
pub features: HashMap<String, Vec<String>>,
/// Path containing the `Cargo.toml`
pub manifest_path: Utf8PathBuf,
Expand Down

0 comments on commit 084de02

Please sign in to comment.