stax 0.96.0

Fast stacked Git branches and PRs
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
#![allow(clippy::result_large_err)]

use super::operation::report_operation;
use super::{
    OperationError, OperationErrorDetails, OperationErrorKind, OperationEvent, OperationOutcome,
    OperationProgress, OperationReceipt, OperationReporter, OperationRequest, OperationResult,
    OperationSideEffects, OperationStage, RepositorySession, TransactionSummary,
};
use crate::application::repository::MutationTargets;
use crate::engine::{BranchMetadata, Stack};
use crate::git::{GitRepo, RebaseResult};
use crate::ops::receipt::OpKind;
use crate::ops::tx::Transaction;
use std::collections::HashSet;

impl RepositorySession {
    /// Move a tracked branch and its complete descendant subtree onto a new parent.
    pub fn move_subtree(
        &self,
        source: &str,
        new_parent: &str,
        auto_stash: bool,
        reporter: &mut dyn OperationReporter,
    ) -> OperationResult {
        let request = OperationRequest::MoveSubtree {
            source: source.to_owned(),
            new_parent: new_parent.to_owned(),
            auto_stash,
        };
        report_operation(request.clone(), reporter, |reporter| {
            self.move_subtree_unframed(&request, source, new_parent, auto_stash, reporter)
        })
    }

    pub(super) fn move_subtree_unframed(
        &self,
        request: &OperationRequest,
        source: &str,
        new_parent: &str,
        auto_stash: bool,
        reporter: &mut dyn OperationReporter,
    ) -> OperationResult {
        let repo = self.open_repo().map_err(|error| {
            source_error(
                request,
                OperationErrorKind::RepositoryUnavailable,
                OperationErrorDetails::None,
                "Could not open the repository",
                "Check the repository path and retry",
                error,
                OperationSideEffects::None,
            )
        })?;
        let stack = Stack::load(&repo).map_err(|error| {
            source_error(
                request,
                OperationErrorKind::LocalGit,
                OperationErrorDetails::None,
                "Could not load the stack",
                "Resolve the stack metadata error and retry",
                error,
                OperationSideEffects::None,
            )
        })?;
        let mut moved = vec![source.trim().to_string()];
        moved.extend(stack.descendants(source.trim()));
        let mut targets = moved.clone();
        targets.push(new_parent.trim().to_string());
        self.with_mutation(request, MutationTargets::branches(targets), || {
            move_subtree_inner(
                self,
                request,
                &repo,
                stack,
                source.trim(),
                new_parent.trim(),
                moved,
                auto_stash,
                reporter,
            )
        })
    }
}

