summaryrefslogtreecommitdiffstats
path: root/src/commute.rs
blob: 892a75505f77f9674df1965b69fe778321bb967a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use crate::owned;

/// Tests if all elements of the iterator are equal to each other.
///
/// An empty iterator returns `true`.
///
/// `uniform()` is short-circuiting. It will stop processing as soon
/// as it finds two pairwise inequal elements.
fn uniform<I, E>(iter: I) -> bool
where
    I: IntoIterator<Item = E>,
    E: Eq,
{
    let mut iter = iter.into_iter();
    match iter.next() {
        Some(first) => iter.all(|e| e == first),
        None => true,
    }
}

pub fn commute(first: &owned::Hunk, second: &owned::Hunk) -> Option<(owned::Hunk, owned::Hunk)> {
    let (_, _, first_upper, first_lower) = first.anchors();
    let (second_upper, second_lower, _, _) = second.anchors();

    // represent hunks in content order rather than application order
    let (first_above, above, below) = {
        if first_lower <= second_upper {
            (true, first, second)
        } else if second_lower <= first_upper {
            (false, second, first)
        } else {
            // if both hunks are exclusively adding or removing, and
            // both hunks are composed entirely of the same line being
            // repeated, then they commute no matter what their
            // offsets are, because they can be interleaved in any
            // order without changing the final result
            if (first.added.lines.is_empty()
                && second.added.lines.is_empty()
                && uniform(first.removed.lines.iter().chain(&*second.removed.lines)))
                || (first.removed.lines.is_empty()
                    && second.removed.lines.is_empty()
                    && uniform(first.added.lines.iter().chain(&*second.added.lines)))
            {
                // TODO: removed/added start positions probably need to be
                // tweaked here
                return Some((second.clone(), first.clone()));
            }
            // these hunks overlap and cannot be interleaved, so they
            // do not commute
            return None;
        }
    };

    let above = above.clone();
    let mut below = below.clone();
    let above_change_offset = (above.added.lines.len() as i64 - above.removed.lines.len() as i64)
        * if first_above { -1 } else { 1 };
    below.added.start = (below.added.start as i64 + above_change_offset) as usize;
    below.removed.start = (below.removed.start as i64 + above_change_offset) as usize;

    Some(if first_above {
        (below, above)
    } else {
        (above, below)
    })
}

pub fn commute_diff_before<'a, I>(after: &owned::Hunk, before: I) -> Option<owned::Hunk>
where
    I: IntoIterator<Item = &'a owned::Hunk>,
    <I as IntoIterator>::IntoIter: DoubleEndedIterator,
{
    before
        .into_iter()
        // the patch's hunks must be iterated in reverse application
        // order (last applied to first applied), which also happens
        // to be reverse line order (bottom to top), which also
        // happens to be reverse of the order they're stored
        .rev()
        .try_fold(after.clone(), |after, next| {
            commute(next, &after).map(|(commuted_after, _)| commuted_after)
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::rc::Rc;

    #[test]
    fn test_commute() {
        // example init: <<EOF
        // foo
        // EOF
        let hunk1 = owned::Hunk {
            added: owned::Block {
                start: 2,
                lines: Rc::new(vec![b"bar\n".to_vec()]),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 1,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
        };
        // after hunk1: <<EOF
        // foo
        // bar
        // EOF
        let hunk2 = owned::Hunk {
            added: owned::Block {
                start: 1,
                lines: Rc::new(vec![b"bar\n".to_vec()]),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 0,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
        };
        // after hunk2: <<EOF
        // bar
        // foo
        // bar
        // EOF

        let (new1, new2) = commute(&hunk1, &hunk2).unwrap();
        assert_eq!(new1.added.start, 1);
        assert_eq!(new2.added.start, 3);
    }

    #[test]
    fn test_commute_trivial_add() {
        let mut line = ::std::iter::repeat(b"bar\n".to_vec());
        let hunk1 = owned::Hunk {
            added: owned::Block {
                start: 1,
                lines: Rc::new((&mut line).take(4).collect::<Vec<_>>()),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 0,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
        };
        let hunk2 = owned::Hunk {
            added: owned::Block {
                start: 1,
                lines: Rc::new((&mut line).take(2).collect::<Vec<_>>()),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 0,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
        };

        let (new1, new2) = commute(&hunk1, &hunk2).unwrap();
        assert_eq!(new1.added.lines.len(), 2);
        assert_eq!(new2.added.lines.len(), 4);
    }

    #[test]
    fn test_commute_trivial_remove() {
        let mut line = ::std::iter::repeat(b"bar\n".to_vec());
        let hunk1 = owned::Hunk {
            added: owned::Block {
                start: 1,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 4,
                lines: Rc::new((&mut line).take(4).collect::<Vec<_>>()),
                trailing_newline: true,
            },
        };
        let hunk2 = owned::Hunk {
            added: owned::Block {
                start: 1,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 2,
                lines: Rc::new((&mut line).take(2).collect::<Vec<_>>()),
                trailing_newline: true,
            },
        };

        let (new1, new2) = commute(&hunk1, &hunk2).unwrap();
        assert_eq!(new1.removed.lines.len(), 2);
        assert_eq!(new2.removed.lines.len(), 4);
    }

    #[test]
    fn test_commute_patch() {
        // example init: <<EOF
        // foo
        // foo
        // EOF
        let patch = vec![
            owned::Hunk {
                added: owned::Block {
                    start: 1,
                    lines: Rc::new(vec![b"bar\n".to_vec()]),
                    trailing_newline: true,
                },
                removed: owned::Block {
                    start: 0,
                    lines: Rc::new(vec![]),
                    trailing_newline: true,
                },
            },
            owned::Hunk {
                added: owned::Block {
                    start: 3,
                    lines: Rc::new(vec![b"bar\n".to_vec()]),
                    trailing_newline: true,
                },
                removed: owned::Block {
                    start: 1,
                    lines: Rc::new(vec![]),
                    trailing_newline: true,
                },
            },
        ];
        // after patch: <<EOF
        // bar
        // foo
        // bar
        // foo
        // EOF
        let hunk = owned::Hunk {
            added: owned::Block {
                start: 5,
                lines: Rc::new(vec![b"bar\n".to_vec()]),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 4,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
        };
        // after hunk: <<EOF
        // bar
        // foo
        // bar
        // foo
        // bar
        // EOF

        let commuted = commute_diff_before(&hunk, &patch).unwrap();
        assert_eq!(commuted.added.start, 3);
    }
}