jj-vine 0.1.0

Stacked pull requests for jj (jujutsu). Supports GitLab and bookmark-based flow.
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
use std::collections::HashMap;

use crate::{bookmark::BranchStack, config::StackFormat, error::Result, gitlab::MergeRequest};

/// Stack description management and formatting for MR descriptions
/// Abstraction for different stack visualization formats
pub trait DescriptionFormatter {
    /// Format the stack visualization
    fn format_stack(&self, stack: &StackContext, current_bookmark: &str) -> String;

    /// Start marker for the stack section
    fn start_marker(&self) -> &'static str;

    /// End marker for the stack section
    fn end_marker(&self) -> &'static str;
}

/// Linear list formatter (like jj-stack)
pub struct LinearListFormatter;

impl DescriptionFormatter for LinearListFormatter {
    fn format_stack(&self, stack: &StackContext, current_bookmark: &str) -> String {
        let mut lines = Vec::new();

        // Header
        lines.push(format!(
            "This MR is part of a stack of {} MRs:",
            stack.bookmarks.len()
        ));
        lines.push("".to_string());

        // Bookmarks (no base branch in the list)
        for (idx, bookmark) in stack.bookmarks.iter().enumerate() {
            let num = idx + 1;
            let display_name = bookmark.title.as_deref().unwrap_or(bookmark.name.as_str());

            if bookmark.name == current_bookmark {
                // Current bookmark - bold with marker
                lines.push(format!("{}. **{} ← this MR**", num, display_name));
            } else if let Some(iid) = bookmark.mr_iid {
                // Other bookmark with MR - use !{iid} format (GitLab auto-links)
                lines.push(format!("{}. {} - !{}", num, display_name, iid));
            } else {
                // Bookmark without MR yet
                lines.push(format!("{}. {}", num, display_name));
            }
        }

        lines.join("\n")
    }

    fn start_marker(&self) -> &'static str {
        "<!-- start jj-vine stack -->"
    }

    fn end_marker(&self) -> &'static str {
        "<!-- end jj-vine stack -->"
    }
}

/// Context for building stack visualizations
pub struct StackContext {
    /// Bookmarks in the stack (ordered from base to tip)
    pub bookmarks: Vec<StackBookmarkInfo>,

    /// Base branch name (e.g., "main", "master")
    pub base_branch: String,
}

/// Information about a bookmark in the stack
pub struct StackBookmarkInfo {
    /// Bookmark name
    pub name: String,

    /// MR title if available
    pub title: Option<String>,

    /// MR IID if it exists
    pub mr_iid: Option<u64>,

    /// MR URL if it exists
    pub mr_url: Option<String>,
}

/// Result of parsing a description
pub struct ParsedDescription {
    /// User-provided content before the stack section
    pub content_before: Option<String>,
    /// User-provided content after the stack section
    pub content_after: Option<String>,
}

/// Manager for parsing and generating MR descriptions
pub struct DescriptionManager {
    formatter: Box<dyn DescriptionFormatter + Send + Sync>,
}

impl DescriptionManager {
    /// Create a new description manager with the given formatter
    pub fn new(formatter: Box<dyn DescriptionFormatter + Send + Sync>) -> Self {
        Self { formatter }
    }

    /// Parse an existing description and extract user content before and after
    /// markers
    pub fn parse_description(&self, description: &str) -> ParsedDescription {
        if description.is_empty() {
            return ParsedDescription {
                content_before: None,
                content_after: None,
            };
        }

        let start_marker = self.formatter.start_marker();
        let end_marker = self.formatter.end_marker();

        // If no stack section markers, entire description is content before
        if !description.contains(start_marker) {
            return ParsedDescription {
                content_before: Some(description.to_string()),
                content_after: None,
            };
        }

        // Find start and end markers
        let start_pos = description.find(start_marker);
        let end_pos = description.find(end_marker);

        match (start_pos, end_pos) {
            (Some(start), Some(end)) if start < end => {
                // Both markers found in correct order
                let before = &description[..start];
                let after = &description[end + end_marker.len()..];

                let content_before = if before.trim().is_empty() {
                    None
                } else {
                    Some(before.trim().to_string())
                };

                let content_after = if after.trim().is_empty() {
                    None
                } else {
                    Some(after.trim().to_string())
                };

                ParsedDescription {
                    content_before,
                    content_after,
                }
            }
            _ => {
                // Malformed markers - treat entire description as content before
                ParsedDescription {
                    content_before: Some(description.to_string()),
                    content_after: None,
                }
            }
        }
    }

