patchkit 0.2.4

A library for parsing and manipulating patch files
Documentation
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Editor implementation for quilt series files

use crate::edit::series::lex::SyntaxKind;
use crate::edit::series::lossless::{SeriesEntry, SeriesFile, SeriesLang};
use rowan::{ast::AstNode, GreenNodeBuilder, NodeOrToken};

impl SeriesFile {
    /// Number of patches in the series
    pub fn len(&self) -> usize {
        self.patch_entries().count()
    }

    /// Check if the series is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Add a patch at the end of the series
    pub fn push(
        &mut self,
        name: impl AsRef<str>,
        options: impl IntoIterator<Item = impl AsRef<str>>,
    ) {
        let patch_count = self.len();
        self.insert(patch_count, name, options);
    }

    /// Add a patch at the beginning of the series
    pub fn prepend(
        &mut self,
        name: impl AsRef<str>,
        options: impl IntoIterator<Item = impl AsRef<str>>,
    ) {
        self.insert(0, name, options);
    }

    /// Insert a patch entry at the specified index
    pub fn insert(
        &mut self,
        index: usize,
        name: impl AsRef<str>,
        options: impl IntoIterator<Item = impl AsRef<str>>,
    ) {
        let name = name.as_ref();
        let options: Vec<String> = options
            .into_iter()
            .map(|s| s.as_ref().to_string())
            .collect();
        // Build just the new patch entry (minimal allocation)
        let new_entry_green = Self::build_patch_entry_green(name, &options);
        let new_entry_syntax = rowan::SyntaxNode::<SeriesLang>::new_root_mut(new_entry_green);
        let new_element = NodeOrToken::Node(new_entry_syntax);

        // Find the insertion point by counting patch entries
        let mut patch_count = 0;
        let mut insertion_index = 0;

        for (i, element) in self.syntax().children_with_tokens().enumerate() {
            if let NodeOrToken::Node(node) = &element {
                if let Some(entry) = SeriesEntry::cast(node.clone()) {
                    if entry.as_patch_entry().is_some() {
                        if patch_count == index {
                            insertion_index = i;
                            break;
                        }
                        patch_count += 1;
                    }
                }
            }
            // If we reach the end, insert at the end
            insertion_index = i + 1;
        }

        // Use splice_children for efficient in-place modification
        self.syntax()
            .splice_children(insertion_index..insertion_index, vec![new_element]);
    }

    /// Remove a patch entry by name
    pub fn remove(&mut self, name: &str) -> bool {
        // Find the entry to remove
        for (i, element) in self.syntax().children_with_tokens().enumerate() {
            if let NodeOrToken::Node(node) = element {
                if let Some(entry) = SeriesEntry::cast(node.clone()) {
                    if let Some(patch) = entry.as_patch_entry() {
                        if patch.name().as_deref() == Some(name) {
                            // Remove this single element using splice_children
                            self.syntax().splice_children(i..i + 1, vec![]);
                            return true;
                        }
                    }
                }
            }
        }
        false
    }

