Skip to content
Draft
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 rust/pact_models/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub mod sync_pact;
pub mod message_pact;
mod iterator_utils;
pub mod plugins;
pub mod spec_version_check;

/// A "prelude" or a default list of import types to include.
pub mod prelude {
Expand Down
45 changes: 40 additions & 5 deletions rust/pact_models/src/matchingrules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,17 @@ impl MatchingRule {
}
}

/// Converts this `MatchingRule` to the V2 rule that matches the same values, if there is one.
/// Only lossless rewrites are done: `include` becomes an escaped `regex`. Everything else
/// returns None.
pub fn to_v2_json(&self) -> Option<Value> {
match self {
MatchingRule::Include(s) => Some(json!({ "match": "regex",
"regex": format!("(?s).*{}.*", regex::escape(s)) })),
_ => None
}
}

/// Converts this `MatchingRule` to a `Value` struct
pub fn to_json(&self) -> Value {
match self {
Expand Down Expand Up @@ -817,11 +828,17 @@ impl RuleList {

fn to_v2_json(&self) -> Value {
match self.rules.get(0) {
Some(rule) => rule.to_json(),
Some(rule) => rule.to_v2_json().unwrap_or_else(|| rule.to_json()),
None => json!({})
}
}

// V2 has no equality matcher, but equality is what V2 does when no rule applies. So the
// rule can be left out, as long as nothing cascades onto this path from a parent.
fn is_only_equality(&self) -> bool {
matches!(self.rules.as_slice(), [MatchingRule::Equality])
}

/// If there is a type matcher defined for the rule list
pub fn type_matcher_defined(&self) -> bool {
self.rules.iter().any(|rule| match rule {
Expand Down Expand Up @@ -1138,28 +1155,46 @@ impl MatchingRuleCategory {
/// Returns a JSON Value representation in V2 format
pub fn to_v2_json(&self) -> HashMap<String, Value> {
let mut map = hashmap!{};
let rules = self.v2_rules();

match &self.name {
Category::PATH => for (_, v) in self.rules.clone() {
Category::PATH => for (_, v) in rules.clone() {
map.insert("$.path".to_string(), v.to_v2_json());
}
Category::BODY => for (k, v) in self.rules.clone() {
Category::BODY => for (k, v) in rules.clone() {
map.insert(String::from(k).replace("$", "$.body"), v.to_v2_json());
}
Category::HEADER | Category::QUERY => for (k, v) in &self.rules {
Category::HEADER | Category::QUERY => for (k, v) in &rules {
let mut path = DocPath::root();
path.push_field(self.name.v2_form());
path.push_path(k);
map.insert(path.to_string(), v.to_v2_json());
}
_ => for (k, v) in &self.rules {
_ => for (k, v) in &rules {
map.insert(format!("$.{}.{}", self.name.v2_form(), k), v.to_v2_json());
}
};

map
}

// The rules to write to a V2 pact: equality-only rules are dropped where no other rule is
// defined on a parent path, as V2 falls back to equality there anyway.
fn v2_rules(&self) -> HashMap<DocPath, RuleList> {
self.rules.iter()
.filter(|(path, rules)| !(rules.is_only_equality() && !self.has_parent_rule(path)))
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}

fn has_parent_rule(&self, path: &DocPath) -> bool {
let path = path.to_string();
self.rules.keys()
.map(|other| other.to_string())
.any(|other| other != path && (path.starts_with(&format!("{}.", other))
|| path.starts_with(&format!("{}[", other))))
}

/// If there is a type matcher defined for the category
pub fn type_matcher_defined(&self) -> bool {
self.rules.values().any(|rule_list| rule_list.type_matcher_defined())
Expand Down
30 changes: 27 additions & 3 deletions rust/pact_models/src/pact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use std::sync::{Arc, Mutex};

use anyhow::anyhow;
#[cfg(not(target_family = "wasm"))] use anyhow::Context;
use itertools::Itertools;
use lazy_static::lazy_static;
use maplit::btreemap;
use serde_json::{json, Value};
Expand All @@ -24,6 +25,7 @@ use crate::{Consumer, PactSpecification, Provider};
use crate::interaction::Interaction;
use crate::message_pact::MessagePact;
use crate::plugins::PluginData;
use crate::spec_version_check::{spec_violations, strict_spec_version, STRICT_SPEC_ENV_VAR};
use crate::sync_pact::RequestResponsePact;
use crate::v4;
use crate::v4::pact::V4Pact;
Expand Down Expand Up @@ -240,9 +242,9 @@ pub fn write_pact(
f.read_to_string(&mut existing)?;
}

let pact_json = if existing.is_empty() {
let json = if existing.is_empty() {
debug!("Writing new pact file to {:?}", path);
serde_json::to_string_pretty(&pact.to_json(pact_spec)?)?
pact.to_json(pact_spec)?
} else {
debug!("Merging pact with file {:?}", path);
let existing_pact = parse_pact_file(&existing, path)?;
Expand All @@ -253,8 +255,10 @@ pub fn write_pact(
}

let merged_pact = pact.merge(existing_pact.deref())?;
serde_json::to_string_pretty(&merged_pact.to_json(pact_spec)?)?
merged_pact.to_json(pact_spec)?
};
check_spec_version(&json, pact_spec, path)?;
let pact_json = serde_json::to_string_pretty(&json)?;

f.set_len(0)?;
f.seek(SeekFrom::Start(0))?;
Expand All @@ -264,6 +268,26 @@ pub fn write_pact(
}


// Rules and generators the target spec doesn't define are a warning for now, and an error
// with PACT_STRICT_SPEC_VERSION=true. The plan is to make the error the default in the next
// major version.
fn check_spec_version(json: &Value, pact_spec: PactSpecification, path: &Path) -> anyhow::Result<()> {
let violations = spec_violations(json, pact_spec);
if violations.is_empty() {
return Ok(());
}
let details = violations.iter().map(|v| format!(" {}", v)).join("\n");
if strict_spec_version() {
Err(anyhow!("Pact {:?} uses features the {} specification does not define:\n{}\n\
Write it as a newer specification version, or remove them", path, pact_spec, details))
} else {
warn!("Pact {:?} uses features the {} specification does not define, they will be written \
anyway but other pact implementations may reject or ignore them (set {}=true to make this \
an error):\n{}", path, pact_spec, STRICT_SPEC_ENV_VAR, details);
Ok(())
}
}

/// Construct Metadata from JSON value
pub fn parse_meta_data(pact_json: &Value) -> BTreeMap<String, BTreeMap<String, String>> {
match pact_json.get("metadata") {
Expand Down
2 changes: 1 addition & 1 deletion rust/pact_models/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ impl Request {
&self.matching_rules.clone(), spec_version));
}

if self.generators.is_not_empty() {
if self.generators.is_not_empty() && spec_version >= &PactSpecification::V3 {
map.insert("generators".to_string(), generators_to_json(
&self.generators.clone(), spec_version));
}
Expand Down
2 changes: 1 addition & 1 deletion rust/pact_models/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl Response {
map.insert("matchingRules".to_string(), matchers_to_json(
&self.matching_rules.clone(), spec_version));
}
if self.generators.is_not_empty() {
if self.generators.is_not_empty() && spec_version >= &PactSpecification::V3 {
map.insert("generators".to_string(), generators_to_json(
&self.generators.clone(), spec_version));
}
Expand Down
Loading