    /// Get the start marker for this formatter
    pub fn start_marker(&self) -> &'static str {
        self.formatter.start_marker()
    }

    /// Get the end marker for this formatter
    pub fn end_marker(&self) -> &'static str {
        self.formatter.end_marker()
    }

    /// Generate a new description with stack visualization and user content
    pub fn generate_description(
        &self,
        content_before: Option<&str>,
        content_after: Option<&str>,
        stack_context: &StackContext,
        current_bookmark: &str,
    ) -> String {
        let stack_section = self.formatter.format_stack(stack_context, current_bookmark);
        self.build_description(content_before, content_after, &stack_section)
    }

    /// Build a description with pre-formatted stack content and user content
    pub fn build_description(
        &self,
        content_before: Option<&str>,
        content_after: Option<&str>,
        stack_content: &str,
    ) -> String {
        let start_marker = self.formatter.start_marker();
        let end_marker = self.formatter.end_marker();

        let mut result = String::new();

        // Add content before markers
        if let Some(before) = content_before {
            result.push_str(before);
            result.push_str("\n\n");
        }

        // Add stack section with markers
        result.push_str(start_marker);
        result.push('\n');
        result.push_str(stack_content);
        result.push('\n');
        result.push_str(end_marker);

        // Add content after markers
        if let Some(after) = content_after {
            result.push_str("\n\n");
            result.push_str(after);
        }

        result
    }
}