#[allow(clippy::too_many_arguments)]
fn move_subtree_inner(
    session: &RepositorySession,
    request: &OperationRequest,
    repo: &GitRepo,
    stack: Stack,
    source: &str,
    new_parent: &str,
    moved: Vec<String>,
    auto_stash: bool,
    reporter: &mut dyn OperationReporter,
) -> OperationResult {
    if source.is_empty() || new_parent.is_empty() {
        return Err(simple_error(
            request,
            OperationErrorKind::InvalidInput,
            "Source and new parent branch names are required",
            "Choose existing local branches and retry",
            "move subtree input was empty",
        ));
    }
    if source == stack.trunk {
        return Err(simple_error(
            request,
            OperationErrorKind::PreconditionFailed,
            "Cannot move the trunk branch",
            "Choose a stacked branch and retry",
            "move source is trunk",
        ));
    }
    repo.branch_commit(source).map_err(|error| {
        source_error(
            request,
            OperationErrorKind::InvalidInput,
            branch_details(source),
            format!("Branch '{source}' does not exist locally"),
            "Choose an existing source branch and retry",
            error,
            OperationSideEffects::None,
        )
    })?;
    repo.branch_commit(new_parent).map_err(|error| {
        source_error(
            request,
            OperationErrorKind::InvalidInput,
            branch_details(new_parent),
            format!("Branch '{new_parent}' does not exist locally"),
            "Choose an existing parent branch and retry",
            error,
            OperationSideEffects::None,
        )
    })?;
    let old_metadata = BranchMetadata::read(repo.inner(), source)
        .map_err(|error| {
            source_error(
                request,
                OperationErrorKind::LocalGit,
                branch_details(source),
                format!("Could not read metadata for '{source}'"),
                "Resolve the stax metadata error and retry",
                error,
                OperationSideEffects::None,
            )
        })?
        .ok_or_else(|| {
            simple_error(
                request,
                OperationErrorKind::PreconditionFailed,
                format!("Branch '{source}' is not tracked by stax"),
                "Track the branch before moving it",
                "move source has no branch metadata",
            )
        })?;
    if source == new_parent {
        return Err(simple_error(
            request,
            OperationErrorKind::InvalidInput,
            "Cannot move a branch onto itself",
            "Choose a different parent and retry",
            "move source equals new parent",
        ));
    }
    if moved.iter().skip(1).any(|branch| branch == new_parent) {
        return Err(simple_error(
            request,
            OperationErrorKind::PreconditionFailed,
            format!(
                "Cannot move '{source}' onto its descendant '{new_parent}': this would create a circular dependency"
            ),
            "Choose a branch outside the moved subtree",
            "move would create a circular dependency",
        ));
    }
    if old_metadata.parent_branch_name == new_parent {
        return Ok(move_receipt(
            request,
            source,
            new_parent,
            moved,
            None,
            OperationSideEffects::None,
        ));
    }

    let original_checkout = repo.current_branch().map_err(|error| {
        source_error(
            request,
            OperationErrorKind::LocalGit,
            OperationErrorDetails::None,
            "Could not determine the current branch",
            "Resolve the Git HEAD error and retry",
            error,
            OperationSideEffects::None,
        )
    })?;
    let metadata = load_moved_metadata(request, repo, &moved)?;
    preflight_dirty_worktrees(request, repo, &moved, auto_stash)?;

    let mut transaction = Transaction::begin(OpKind::MoveSubtree, repo, true).map_err(|error| {
        source_error(
            request,
            OperationErrorKind::LocalGit,
            OperationErrorDetails::None,
            "Could not start the move transaction",
            "Resolve the receipt error and retry",
            error,
            OperationSideEffects::None,
        )
    })?;
    transaction.plan_branches(repo, &moved).map_err(|error| {
        source_error(
            request,
            OperationErrorKind::LocalGit,
            OperationErrorDetails::None,
            "Could not prepare branch recovery for the move",
            "Resolve the receipt error and retry",
            error,
            OperationSideEffects::None,
        )
    })?;
    for branch in &moved {
        transaction
            .plan_metadata_ref(repo, branch)
            .map_err(|error| {
                source_error(
                    request,
                    OperationErrorKind::LocalGit,
                    OperationErrorDetails::None,
                    "Could not prepare metadata recovery for the move",
                    "Resolve the receipt error and retry",
                    error,
                    OperationSideEffects::None,
                )
            })?;
    }
    transaction.set_auto_stash_pop(auto_stash);
    transaction.snapshot().map_err(|error| {
        source_error(
            request,
            OperationErrorKind::LocalGit,
            OperationErrorDetails::None,
            "Could not save the move recovery snapshot",
            "Resolve the receipt error and retry",
            error,
            OperationSideEffects::None,
        )
    })?;
    let mut transaction = Some(transaction);

    reporter.report(OperationEvent::Progress(OperationProgress {
        stage: OperationStage::MovingSubtree,
        completed: 0,
        total: Some(moved.len()),
        branch: Some(source.to_string()),
        message: format!("Moving {source} onto {new_parent}"),
    }));

    for (index, branch) in moved.iter().enumerate() {
        let existing = metadata
            .iter()
            .find(|(name, _)| name == branch)
            .and_then(|(_, metadata)| metadata.as_ref())
            .expect("moved branches were validated as tracked");
        let parent = if index == 0 {
            new_parent
        } else {
            existing.parent_branch_name.as_str()
        };
        let parent_revision = repo.branch_commit(parent).map_err(|error| {
            finish_move_error(
                request,
                &mut transaction,
                repo,
                source,
                new_parent,
                &moved,
                &original_checkout,
                OperationErrorKind::LocalGit,
                format!("Could not resolve parent '{parent}'"),
                "Resolve the Git ref error and retry",
                error,
                "resolve-parent",
                OperationSideEffects::RepositoryChanged,
            )
        })?;
        let merge_base = repo
            .merge_base(parent, branch)
            .unwrap_or_else(|_| parent_revision.clone());
        let upstream = resolve_rebase_upstream(
            repo,
            &existing.parent_branch_name,
            &existing.parent_branch_revision,
            branch,
            &merge_base,
        )
        .map_err(|error| {
            finish_move_error(
                request,
                &mut transaction,
                repo,
                source,
                new_parent,
                &moved,
                &original_checkout,
                OperationErrorKind::LocalGit,
                format!("Could not prepare rebase for '{branch}'"),
                "Resolve the Git history error and retry",
                error,
                "prepare-rebase",
                OperationSideEffects::RepositoryChanged,
            )
        })?;
        reporter.report(OperationEvent::Progress(OperationProgress {
            stage: OperationStage::Restacking,
            completed: index,
            total: Some(moved.len()),
            branch: Some(branch.clone()),
            message: format!("Restacking {branch} onto {parent}"),
        }));
        let rebase = repo
            .rebase_branch_onto_with_provenance(branch, parent, &upstream, auto_stash)
            .map_err(|error| {
                finish_move_error(
                    request,
                    &mut transaction,
                    repo,
                    source,
                    new_parent,
                    &moved,
                    &original_checkout,
                    OperationErrorKind::LocalGit,
                    format!("Could not rebase '{branch}' onto '{parent}'"),
                    "Resolve the Git rebase error and retry",
                    error,
                    "rebase",
                    OperationSideEffects::RepositoryChanged,
                )
            })?;
        if rebase == RebaseResult::Conflict {
            let worktree = repo
                .branch_rebase_target_workdir(branch)
                .unwrap_or_else(|_| session.repository_root().to_path_buf());
            return Err(finish_move_error_with_details(
                request,
                &mut transaction,
                repo,
                source,
                new_parent,
                &moved,
                &original_checkout,
                OperationErrorKind::RebaseConflict,
                OperationErrorDetails::Rebase {
                    branch: Some(branch.clone()),
                    worktree,
                },
                format!("Rebase conflict while moving '{branch}'"),
                "Resolve conflicts, then run `st continue`, `st abort`, or `stax undo`",
                anyhow::anyhow!("rebase conflict"),
                "rebase",
                OperationSideEffects::RepositoryChanged,
            ));
        }
        let mut updated = existing.clone();
        updated.parent_branch_name = parent.to_string();
        updated.parent_branch_revision = repo.branch_commit(parent).unwrap_or(parent_revision);
        if let Err(error) = updated.write(repo.inner(), branch) {
            return Err(finish_move_error(
                request,
                &mut transaction,
                repo,
                source,
                new_parent,
                &moved,
                &original_checkout,
                OperationErrorKind::LocalGit,
                format!("Could not update metadata for '{branch}'"),
                "Run `stax undo`, resolve the metadata error, and retry",
                error,
                "write-metadata",
                OperationSideEffects::RepositoryChanged,
            ));
        }
        transaction
            .as_mut()
            .expect("move transaction should remain active")
            .push_completed_branch(branch);
    }

    if !matches!(repo.current_branch().as_deref(), Ok(branch) if branch == original_checkout)
        && let Err(error) = repo.checkout(&original_checkout)
    {
        return Err(finish_move_error(
            request,
            &mut transaction,
            repo,
            source,
            new_parent,
            &moved,
            &original_checkout,
            OperationErrorKind::LocalGit,
            "The subtree moved, but the original checkout could not be restored",
            "Check out the original branch manually and inspect the repository",
            error,
            "restore-checkout",
            OperationSideEffects::RepositoryChanged,
        ));
    }
    if let Err(error) = record_after_states(
        transaction
            .as_mut()
            .expect("move transaction should remain active"),
        repo,
        &moved,
    ) {
        return Err(finish_move_error(
            request,
            &mut transaction,
            repo,
            source,
            new_parent,
            &moved,
            &original_checkout,
            OperationErrorKind::LocalGit,
            "The subtree moved, but its recovery state could not be recorded",
            "Inspect the repository and retry if needed",
            error,
            "record-after",
            OperationSideEffects::RepositoryChanged,
        ));
    }
    let mut transaction = transaction
        .take()
        .expect("move transaction should remain active");
    transaction.set_head_branch_after(&original_checkout);
    let finalized = transaction.finish_ok_preserving_receipt();
    let receipt = move_receipt(
        request,
        source,
        new_parent,
        moved,
        Some(TransactionSummary::from(&finalized.receipt)),
        OperationSideEffects::RepositoryChanged,
    );
    if let Some(error) = finalized.persistence_error {
        return Err(OperationError::from_source(
            request.clone(),
            OperationErrorKind::LocalGit,
            OperationErrorDetails::None,
            "The subtree moved, but its receipt could not be saved",
            "Inspect the repository and retry if needed",
            &error,
            Some(receipt),
            OperationSideEffects::RepositoryChanged,
        ));
    }
    Ok(receipt)
}

