Debian Codegraph @

contrib/merge-lists/src/main.rs

raw
1 use std::cmp::max;
2 use std::cmp::min;
3 use std::cmp::Ordering;
4 use std::collections::HashSet;
5 use std::ffi::OsString;
6 use std::ops::Range;
7 use std::path::PathBuf;
8
9 use clap::ArgGroup;
10 use clap::Parser;
11 use itertools::Itertools;
12 use regex::bytes::Regex;
13 use similar::ChangeTag;
14
15 fn find_unchanged_ranges(
16 old_bytes: &[u8],
17 new_bytes: &[u8],
18 ) -> Vec<(Range<usize>, Range<usize>)> {
19 let diff = similar::TextDiff::configure()
20 .algorithm(similar::Algorithm::Patience)
21 .diff_lines(old_bytes, new_bytes);
22 let mut new_unchanged_ranges = vec![];
23 let mut old_index = 0;
24 let mut new_index = 0;
25 for diff in diff.iter_all_changes() {
26 match diff.tag() {
27 ChangeTag::Equal => {
28 new_unchanged_ranges.push((
29 old_index..old_index + diff.value().len(),
30 new_index..new_index + diff.value().len(),
31 ));
32 old_index += diff.value().len();
33 new_index += diff.value().len();
34 }
35 ChangeTag::Delete => {
36 old_index += diff.value().len();
37 }
38 ChangeTag::Insert => {
39 new_index += diff.value().len();
40 }
41 }
42 }
43 new_unchanged_ranges
44 }
45
46 /// Returns a list of all the lines in the input (including trailing newlines),
47 /// but only if they all match the regex and they are sorted.
48 fn get_lines<'input>(
49 input: &'input [u8],
50 regex: &Regex,
51 ) -> Option<Vec<&'input [u8]>> {
52 let lines = input.split_inclusive(|x| *x == b'\n').collect_vec();
53 let mut previous_line = "".as_bytes();
54 for line in &lines {
55 if *line < previous_line {
56 return None;
57 }
58 if !regex.is_match(line) {
59 return None;
60 }
61 previous_line = line;
62 }
63 Some(lines)
64 }
65
66 fn resolve_conflict(
67 base_slice: &[u8],
68 local_slice: &[u8],
69 other_slice: &[u8],
70 regex: &Regex,
71 ) -> Option<Vec<u8>> {
72 let base_lines = get_lines(base_slice, regex)?;
73 let local_lines = get_lines(local_slice, regex)?;
74 let other_lines = get_lines(other_slice, regex)?;
75 let base_lines_set: HashSet<_> = base_lines.iter().copied().collect();
76 let local_lines_set: HashSet<_> = local_lines.iter().copied().collect();
77 let other_lines_set: HashSet<_> = other_lines.iter().copied().collect();
78 let mut result = local_lines_set;
79 for to_add in other_lines_set.difference(&base_lines_set) {
80 result.insert(to_add);
81 }
82 for to_remove in base_lines_set.difference(&other_lines_set) {
83 result.remove(to_remove);
84 }
85 Some(result.into_iter().sorted().collect_vec().concat())
86 }
87
88 fn resolve(
89 base_bytes: &[u8],
90 local_bytes: &[u8],
91 other_bytes: &[u8],
92 regex: &Regex,
93 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
94 // Find unchanged ranges between the base and the two sides. We do that by
95 // initially considering the whole base unchanged. Then we compare each
96 // side with the base and intersect the unchanged ranges we find with
97 // what we had before.
98 let unchanged_ranges = vec![UnchangedRange {
99 base_range: 0..base_bytes.len(),
100 offsets: vec![],
101 }];
102 let unchanged_ranges = intersect_regions(
103 unchanged_ranges,
104 &find_unchanged_ranges(base_bytes, local_bytes),
105 );
106 let mut unchanged_ranges = intersect_regions(
107 unchanged_ranges,
108 &find_unchanged_ranges(base_bytes, other_bytes),
109 );
110 // Add an empty UnchangedRange at the end to make it easier to find change
111 // ranges. That way there's a changed range before each UnchangedRange.
112 unchanged_ranges.push(UnchangedRange {
113 base_range: base_bytes.len()..base_bytes.len(),
114 offsets: vec![
115 local_bytes.len().wrapping_sub(base_bytes.len()) as isize,
116 other_bytes.len().wrapping_sub(base_bytes.len()) as isize,
117 ],
118 });
119
120 let mut new_base_bytes: Vec<u8> = vec![];
121 let mut new_local_bytes: Vec<u8> = vec![];
122 let mut new_other_bytes: Vec<u8> = vec![];
123 let mut previous = UnchangedRange { base_range: 0..0, offsets: vec![0, 0] };
124 for current in unchanged_ranges {
125 let base_slice =
126 &base_bytes[previous.base_range.end..current.base_range.start];
127 let local_slice = &local_bytes[previous.end(0)..current.start(0)];
128 let other_slice = &other_bytes[previous.end(1)..current.start(1)];
129 if let Some(resolution) =
130 resolve_conflict(base_slice, local_slice, other_slice, regex)
131 {
132 new_base_bytes.extend(&resolution);
133 new_local_bytes.extend(&resolution);
134 new_other_bytes.extend(&resolution);
135 } else {
136 new_base_bytes.extend(base_slice);
137 new_local_bytes.extend(local_slice);
138 new_other_bytes.extend(other_slice);
139 }
140 new_base_bytes.extend(&base_bytes[current.base_range.clone()]);
141 new_local_bytes.extend(&local_bytes[current.start(0)..current.end(0)]);
142 new_other_bytes.extend(&other_bytes[current.start(1)..current.end(1)]);
143 previous = current;
144 }
145
146 (new_base_bytes, new_local_bytes, new_other_bytes)
147 }
148
149 /// A tool that performs a 3-way merge, resolving conflicts in sorted lists and
150 /// leaving other conflicts unchanged. This is useful with Mercurial's support
151 /// for partial merge tools (configured in `[partial-merge-tools]`).
152 #[derive(Parser, Debug)]
153 #[clap(version, about, long_about = None)]
154 #[clap(group(ArgGroup::new("match").required(true).args(&["pattern", "python-imports"])))]
155 struct Args {
156 /// Path to the file's content in the "local" side
157 local: OsString,
158
159 /// Path to the file's content in the base
160 base: OsString,
161
162 /// Path to the file's content in the "other" side
163 other: OsString,
164
165 /// Regular expression to use
166 #[clap(long, short)]
167 pattern: Option<String>,
168
169 /// Use built-in regular expression for Python imports
170 #[clap(long)]
171 python_imports: bool,
172 }
173
174 fn get_regex(args: &Args) -> Regex {
175 let pattern = if args.python_imports {
176 r"import \w+(\.\w+)*( +#.*)?\n|from (\w+(\.\w+)* import \w+( as \w+)?(, \w+( as \w+)?)*( +#.*)?)"
177 } else if let Some(pattern) = &args.pattern {
178 pattern
179 } else {
180 ".*"
181 };
182 let pattern = format!(r"{}\r?\n?", pattern);
183 regex::bytes::Regex::new(&pattern).unwrap()
184 }
185
186 fn main() {
187 let args: Args = Args::parse();
188
189 let base_path = PathBuf::from(&args.base);
190 let local_path = PathBuf::from(&args.local);
191 let other_path = PathBuf::from(&args.other);
192
193 let base_bytes = std::fs::read(&base_path).unwrap();
194 let local_bytes = std::fs::read(&local_path).unwrap();
195 let other_bytes = std::fs::read(&other_path).unwrap();
196
197 let regex = get_regex(&args);
198 let (new_base_bytes, new_local_bytes, new_other_bytes) =
199 resolve(&base_bytes, &local_bytes, &other_bytes, &regex);
200
201 // Write out the result if anything changed
202 if new_base_bytes != base_bytes {
203 std::fs::write(&base_path, new_base_bytes).unwrap();
204 }
205 if new_local_bytes != local_bytes {
206 std::fs::write(&local_path, new_local_bytes).unwrap();
207 }
208 if new_other_bytes != other_bytes {
209 std::fs::write(&other_path, new_other_bytes).unwrap();
210 }
211 }
212
213 fn checked_add(base: usize, offset: isize) -> usize {
214 if offset < 0 {
215 base.checked_sub(offset.checked_abs().unwrap() as usize).unwrap()
216 } else {
217 base.checked_add(offset as usize).unwrap()
218 }
219 }
220
221 // The remainder of the file is copied from
222 // https://github.com/martinvonz/jj/blob/main/lib/src/diff.rs
223
224 #[derive(Clone, PartialEq, Eq, Debug)]
225 struct UnchangedRange {
226 base_range: Range<usize>,
227 offsets: Vec<isize>,
228 }
229
230 impl UnchangedRange {
231 fn start(&self, side: usize) -> usize {
232 checked_add(self.base_range.start, self.offsets[side])
233 }
234
235 fn end(&self, side: usize) -> usize {
236 checked_add(self.base_range.end, self.offsets[side])
237 }
238 }
239
240 impl PartialOrd for UnchangedRange {
241 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
242 Some(self.cmp(other))
243 }
244 }
245
246 impl Ord for UnchangedRange {
247 fn cmp(&self, other: &Self) -> Ordering {
248 self.base_range
249 .start
250 .cmp(&other.base_range.start)
251 .then_with(|| self.base_range.end.cmp(&other.base_range.end))
252 }
253 }
254
255 /// Takes the current regions and intersects it with the new unchanged ranges
256 /// from a 2-way diff. The result is a map of unchanged regions with one more
257 /// offset in the map's values.
258 fn intersect_regions(
259 current_ranges: Vec<UnchangedRange>,
260 new_unchanged_ranges: &[(Range<usize>, Range<usize>)],
261 ) -> Vec<UnchangedRange> {
262 let mut result = vec![];
263 let mut current_ranges_iter = current_ranges.into_iter().peekable();
264 for (new_base_range, other_range) in new_unchanged_ranges.iter() {
265 assert_eq!(new_base_range.len(), other_range.len());
266 while let Some(UnchangedRange { base_range, offsets }) =
267 current_ranges_iter.peek()
268 {
269 // No need to look further if we're past the new range.
270 if base_range.start >= new_base_range.end {
271 break;
272 }
273 // Discard any current unchanged regions that don't match between
274 // the base and the new input.
275 if base_range.end <= new_base_range.start {
276 current_ranges_iter.next();
277 continue;
278 }
279 let new_start = max(base_range.start, new_base_range.start);
280 let new_end = min(base_range.end, new_base_range.end);
281 let mut new_offsets = offsets.clone();
282 new_offsets
283 .push(other_range.start.wrapping_sub(new_base_range.start)
284 as isize);
285 result.push(UnchangedRange {
286 base_range: new_start..new_end,
287 offsets: new_offsets,
288 });
289 if base_range.end >= new_base_range.end {
290 // Break without consuming the item; there may be other new
291 // ranges that overlap with it.
292 break;
293 }
294 current_ranges_iter.next();
295 }
296 }
297 result
298 }