/// Generate description for a bookmark that may be in multiple stacks
pub fn generate_multi_stack_description(
    bookmark: &str,
    stacks: &[&BranchStack],
    existing_mrs: &HashMap<String, MergeRequest>,
    format: &StackFormat,
    base_branch: &str,
) -> Result<String> {
    if stacks.is_empty() {
        return Ok(String::new());
    }

    // Create formatter based on config
    let formatter: Box<dyn DescriptionFormatter> = match format {
        StackFormat::Linear => Box::new(LinearListFormatter),
    };

    if stacks.len() == 1 {
        // Single stack - use existing format
        let stack = stacks[0];
        let stack_info: Vec<StackBookmarkInfo> = stack
            .bookmarks
            .iter()
            .map(|bm| StackBookmarkInfo {
                name: bm.clone(),
                title: existing_mrs.get(bm).map(|mr| mr.title.clone()),
                mr_iid: existing_mrs.get(bm).map(|mr| mr.iid),
                mr_url: existing_mrs.get(bm).map(|mr| mr.web_url.clone()),
            })
            .collect();

        let context = StackContext {
            bookmarks: stack_info,
            base_branch: base_branch.to_string(),
        };

        return Ok(formatter.format_stack(&context, bookmark));
    }

    // Multiple stacks - format each separately
    let mut lines = Vec::new();
    lines.push(format!("This MR is part of {} stacks:", stacks.len()));
    lines.push("".to_string());

    for (idx, stack) in stacks.iter().enumerate() {
        lines.push(format!(
            "Stack {} ({} MRs):",
            idx + 1,
            stack.bookmarks.len()
        ));

        // Build StackContext for this stack
        let stack_info: Vec<StackBookmarkInfo> = stack
            .bookmarks
            .iter()
            .map(|bm| StackBookmarkInfo {
                name: bm.clone(),
                title: existing_mrs.get(bm).map(|mr| mr.title.clone()),
                mr_iid: existing_mrs.get(bm).map(|mr| mr.iid),
                mr_url: existing_mrs.get(bm).map(|mr| mr.web_url.clone()),
            })
            .collect();

        let context = StackContext {
            bookmarks: stack_info,
            base_branch: base_branch.to_string(),
        };

        let stack_desc = formatter.format_stack(&context, bookmark);

        for line in stack_desc.lines().skip(2) {
            lines.push(line.to_string());
        }

        if idx < stacks.len() - 1 {
            lines.push("".to_string());
        }
    }

    Ok(lines.join("\n"))
}

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

    #[test]
    fn test_parse_empty_description() {
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));
        let parsed = manager.parse_description("");
        assert!(parsed.content_before.is_none());
        assert!(parsed.content_after.is_none());
    }

    #[test]
    fn test_parse_user_content_only() {
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));
        let parsed = manager.parse_description("User's description here");
        assert_eq!(
            parsed.content_before,
            Some("User's description here".to_string())
        );
        assert!(parsed.content_after.is_none());
    }

    #[test]
    fn test_parse_preserves_user_content_after_markers() {
        let desc =
            "<!-- start jj-vine stack -->\nStack info\n<!-- end jj-vine stack -->\n\nUser content";
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));
        let parsed = manager.parse_description(desc);
        assert!(parsed.content_before.is_none());
        assert_eq!(parsed.content_after, Some("User content".to_string()));
    }

    #[test]
    fn test_generate_stack_only() {
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));

        let stack = StackContext {
            bookmarks: vec![
                StackBookmarkInfo {
                    name: "bookmark-a".to_string(),
                    title: None,
                    mr_iid: Some(100),
                    mr_url: Some("https://gitlab.com/project/-/merge_requests/100".to_string()),
                },
                StackBookmarkInfo {
                    name: "bookmark-b".to_string(),
                    title: None,
                    mr_iid: Some(101),
                    mr_url: Some("https://gitlab.com/project/-/merge_requests/101".to_string()),
                },
            ],
            base_branch: "main".to_string(),
        };

        let desc = manager.generate_description(None, None, &stack, "bookmark-b");

        assert!(desc.contains("<!-- start jj-vine stack -->"));
        assert!(desc.contains("<!-- end jj-vine stack -->"));
        assert!(desc.contains("bookmark-b ← this MR"));
    }

    #[test]
    fn test_generate_preserves_user_content() {
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));

        let stack = StackContext {
            bookmarks: vec![StackBookmarkInfo {
                name: "bookmark-a".to_string(),
                title: None,
                mr_iid: None,
                mr_url: None,
            }],
            base_branch: "main".to_string(),
        };

        let desc = manager.generate_description(None, Some("User stuff"), &stack, "bookmark-a");
        assert!(desc.ends_with("User stuff"));
    }

    #[test]
    fn test_linear_formatter_current_bookmark_bold() {
        let formatter = LinearListFormatter;

        let stack = StackContext {
            bookmarks: vec![
                StackBookmarkInfo {
                    name: "bookmark-a".to_string(),
                    title: None,
                    mr_iid: Some(100),
                    mr_url: Some("https://gitlab.com/mrs/100".to_string()),
                },
                StackBookmarkInfo {
                    name: "bookmark-b".to_string(),
                    title: None,
                    mr_iid: None,
                    mr_url: None,
                },
            ],
            base_branch: "main".to_string(),
        };

        let output = formatter.format_stack(&stack, "bookmark-b");
        assert!(output.contains("**bookmark-b ← this MR**"));
        assert!(output.contains("bookmark-a - !100"));
    }

    #[test]
    fn test_linear_formatter_proper_gitlab_format() {
        let formatter = LinearListFormatter;

        let stack = StackContext {
            bookmarks: vec![
                StackBookmarkInfo {
                    name: "feature-1".to_string(),
                    title: None,
                    mr_iid: Some(18),
                    mr_url: Some(
                        "https://gitlab.internal.valence.nl/abrenneke/testing/-/merge_requests/18"
                            .to_string(),
                    ),
                },
                StackBookmarkInfo {
                    name: "feature-2".to_string(),
                    title: None,
                    mr_iid: None,
                    mr_url: None,
                },
                StackBookmarkInfo {
                    name: "alt-feature".to_string(),
                    title: None,
                    mr_iid: Some(19),
                    mr_url: Some(
                        "https://gitlab.internal.valence.nl/abrenneke/testing/-/merge_requests/19"
                            .to_string(),
                    ),
                },
            ],
            base_branch: "main".to_string(),
        };

        let output = formatter.format_stack(&stack, "feature-2");

        // Should NOT include the base branch in the list
        assert!(!output.contains("1. `main`"));

        // Should use "MRs" not "bookmarks" in description
        assert!(output.contains("This MR is part of a stack of 3 MRs"));

        // Should use !{iid} format, not full markdown links
        assert!(output.contains("1. feature-1 - !18"));
        assert!(!output.contains("[feature-1](https://gitlab"));

        // Current MR should be bold with marker
        assert!(output.contains("2. **feature-2 ← this MR**"));

        // Other MR with link should also use !{iid} format
        assert!(output.contains("3. alt-feature - !19"));
        assert!(!output.contains("[alt-feature](https://gitlab"));
    }

    #[test]
    fn test_parse_no_end_marker_malformed() {
        let desc = "<!-- start jj-vine stack -->\nStack info without end";
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));
        let parsed = manager.parse_description(desc);
        assert_eq!(parsed.content_before, Some(desc.to_string()));
        assert!(parsed.content_after.is_none());
    }

    #[test]
    fn test_round_trip_preserves_user_content() {
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));
        let original =
            "<!-- start jj-vine stack -->\nOld stack\n<!-- end jj-vine stack -->\n\nMy notes";
        let parsed = manager.parse_description(original);

        let stack = StackContext {
            bookmarks: vec![StackBookmarkInfo {
                name: "feature".to_string(),
                title: None,
                mr_iid: Some(100),
                mr_url: Some("url".to_string()),
            }],
            base_branch: "main".to_string(),
        };

        let new_desc = manager.generate_description(
            parsed.content_before.as_deref(),
            parsed.content_after.as_deref(),
            &stack,
            "feature",
        );
        assert!(new_desc.contains("My notes"));
    }

    #[test]
    fn test_generate_no_trailing_whitespace_when_no_user_content() {
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));
        let stack = StackContext {
            bookmarks: vec![StackBookmarkInfo {
                name: "f".to_string(),
                title: None,
                mr_iid: Some(1),
                mr_url: Some("u".to_string()),
            }],
            base_branch: "main".to_string(),
        };

        let desc = manager.generate_description(None, None, &stack, "f");
        assert!(desc.ends_with("<!-- end jj-vine stack -->"));
    }

    #[test]
    fn test_parse_content_before_and_after_markers() {
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));
        let desc = "Content before\n\n<!-- start jj-vine stack -->\nStack info\n<!-- end jj-vine stack -->\n\nContent after";
        let parsed = manager.parse_description(desc);

        assert_eq!(parsed.content_before, Some("Content before".to_string()));
        assert_eq!(parsed.content_after, Some("Content after".to_string()));
    }

    #[test]
    fn test_generate_with_content_before_and_after() {
        let manager = DescriptionManager::new(Box::new(LinearListFormatter));
        let stack = StackContext {
            bookmarks: vec![StackBookmarkInfo {
                name: "feature".to_string(),
                title: None,
                mr_iid: Some(100),
                mr_url: Some("url".to_string()),
            }],
            base_branch: "main".to_string(),
        };

        let desc = manager.generate_description(
            Some("Before content"),
            Some("After content"),
            &stack,
            "feature",
        );

        assert!(desc.starts_with("Before content"));
        assert!(desc.contains("<!-- start jj-vine stack -->"));
        assert!(desc.contains("<!-- end jj-vine stack -->"));
        assert!(desc.ends_with("After content"));
    }

    #[test]
    fn test_linear_formatter_shows_title_instead_of_bookmark_name() {
        let formatter = LinearListFormatter;

        let stack = StackContext {
            bookmarks: vec![
                StackBookmarkInfo {
                    name: "push-rzmzwomlxplr".to_string(),
                    title: Some("Add user authentication".to_string()),
                    mr_iid: Some(18),
                    mr_url: Some("https://gitlab.com/project/-/merge_requests/18".to_string()),
                },
                StackBookmarkInfo {
                    name: "push-xyzabc123".to_string(),
                    title: Some("Implement login form".to_string()),
                    mr_iid: Some(19),
                    mr_url: Some("https://gitlab.com/project/-/merge_requests/19".to_string()),
                },
                StackBookmarkInfo {
                    name: "feature-final".to_string(),
                    title: None,
                    mr_iid: None,
                    mr_url: None,
                },
            ],
            base_branch: "main".to_string(),
        };

        let output = formatter.format_stack(&stack, "push-xyzabc123");

        // Should show MR title, not bookmark name
        assert!(output.contains("Add user authentication - !18"));
        assert!(!output.contains("push-rzmzwomlxplr"));

        // Current MR should show title
        assert!(output.contains("**Implement login form ← this MR**"));
        assert!(!output.contains("push-xyzabc123"));

        // Bookmark without title should fall back to bookmark name
        assert!(output.contains("feature-final"));
    }
}