fn load_moved_metadata(
    request: &OperationRequest,
    repo: &GitRepo,
    moved: &[String],
) -> Result<Vec<(String, Option<BranchMetadata>)>, OperationError> {
    let mut result = Vec::with_capacity(moved.len());
    for branch in moved {
        let metadata = BranchMetadata::read(repo.inner(), branch).map_err(|error| {
            source_error(
                request,
                OperationErrorKind::LocalGit,
                branch_details(branch),
                format!("Could not read metadata for '{branch}'"),
                "Resolve the stax metadata error and retry",
                error,
                OperationSideEffects::None,
            )
        })?;
        if metadata.is_none() {
            return Err(simple_error(
                request,
                OperationErrorKind::PreconditionFailed,
                format!("Branch '{branch}' is not tracked by stax"),
                "Track every branch in the subtree before moving it",
                "moved subtree contains a branch without metadata",
            ));
        }
        result.push((branch.clone(), metadata));
    }
    Ok(result)
}

fn preflight_dirty_worktrees(
    request: &OperationRequest,
    repo: &GitRepo,
    moved: &[String],
    auto_stash: bool,
) -> Result<(), OperationError> {
    if auto_stash {
        return Ok(());
    }
    let mut seen = HashSet::new();
    for branch in moved {
        let worktree = repo.branch_rebase_target_workdir(branch).map_err(|error| {
            source_error(
                request,
                OperationErrorKind::LocalGit,
                branch_details(branch),
                format!("Could not locate the rebase worktree for '{branch}'"),
                "Resolve the Git worktree error and retry",
                error,
                OperationSideEffects::None,
            )
        })?;
        if seen.insert(worktree.clone()) && repo.is_dirty_at(&worktree).unwrap_or(false) {
            return Err(OperationError {
                request: request.clone(),
                kind: OperationErrorKind::DirtyWorktree,
                details: OperationErrorDetails::Rebase {
                    branch: Some(branch.clone()),
                    worktree,
                },
                primary: "An affected worktree has uncommitted changes".into(),
                action: "Retry with automatic stashing after reviewing the worktree".into(),
                diagnostic_chain: "dirty worktree preflight rejected subtree move".into(),
                receipt: None,
                side_effects: OperationSideEffects::None,
            });
        }
    }
    Ok(())
}