    /// Update patch options  
    pub fn set_options(
        &mut self,
        name: &str,
        options: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> bool {
        let new_options: Vec<String> = options
            .into_iter()
            .map(|s| s.as_ref().to_string())
            .collect();
        // Find the entry to update
        for (i, element) in self.syntax().children_with_tokens().enumerate() {
            if let NodeOrToken::Node(node) = element {
                if let Some(entry) = SeriesEntry::cast(node.clone()) {
                    if let Some(patch) = entry.as_patch_entry() {
                        if patch.name().as_deref() == Some(name) {
                            // Build replacement entry
                            let new_entry_green = Self::build_patch_entry_green(name, &new_options);
                            let new_entry_syntax =
                                rowan::SyntaxNode::<SeriesLang>::new_root_mut(new_entry_green);
                            let new_element = NodeOrToken::Node(new_entry_syntax);

                            // Replace this single element using splice_children
                            self.syntax().splice_children(i..i + 1, vec![new_element]);
                            return true;
                        }
                    }
                }
            }
        }
        false
    }

    /// Add a comment at the end of the series
    pub fn add_comment(&mut self, text: impl AsRef<str>) {
        let text = text.as_ref();
        // Build just the new comment entry
        let new_comment_green = Self::build_comment_entry_green(text);
        let new_comment_syntax = rowan::SyntaxNode::<SeriesLang>::new_root_mut(new_comment_green);
        let new_element = NodeOrToken::Node(new_comment_syntax);

        // Append at the end
        let end_index = self.syntax().children_with_tokens().count();
        self.syntax()
            .splice_children(end_index..end_index, vec![new_element]);
    }

    /// Rename a patch entry
    pub fn rename(&mut self, old_name: &str, new_name: &str) -> bool {
        // Find the entry to rename
        for (i, element) in self.syntax().children_with_tokens().enumerate() {
            if let NodeOrToken::Node(node) = element {
                if let Some(entry) = SeriesEntry::cast(node.clone()) {
                    if let Some(patch) = entry.as_patch_entry() {
                        if patch.name().as_deref() == Some(old_name) {
                            // Get existing options
                            let options = patch.option_strings();

                            // Build replacement entry with new name
                            let new_entry_green = Self::build_patch_entry_green(new_name, &options);
                            let new_entry_syntax =
                                rowan::SyntaxNode::<SeriesLang>::new_root_mut(new_entry_green);
                            let new_element = NodeOrToken::Node(new_entry_syntax);

                            // Replace using splice_children
                            self.syntax().splice_children(i..i + 1, vec![new_element]);
                            return true;
                        }
                    }
                }
            }
        }
        false
    }

    /// Move a patch to a new position
    pub fn move_to(&mut self, name: &str, new_index: usize) -> bool {
        // First, find and remove the patch
        let mut patch_entry = None;
        let mut patch_options = Vec::new();

        for (i, element) in self.syntax().children_with_tokens().enumerate() {
            if let NodeOrToken::Node(node) = &element {
                if let Some(entry) = SeriesEntry::cast(node.clone()) {
                    if let Some(patch) = entry.as_patch_entry() {
                        if patch.name().as_deref() == Some(name) {
                            patch_options = patch.option_strings();
                            patch_entry = Some(i);
                            break;
                        }
                    }
                }
            }
        }

        if let Some(old_index) = patch_entry {
            // Remove from old position
            self.syntax()
                .splice_children(old_index..old_index + 1, vec![]);

            // Find new insertion point
            let mut patch_count = 0;
            let mut insertion_index = 0;

            for (i, element) in self.syntax().children_with_tokens().enumerate() {
                if let NodeOrToken::Node(node) = &element {
                    if let Some(entry) = SeriesEntry::cast(node.clone()) {
                        if entry.as_patch_entry().is_some() {
                            if patch_count == new_index {
                                insertion_index = i;
                                break;
                            }
                            patch_count += 1;
                        }
                    }
                }
                insertion_index = i + 1;
            }

            // Insert at new position
            let new_entry_green = Self::build_patch_entry_green(name, &patch_options);
            let new_entry_syntax = rowan::SyntaxNode::<SeriesLang>::new_root_mut(new_entry_green);
            let new_element = NodeOrToken::Node(new_entry_syntax);

            self.syntax()
                .splice_children(insertion_index..insertion_index, vec![new_element]);
            true
        } else {
            false
        }
    }

    /// Insert a comment at a specific position
    pub fn insert_comment(&mut self, index: usize, text: impl AsRef<str>) {
        let text = text.as_ref();
        // Build the new comment entry
        let new_comment_green = Self::build_comment_entry_green(text);
        let new_comment_syntax = rowan::SyntaxNode::<SeriesLang>::new_root_mut(new_comment_green);
        let new_element = NodeOrToken::Node(new_comment_syntax);

        // Find the insertion point by counting all entries
        let mut entry_count = 0;
        let mut insertion_index = 0;

        for (i, element) in self.syntax().children_with_tokens().enumerate() {
            if let NodeOrToken::Node(node) = &element {
                if let Some(_) = SeriesEntry::cast(node.clone()) {
                    if entry_count == index {
                        insertion_index = i;
                        break;
                    }
                    entry_count += 1;
                }
            }
            insertion_index = i + 1;
        }

        // Insert the comment
        self.syntax()
            .splice_children(insertion_index..insertion_index, vec![new_element]);
    }

    /// Remove all patches, keeping comments  
    pub fn clear(&mut self) {
        let mut indices_to_remove = Vec::new();

        // Find all patch entries
        for (i, element) in self.syntax().children_with_tokens().enumerate() {
            if let NodeOrToken::Node(node) = element {
                if let Some(entry) = SeriesEntry::cast(node.clone()) {
                    if entry.as_patch_entry().is_some() {
                        indices_to_remove.push(i);
                    }
                }
            }
        }

        // Remove in reverse order to maintain indices
        for &i in indices_to_remove.iter().rev() {
            self.syntax().splice_children(i..i + 1, vec![]);
        }
    }

    /// Check if a patch exists
    pub fn contains(&self, name: &str) -> bool {
        self.patch_entries()
            .any(|patch| patch.name().as_deref() == Some(name))
    }

    /// Get the position of a patch
    pub fn position(&self, name: &str) -> Option<usize> {
        self.patch_entries()
            .position(|patch| patch.name().as_deref() == Some(name))
    }

    /// Update multiple patches atomically
    pub fn update_all<F>(&mut self, mut updates: F)
    where
        F: FnMut(&str, Vec<String>) -> Option<Vec<String>>,
    {
        let mut modifications = Vec::new();

        // Collect all modifications first
        for (i, element) in self.syntax().children_with_tokens().enumerate() {
            if let NodeOrToken::Node(node) = element {
                if let Some(entry) = SeriesEntry::cast(node.clone()) {
                    if let Some(patch) = entry.as_patch_entry() {
                        if let Some(name) = patch.name() {
                            let current_options = patch.option_strings();
                            if let Some(new_options) = updates(&name, current_options) {
                                let new_entry_green =
                                    Self::build_patch_entry_green(&name, &new_options);
                                let new_entry_syntax =
                                    rowan::SyntaxNode::<SeriesLang>::new_root_mut(new_entry_green);
                                modifications.push((i, NodeOrToken::Node(new_entry_syntax)));
                            }
                        }
                    }
                }
            }
        }

        // Apply modifications in reverse order to maintain indices
        for (index, new_element) in modifications.into_iter().rev() {
            self.syntax()
                .splice_children(index..index + 1, vec![new_element]);
        }
    }

    /// Reorder patches to match the given order
    pub fn reorder(&mut self, new_order: &[String]) -> bool {
        let mut patch_elements = Vec::new();
        let mut non_patch_positions = Vec::new();

        // Collect patches and remember non-patch positions
        for (i, element) in self.syntax().children_with_tokens().enumerate() {
            match &element {
                NodeOrToken::Node(node) => {
                    if let Some(entry) = SeriesEntry::cast(node.clone()) {
                        if let Some(patch) = entry.as_patch_entry() {
                            if let Some(name) = patch.name() {
                                patch_elements.push((name, element.clone()));
                                continue;
                            }
                        }
                    }
                    non_patch_positions.push(i);
                }
                NodeOrToken::Token(_) => {
                    non_patch_positions.push(i);
                }
            }
        }

        // Verify all patches in new_order exist
        for name in new_order {
            if !patch_elements.iter().any(|(n, _)| n == name) {
                return false;
            }
        }

        // Clear all children
        let total_elements = self.syntax().children_with_tokens().count();
        self.syntax().splice_children(0..total_elements, vec![]);

        // Rebuild with new order
        let mut patch_iter = new_order.iter();
        let mut next_patch_name = patch_iter.next();
        let mut used_patches = std::collections::HashSet::new();

        for original_pos in 0..total_elements {
            if non_patch_positions.contains(&original_pos) {
                // This was a non-patch element, keep it
                // We need to recreate it from the original
                // For now, skip this complex case
                continue;
            } else {
                // This was a patch position, insert next ordered patch
                if let Some(patch_name) = next_patch_name {
                    if let Some((_, element)) = patch_elements.iter().find(|(n, _)| n == patch_name)
                    {
                        self.syntax().splice_children(
                            self.syntax().children_with_tokens().count()
                                ..self.syntax().children_with_tokens().count(),
                            vec![element.clone()],
                        );
                        used_patches.insert(patch_name.clone());
                        next_patch_name = patch_iter.next();
                    }
                }
            }
        }

        true
    }

    /// Helper to build a patch entry green node
    fn build_patch_entry_green(name: &str, options: &[String]) -> rowan::GreenNode {
        let mut builder = GreenNodeBuilder::new();

        builder.start_node(SyntaxKind::SERIES_ENTRY.into());
        builder.start_node(SyntaxKind::PATCH_ENTRY.into());

        // Add patch name
        builder.token(SyntaxKind::PATCH_NAME.into(), name);

        // Add options if present
        if !options.is_empty() {
            builder.token(SyntaxKind::SPACE.into(), " ");
            builder.start_node(SyntaxKind::OPTIONS.into());

            for (i, option) in options.iter().enumerate() {
                if i > 0 {
                    builder.token(SyntaxKind::SPACE.into(), " ");
                }
                builder.start_node(SyntaxKind::OPTION_ITEM.into());
                builder.token(SyntaxKind::OPTION.into(), option);
                builder.finish_node(); // OPTION_ITEM
            }

            builder.finish_node(); // OPTIONS
        }

        // Add newline
        builder.token(SyntaxKind::NEWLINE.into(), "\n");

        builder.finish_node(); // PATCH_ENTRY
        builder.finish_node(); // SERIES_ENTRY

        builder.finish()
    }

    /// Helper to build a comment entry green node
    fn build_comment_entry_green(text: &str) -> rowan::GreenNode {
        let mut builder = GreenNodeBuilder::new();

        builder.start_node(SyntaxKind::SERIES_ENTRY.into());
        builder.start_node(SyntaxKind::COMMENT_LINE.into());

        // Add comment marker
        builder.token(SyntaxKind::HASH.into(), "#");

        if !text.is_empty() {
            // Add space after hash
            builder.token(SyntaxKind::SPACE.into(), " ");
            // Add comment text
            builder.token(SyntaxKind::TEXT.into(), text);
        }

        // Add newline
        builder.token(SyntaxKind::NEWLINE.into(), "\n");

        builder.finish_node(); // COMMENT_LINE
        builder.finish_node(); // SERIES_ENTRY

        builder.finish()
    }
}

#[cfg(test)]
mod tests {
    use crate::edit::series;

