1 // Copyright (c) 2018 The predicates-rs Project Developers.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8
9 use std::borrow;
10 use std::fmt;
11
12 use crate::reflection;
13 use crate::Predicate;
14
15 /// Predicate that diffs two strings.
16 ///
17 /// This is created by the `predicate::str::diff`.
18 #[derive(Debug, Clone, PartialEq, Eq)]
19 pub struct DifferencePredicate {
20 orig: borrow::Cow<'static, str>,
21 }
22
23 impl Predicate<str> for DifferencePredicate {
eval(&self, edit: &str) -> bool24 fn eval(&self, edit: &str) -> bool {
25 edit == self.orig
26 }
27
find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>>28 fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> {
29 let result = variable != self.orig;
30 if result == expected {
31 None
32 } else {
33 let palette = crate::Palette::new(true);
34 let orig: Vec<_> = self.orig.lines().map(|l| format!("{l}\n")).collect();
35 let variable: Vec<_> = variable.lines().map(|l| format!("{l}\n")).collect();
36 let diff = difflib::unified_diff(
37 &orig,
38 &variable,
39 "",
40 "",
41 &palette.expected("orig").to_string(),
42 &palette.var("var").to_string(),
43 0,
44 );
45 let mut diff = colorize_diff(diff, palette);
46 diff.insert(0, "\n".to_owned());
47
48 Some(
49 reflection::Case::new(Some(self), result)
50 .add_product(reflection::Product::new("diff", diff.join(""))),
51 )
52 }
53 }
54 }
55
56 impl reflection::PredicateReflection for DifferencePredicate {
parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a>57 fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> {
58 let params = vec![reflection::Parameter::new("original", &self.orig)];
59 Box::new(params.into_iter())
60 }
61 }
62
63 impl fmt::Display for DifferencePredicate {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 let palette = crate::Palette::new(f.alternate());
66 write!(
67 f,
68 "{:#} {:#} {:#}",
69 palette.description("diff"),
70 palette.expected("original"),
71 palette.var("var"),
72 )
73 }
74 }
75
76 /// Creates a new `Predicate` that diffs two strings.
77 ///
78 /// # Examples
79 ///
80 /// ```
81 /// use predicates::prelude::*;
82 ///
83 /// let predicate_fn = predicate::str::diff("Hello World");
84 /// assert_eq!(true, predicate_fn.eval("Hello World"));
85 /// assert!(predicate_fn.find_case(false, "Hello World").is_none());
86 /// assert_eq!(false, predicate_fn.eval("Goodbye World"));
87 /// assert!(predicate_fn.find_case(false, "Goodbye World").is_some());
88 /// ```
diff<S>(orig: S) -> DifferencePredicate where S: Into<borrow::Cow<'static, str>>,89 pub fn diff<S>(orig: S) -> DifferencePredicate
90 where
91 S: Into<borrow::Cow<'static, str>>,
92 {
93 DifferencePredicate { orig: orig.into() }
94 }
95
96 #[cfg(feature = "color")]
colorize_diff(mut lines: Vec<String>, palette: crate::Palette) -> Vec<String>97 fn colorize_diff(mut lines: Vec<String>, palette: crate::Palette) -> Vec<String> {
98 for (i, line) in lines.iter_mut().enumerate() {
99 match (i, line.as_bytes().first()) {
100 (0, _) => {
101 if let Some((prefix, body)) = line.split_once(' ') {
102 *line = format!("{:#} {}", palette.expected(prefix), body);
103 }
104 }
105 (1, _) => {
106 if let Some((prefix, body)) = line.split_once(' ') {
107 *line = format!("{:#} {}", palette.var(prefix), body);
108 }
109 }
110 (_, Some(b'-')) => {
111 let (prefix, body) = line.split_at(1);
112 *line = format!("{:#}{}", palette.expected(prefix), body);
113 }
114 (_, Some(b'+')) => {
115 let (prefix, body) = line.split_at(1);
116 *line = format!("{:#}{}", palette.var(prefix), body);
117 }
118 (_, Some(b'@')) => {
119 *line = format!("{:#}", palette.description(&line));
120 }
121 _ => (),
122 }
123 }
124 lines
125 }
126
127 #[cfg(not(feature = "color"))]
colorize_diff(lines: Vec<String>, _palette: crate::Palette) -> Vec<String>128 fn colorize_diff(lines: Vec<String>, _palette: crate::Palette) -> Vec<String> {
129 lines
130 }
131