fn resolve_rebase_upstream(
    repo: &GitRepo,
    old_parent: &str,
    old_revision: &str,
    branch: &str,
    merge_base: &str,
) -> anyhow::Result<String> {
    if let Ok(tip) = repo.branch_commit(old_parent)
        && repo.is_ancestor(&tip, branch)?
    {
        return Ok(tip);
    }
    if !old_revision.is_empty() && repo.is_ancestor(old_revision, branch)? {
        return Ok(old_revision.to_string());
    }
    Ok(merge_base.to_string())
}

fn record_after_states(
    transaction: &mut Transaction,
    repo: &GitRepo,
    moved: &[String],
) -> anyhow::Result<()> {
    for branch in moved {
        transaction.record_optional_after(repo, branch)?;
        transaction.record_metadata_ref_after(repo, branch)?;
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn finish_move_error(
    request: &OperationRequest,
    transaction: &mut Option<Transaction>,
    repo: &GitRepo,
    source: &str,
    new_parent: &str,
    moved: &[String],
    original_checkout: &str,
    kind: OperationErrorKind,
    primary: impl Into<String>,
    action: impl Into<String>,
    error: anyhow::Error,
    step: &'static str,
    side_effects: OperationSideEffects,
) -> OperationError {
    finish_move_error_with_details(
        request,
        transaction,
        repo,
        source,
        new_parent,
        moved,
        original_checkout,
        kind,
        branch_details(source),
        primary,
        action,
        error,
        step,
        side_effects,
    )
}

#[allow(clippy::too_many_arguments)]
fn finish_move_error_with_details(
    request: &OperationRequest,
    transaction: &mut Option<Transaction>,
    repo: &GitRepo,
    source: &str,
    new_parent: &str,
    moved: &[String],
    original_checkout: &str,
    kind: OperationErrorKind,
    details: OperationErrorDetails,
    primary: impl Into<String>,
    action: impl Into<String>,
    error: anyhow::Error,
    step: &'static str,
    side_effects: OperationSideEffects,
) -> OperationError {
    let primary = primary.into();
    let mut diagnostic = format!("{error:#}");
    let mut transaction = transaction
        .take()
        .expect("move transaction should remain active during failure");
    if let Err(error) = record_after_states(&mut transaction, repo, moved) {
        diagnostic.push_str("\nfailed to record final move state: ");
        diagnostic.push_str(&format!("{error:#}"));
    }
    transaction.set_head_branch_after(original_checkout);
    let finalized = transaction.finish_err_preserving_receipt(&primary, Some(step), Some(source));
    if let Some(error) = finalized.persistence_error {
        diagnostic.push_str("\nreceipt persistence failure: ");
        diagnostic.push_str(&format!("{error:#}"));
    }
    let receipt = move_receipt(
        request,
        source,
        new_parent,
        moved.to_vec(),
        Some(TransactionSummary::from(&finalized.receipt)),
        side_effects,
    );
    OperationError {
        request: request.clone(),
        kind,
        details,
        primary,
        action: action.into(),
        diagnostic_chain: diagnostic,
        receipt: Some(receipt),
        side_effects,
    }
}

fn move_receipt(
    request: &OperationRequest,
    source: &str,
    new_parent: &str,
    moved: Vec<String>,
    transaction: Option<TransactionSummary>,
    side_effects: OperationSideEffects,
) -> OperationReceipt {
    OperationReceipt {
        request: request.clone(),
        summary: if side_effects == OperationSideEffects::None {
            format!("{source} is already parented onto {new_parent}")
        } else {
            format!("Moved {source} onto {new_parent}")
        },
        affected_branches: moved.clone(),
        outcome: OperationOutcome::SubtreeMoved {
            source: source.to_string(),
            new_parent: new_parent.to_string(),
            moved_branches: moved,
        },
        transaction,
        warnings: Vec::new(),
        side_effects,
    }
}

fn branch_details(branch: &str) -> OperationErrorDetails {
    OperationErrorDetails::Branch {
        branch: branch.to_string(),
    }
}

fn simple_error(
    request: &OperationRequest,
    kind: OperationErrorKind,
    primary: impl Into<String>,
    action: impl Into<String>,
    diagnostic: impl Into<String>,
) -> OperationError {
    OperationError {
        request: request.clone(),
        kind,
        details: OperationErrorDetails::None,
        primary: primary.into(),
        action: action.into(),
        diagnostic_chain: diagnostic.into(),
        receipt: None,
        side_effects: OperationSideEffects::None,
    }
}

fn source_error(
    request: &OperationRequest,
    kind: OperationErrorKind,
    details: OperationErrorDetails,
    primary: impl Into<String>,
    action: impl Into<String>,
    source: anyhow::Error,
    side_effects: OperationSideEffects,
) -> OperationError {
    OperationError::from_source(
        request.clone(),
        kind,
        details,
        primary,
        action,
        &source,
        None,
        side_effects,
    )
}