    #[test]
    fn test_insert() {
        let text = "patch1.patch\npatch2.patch\n";
        let parsed = series::parse(text);
        let mut series = parsed.quilt_tree_mut();

        series.insert(1, "new.patch", ["-p1"]);

        let patches: Vec<_> = series.patch_entries().collect();
        assert_eq!(patches.len(), 3);
        assert_eq!(patches[0].name(), Some("patch1.patch".to_string()));
        assert_eq!(patches[1].name(), Some("new.patch".to_string()));
        assert_eq!(patches[2].name(), Some("patch2.patch".to_string()));
    }

    #[test]
    fn test_remove_patch() {
        let text = "patch1.patch\npatch2.patch\npatch3.patch\n";
        let parsed = series::parse(text);
        let mut series = parsed.quilt_tree_mut();

        assert!(series.remove("patch2.patch"));

        let patches: Vec<_> = series.patch_entries().collect();
        assert_eq!(patches.len(), 2);
        assert_eq!(patches[0].name(), Some("patch1.patch".to_string()));
        assert_eq!(patches[1].name(), Some("patch3.patch".to_string()));
    }

    #[test]
    fn test_collection_api() {
        let text = "patch1.patch\npatch2.patch\n";
        let parsed = series::parse(text);
        let mut series = parsed.quilt_tree_mut();

        // Test collection methods
        assert_eq!(series.len(), 2);
        assert!(!series.is_empty());
        assert!(series.contains("patch1.patch"));
        assert_eq!(series.position("patch2.patch"), Some(1));

        // Test adding patches
        series.push("patch3.patch", ["-p1", "--reverse"]);
        series.prepend("patch0.patch", std::iter::empty::<&str>());
        series.add_comment("Test comment");

        let patches: Vec<_> = series.patch_entries().collect();
        assert_eq!(patches.len(), 4);
        assert_eq!(patches[0].name(), Some("patch0.patch".to_string()));
        assert_eq!(patches[3].name(), Some("patch3.patch".to_string()));

        // Test clearing
        series.clear();
        assert!(series.is_empty());

        // Comments should remain
        let comments: Vec<_> = series.comment_lines().collect();
        assert_eq!(comments.len(), 1);
    }
}