Debian Codegraph @

cli/src/commands/arrange.rs

raw
1 // Copyright 2026 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::collections::HashMap;
16 use std::collections::HashSet;
17 use std::io;
18
19 use bstr::ByteSlice as _;
20 use crossterm::ExecutableCommand as _;
21 use crossterm::event::Event;
22 use crossterm::event::KeyCode;
23 use crossterm::event::KeyEvent;
24 use crossterm::event::KeyModifiers;
25 use crossterm::event::{self};
26 use crossterm::terminal::EnterAlternateScreen;
27 use crossterm::terminal::LeaveAlternateScreen;
28 use crossterm::terminal::disable_raw_mode;
29 use crossterm::terminal::enable_raw_mode;
30 use futures::StreamExt as _;
31 use futures::TryStreamExt as _;
32 use futures::future::try_join_all;
33 use indexmap::IndexSet;
34 use itertools::Itertools as _;
35 use jj_lib::backend::BackendResult;
36 use jj_lib::backend::CommitId;
37 use jj_lib::commit::Commit;
38 use jj_lib::dag_walk;
39 use jj_lib::repo::MutableRepo;
40 use jj_lib::repo::Repo as _;
41 use jj_lib::revset::RevsetStreamExt as _;
42 use jj_lib::rewrite::CommitRewriter;
43 use ratatui::Terminal;
44 use ratatui::buffer::Buffer;
45 use ratatui::layout::Constraint;
46 use ratatui::layout::Direction;
47 use ratatui::layout::Layout;
48 use ratatui::layout::Offset;
49 use ratatui::layout::Rect;
50 use ratatui::prelude::CrosstermBackend;
51 use ratatui::style::Color;
52 use ratatui::style::Style;
53 use ratatui::text::Line;
54 use ratatui::text::Span;
55 use ratatui::text::Text;
56 use ratatui::widgets::Widget as _;
57 use renderdag::Ancestor;
58 use renderdag::GraphRowRenderer;
59 use renderdag::Renderer as _;
60 use tracing::instrument;
61
62 use crate::cli_util::CommandHelper;
63 use crate::cli_util::RevisionArg;
64 use crate::cli_util::short_commit_hash;
65 use crate::command_error::CommandError;
66 use crate::command_error::internal_error;
67 use crate::command_error::user_error;
68 use crate::complete;
69 use crate::formatter::FormatterExt as _;
70 use crate::templater::TemplateRenderer;
71 use crate::ui::Ui;
72
73 /// Interactively arrange the commit graph.
74 #[derive(clap::Args, Clone, Debug)]
75 pub(crate) struct ArrangeArgs {
76 /// The revisions to arrange [aliases: -r]
77 ///
78 /// If no revisions are specified, this defaults to the `revsets.arrange`
79 /// setting.
80 #[arg(value_name = "REVSETS")]
81 #[arg(add = clap_complete::ArgValueCompleter::new(complete::revset_expression_mutable))]
82 revisions_pos: Vec<RevisionArg>,
83
84 #[arg(short = 'r', hide = true, value_name = "REVSETS")]
85 #[arg(add = clap_complete::ArgValueCompleter::new(complete::revset_expression_mutable))]
86 revisions_opt: Vec<RevisionArg>,
87 }
88
89 #[instrument(skip_all)]
90 pub(crate) async fn cmd_arrange(
91 ui: &mut Ui,
92 command: &CommandHelper,
93 args: &ArrangeArgs,
94 ) -> Result<(), CommandError> {
95 let mut workspace_command = command.workspace_helper(ui).await?;
96 let repo = workspace_command.repo().clone();
97 let target_expression = if args.revisions_pos.is_empty() && args.revisions_opt.is_empty() {
98 let revs = workspace_command.settings().get_string("revsets.arrange")?;
99 workspace_command.parse_revset(ui, &RevisionArg::from(revs))?
100 } else {
101 workspace_command
102 .parse_union_revsets(ui, &[&*args.revisions_pos, &*args.revisions_opt].concat())?
103 }
104 .resolve()?;
105 workspace_command
106 .check_rewritable_expr(&target_expression)
107 .await?;
108
109 let gaps_revset = target_expression
110 .connected()
111 .minus(&target_expression)
112 .evaluate(repo.as_ref())?;
113 if let Some(commit_id) = gaps_revset.stream().next().await {
114 return Err(
115 user_error("Cannot arrange revset with gaps in.").hinted(format!(
116 "Revision {} would need to be in the set.",
117 short_commit_hash(&commit_id?)
118 )),
119 );
120 }
121
122 let children_revset = target_expression
123 .children()
124 .minus(&target_expression)
125 .evaluate(repo.as_ref())?;
126 let external_children: Vec<_> = children_revset
127 .stream()
128 .commits(repo.store())
129 .try_collect()
130 .await?;
131
132 let revset = target_expression.evaluate(repo.as_ref())?;
133 let commits: Vec<Commit> = revset.stream().commits(repo.store()).try_collect().await?;
134 if commits.is_empty() {
135 writeln!(ui.status(), "No revisions to arrange.")?;
136 return Ok(());
137 }
138
139 // Set up the terminal
140 io::stdout().execute(EnterAlternateScreen)?;
141 enable_raw_mode()?;
142 let mut terminal = Terminal::new(CrosstermBackend::new(io::stdout()))?;
143 terminal.clear()?;
144
145 let mut state = State::new(commits, external_children).await?;
146 state.update_commit_order();
147
148 let template_string = workspace_command
149 .settings()
150 .get_string("templates.arrange")?;
151 let template = workspace_command
152 .parse_commit_template(ui, &template_string)?
153 .labeled(["commit"]);
154
155 let result = run_tui(ui, &mut terminal, template, state);
156
157 // Restore the terminal
158 disable_raw_mode()?;
159 io::stdout().execute(LeaveAlternateScreen)?;
160
161 if let Some(new_state) = result? {
162 let mut tx = workspace_command.start_transaction();
163 let rewrites = new_state.to_rewrite_plan();
164 rewrites.execute(tx.repo_mut()).await?;
165 tx.finish(ui, "arrange revisions").await?;
166 Ok(())
167 } else {
168 Err(user_error("Canceled by user"))
169 }
170 }
171
172 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
173 enum UiAction {
174 Abandon,
175 Keep,
176 }
177
178 /// The state of a single commit in the UI
179 #[derive(Clone, Debug, PartialEq, Eq)]
180 struct CommitState {
181 commit: Commit,
182 action: UiAction,
183 parents: Vec<CommitId>,
184 }
185
186 #[derive(Clone, Debug, PartialEq, Eq)]
187 struct State {
188 /// Commits in the target set, as well as any external children and parents.
189 commits: HashMap<CommitId, CommitState>,
190 /// Heads of the target set in the order they should be added to the UI.
191 /// This is used to make the graph rendering more stable. It must be
192 /// kept up to date when parents are changed.
193 head_order: Vec<CommitId>,
194 /// The current order of commits target commits in the UI. This is
195 /// recalculated when necessary from `head_order`.
196 current_order: Vec<CommitId>,
197 /// The current selection as an index into `current_order`
198 current_selection: usize,
199 external_children: IndexSet<CommitId>,
200 external_parents: IndexSet<CommitId>,
201 /// The number of commits to skip from the top of the rendered list to keep
202 /// the selection within the estimated viewport.
203 scroll_top: usize,
204 }
205
206 impl State {
207 /// Creates a new `State` from a list of commits and a list of external
208 /// children. The list of commits must not have gaps between commits.
209 async fn new(commits: Vec<Commit>, external_children: Vec<Commit>) -> BackendResult<Self> {
210 // Initialize head_order to match the heads in the input's order.
211 let commit_set: HashSet<_> = commits.iter().map(|commit| commit.id()).collect();
212 let mut heads: HashSet<_> = commit_set.clone();
213 for commit in &commits {
214 for parent in commit.parent_ids() {
215 heads.remove(parent);
216 }
217 }
218 let mut external_parents = IndexSet::new();
219 for commit in &commits {
220 for parent_id in commit.parent_ids() {
221 if !commit_set.contains(parent_id) {
222 external_parents.insert(parent_id.clone());
223 }
224 }
225 }
226 let external_parent_commits: Vec<_> = try_join_all(
227 external_parents
228 .iter()
229 .map(|id| commits[0].store().get_commit_async(id)),
230 )
231 .await?;
232 let head_order = commits
233 .iter()
234 .filter(|&commit| heads.contains(commit.id()))
235 .map(|commit| commit.id().clone())
236 .collect();
237 let external_children_ids = external_children
238 .iter()
239 .map(|commit| commit.id().clone())
240 .collect();
241 let commits: HashMap<CommitId, CommitState> = commits
242 .into_iter()
243 .chain(external_children)
244 .chain(external_parent_commits)
245 .map(|commit: Commit| {
246 let id = commit.id().clone();
247 let parents = commit.parent_ids().to_vec();
248 let commit_state = CommitState {
249 commit,
250 action: UiAction::Keep,
251 parents,
252 };
253 (id, commit_state)
254 })
255 .collect();
256 let mut state = Self {
257 commits,
258 head_order,
259 current_order: vec![], // Will be set by update_commit_order()
260 current_selection: 0,
261 external_children: external_children_ids,
262 external_parents,
263 scroll_top: 0,
264 };
265 state.update_commit_order();
266 Ok(state)
267 }
268
269 fn is_valid(&self) -> bool {
270 true
271 }
272
273 fn current_id(&self) -> &CommitId {
274 &self.current_order[self.current_selection]
275 }
276
277 /// Update the current UI commit order after parents have changed.
278 fn update_commit_order(&mut self) {
279 // Use the original order to get a determinisic order.
280 // TODO: Use TopoGroupedGraph so the order better matches `jj log`
281 let commit_ids: Vec<&CommitId> = dag_walk::topo_order_reverse(
282 self.head_order.iter(),
283 |id| *id,
284 |id| {
285 self.commits.get(id).unwrap().parents.iter().filter(|id| {
286 self.commits.contains_key(id) && !self.external_parents.contains(*id)
287 })
288 },
289 |_| panic!("cycle detected"),
290 )
291 .unwrap();
292 self.current_order = commit_ids.into_iter().cloned().collect();
293 }
294
295 fn swap_commits(&mut self, a_id: &CommitId, b_id: &CommitId) {
296 if a_id == b_id {
297 return;
298 }
299
300 let a_idx = self.current_order.iter().position(|x| x == a_id).unwrap();
301 let b_idx = self.current_order.iter().position(|x| x == b_id).unwrap();
302
303 if self.current_selection == a_idx {
304 self.current_selection = b_idx;
305 } else if self.current_selection == b_idx {
306 self.current_selection = a_idx;
307 }
308
309 self.current_order.swap(a_idx, b_idx);
310
311 for id in &mut self.head_order {
312 if id == a_id {
313 *id = b_id.clone();
314 } else if id == b_id {
315 *id = a_id.clone();
316 }
317 }
318
319 // Update references to the swapped commits from their children
320 for commit_state in self.commits.values_mut() {
321 for id in &mut commit_state.parents {
322 if id == a_id {
323 *id = b_id.clone();
324 } else if id == b_id {
325 *id = a_id.clone();
326 }
327 }
328 }
329
330 // Swap the parents of the swapped commits
331 let [a_state, b_state] = self
332 .commits
333 .get_disjoint_mut([a_id, b_id])
334 .map(Option::unwrap);
335 std::mem::swap(&mut a_state.parents, &mut b_state.parents);
336 }
337
338 fn to_rewrite_plan(&self) -> RewritePlan {
339 let mut rewrites = HashMap::new();
340 for (id, commit_state) in &self.commits {
341 if self.external_parents.contains(id) {
342 continue;
343 }
344 rewrites.insert(
345 id.clone(),
346 Rewrite {
347 old_commit: commit_state.commit.clone(),
348 new_parents: commit_state.parents.clone(),
349 action: match commit_state.action {
350 UiAction::Abandon => RewriteAction::Abandon,
351 UiAction::Keep => RewriteAction::Keep,
352 },
353 },
354 );
355 }
356 RewritePlan { rewrites }
357 }
358
359 /// Swap the selected commit with its parent. Does nothing if there is not
360 /// exactly one parent or if the parent is an external parent.
361 fn swap_selection_down(&mut self) {
362 let current_id = self.current_id().clone();
363 let [parent] = self.commits.get(&current_id).unwrap().parents.as_slice() else {
364 return;
365 };
366 if self.external_parents.contains(parent) {
367 return;
368 }
369 let parent = parent.clone();
370 self.swap_commits(&current_id, &parent);
371 }
372
373 /// Adjust the scroll position to keep the selection within the estimated
374 /// viewport.
375 fn clamp_scroll(&mut self, viewport_rows: u16) {
376 // `render()` configures the graph renderer with a minimum row height of
377 // two, so this estimates how many commits fit in the common case. Custom
378 // templates and graph topology can make a commit taller, so this is not
379 // a strict bound.
380 let max_visible = (viewport_rows / 2).max(1) as usize;
381 let total_commits =
382 self.external_children.len() + self.current_order.len() + self.external_parents.len();
383 let selection_pos = self.external_children.len() + self.current_selection;
384
385 if selection_pos < self.scroll_top {
386 self.scroll_top = selection_pos;
387 } else if selection_pos >= self.scroll_top.saturating_add(max_visible) {
388 self.scroll_top = selection_pos.saturating_sub(max_visible - 1);
389 }
390
391 let max_scroll = total_commits.saturating_sub(max_visible);
392 self.scroll_top = self.scroll_top.min(max_scroll);
393 }
394
395 /// Swap the selected commit with one of its children. Does nothing if there
396 /// is not exactly one child or if the child is an external child.
397 fn swap_selection_up(&mut self) {
398 let current_id = self.current_id().clone();
399 let children: Vec<_> = self
400 .commits
401 .iter()
402 .filter(|(_, state)| state.parents.contains(&current_id))
403 .map(|(id, _)| id.clone())
404 .collect();
405 let [child] = children.as_slice() else {
406 return;
407 };
408 if self.external_children.contains(child) {
409 return;
410 }
411 self.swap_commits(&current_id, child);
412 }
413 }
414
415 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
416 enum RewriteAction {
417 Abandon,
418 Keep,
419 }
420
421 struct Rewrite {
422 old_commit: Commit,
423 new_parents: Vec<CommitId>,
424 action: RewriteAction,
425 }
426
427 struct RewritePlan {
428 rewrites: HashMap<CommitId, Rewrite>,
429 }
430
431 impl RewritePlan {
432 async fn execute(
433 mut self,
434 mut_repo: &mut MutableRepo,
435 ) -> Result<HashMap<CommitId, Commit>, CommandError> {
436 // Find order to rebase the commits. The order is determined by the new
437 // parents.
438 let ordered_commit_ids = dag_walk::topo_order_forward(
439 self.rewrites.keys().cloned(),
440 |id| id.clone(),
441 |id| {
442 self.rewrites
443 .get(id)
444 .unwrap()
445 .new_parents
446 .iter()
447 .filter(|id| self.rewrites.contains_key(id))
448 .cloned()
449 },
450 |_| panic!("cycle detected"),
451 )
452 .unwrap();
453 // Rewrite the commits in the order determined above
454 let mut rewritten_commits: HashMap<CommitId, Commit> = HashMap::new();
455 for id in ordered_commit_ids {
456 let rewrite = self.rewrites.remove(&id).unwrap();
457 let new_parents = mut_repo.new_parents(&rewrite.new_parents);
458 let rewriter = CommitRewriter::new(mut_repo, rewrite.old_commit, new_parents);
459 match rewrite.action {
460 RewriteAction::Abandon => rewriter.abandon(),
461 RewriteAction::Keep => {
462 if rewriter.parents_changed() {
463 let new_commit = rewriter.rebase().await?.write().await?;
464 rewritten_commits.insert(id, new_commit);
465 }
466 }
467 }
468 }
469 Ok(rewritten_commits)
470 }
471 }
472
473 fn run_tui<B: ratatui::backend::Backend>(
474 ui: &mut Ui,
475 terminal: &mut Terminal<B>,
476 template: TemplateRenderer<Commit>,
477 mut state: State,
478 ) -> Result<Option<State>, CommandError> {
479 let help_items = [
480 ("↓/j", "down"),
481 ("↑/k", "up"),
482 ("⇧+↓/J", "swap down"),
483 ("⇧+↑/K", "swap up"),
484 ("a", "abandon"),
485 ("p", "keep"),
486 ("c", "confirm"),
487 ("q", "quit"),
488 ];
489 let mut help_spans = Vec::new();
490 for (i, (key, desc)) in help_items.iter().enumerate() {
491 if i > 0 {
492 help_spans.push(Span::raw(" • "));
493 }
494 help_spans.push(Span::styled(*key, Style::default().fg(Color::Magenta)));
495 help_spans.push(Span::raw(format!(" {desc}")));
496 }
497 let help_line = Line::from(help_spans);
498
499 let render_commit = |commit: &Commit, is_context_node: bool| {
500 let mut text_lines = vec![];
501 let mut formatter = ui.new_formatter(&mut text_lines).into_labeled("arrange");
502 if is_context_node {
503 template
504 .format(commit, formatter.labeled("context").as_mut())
505 .unwrap();
506 } else {
507 template.format(commit, formatter.as_mut()).unwrap();
508 }
509 drop(formatter);
510 text_lines
511 };
512
513 loop {
514 terminal
515 .draw(|frame| {
516 let layout = Layout::default()
517 .direction(Direction::Vertical)
518 .constraints([Constraint::Fill(1), Constraint::Length(1)])
519 .split(frame.area());
520 let main_area = layout[0];
521 let help_area = layout[1];
522 state.clamp_scroll(main_area.height);
523 render(&state, render_commit, frame.buffer_mut(), main_area);
524 frame.render_widget(&help_line, help_area);
525 })
526 .map_err(|e| internal_error(format!("Failed to draw TUI: {e}")))?;
527
528 if let Event::Key(event) =
529 event::read().map_err(|e| internal_error(format!("Failed to read TUI events: {e}")))?
530 {
531 // On Windows, we get Press and Release (and maybe Repeat) events, but on Linux
532 // we only get Press.
533 if event.is_release() {
534 continue;
535 }
536 match (event.code, event.modifiers) {
537 (KeyCode::Char('q'), KeyModifiers::NONE)
538 | (KeyCode::Char('c'), KeyModifiers::CONTROL) => {
539 return Ok(None);
540 }
541 (KeyCode::Char('c'), KeyModifiers::NONE) => {
542 return Ok(Some(state));
543 }
544 _ => {}
545 }
546 let new_state = handle_key_event(event, state.clone());
547 if new_state != state && new_state.is_valid() {
548 state = new_state;
549 state.update_commit_order();
550 }
551 }
552 }
553 }
554
555 fn handle_key_event(event: KeyEvent, mut state: State) -> State {
556 match (event.code, event.modifiers) {
557 (KeyCode::Down | KeyCode::Char('j'), KeyModifiers::NONE)
558 if state.current_selection + 1 < state.current_order.len() =>
559 {
560 state.current_selection += 1;
561 }
562 (KeyCode::Up | KeyCode::Char('k'), KeyModifiers::NONE) if state.current_selection > 0 => {
563 state.current_selection -= 1;
564 }
565 (KeyCode::Char('a'), KeyModifiers::NONE) => {
566 let id = state.current_id().clone();
567 state.commits.get_mut(&id).unwrap().action = UiAction::Abandon;
568 }
569 (KeyCode::Char('p'), KeyModifiers::NONE) => {
570 let id = state.current_id().clone();
571 state.commits.get_mut(&id).unwrap().action = UiAction::Keep;
572 }
573 (KeyCode::Down | KeyCode::Char('J'), KeyModifiers::SHIFT) => {
574 state.swap_selection_down();
575 }
576 (KeyCode::Up | KeyCode::Char('K'), KeyModifiers::SHIFT) => {
577 state.swap_selection_up();
578 }
579 _ => {}
580 }
581 state
582 }
583
584 fn render(
585 state: &State,
586 render_commit: impl Fn(&Commit, bool) -> Vec<u8>,
587 buf: &mut Buffer,
588 main_area: Rect,
589 ) {
590 let mut row_renderer = GraphRowRenderer::new()
591 .output()
592 .with_min_row_height(2)
593 .build_box_drawing();
594 let mut row_area = main_area;
595 let current_selection_id = state.current_id();
596 let commits_to_render = state
597 .external_children
598 .iter()
599 .chain(state.current_order.iter())
600 .chain(state.external_parents.iter())
601 .skip(state.scroll_top);
602 for id in commits_to_render {
603 // TODO: Make the graph column width depend on what's needed to render the
604 // graph.
605 let row_layout = Layout::horizontal([
606 Constraint::Min(2),
607 Constraint::Min(10),
608 Constraint::Min(10),
609 Constraint::Fill(100),
610 ])
611 .split(row_area);
612 let selection_area = row_layout[0];
613 let graph_area = row_layout[1];
614 let action_area = row_layout[2];
615 let text_area = row_layout[3];
616
617 if id == current_selection_id {
618 Text::from("▶").render(selection_area, buf);
619 }
620
621 let commit_state = state.commits.get(id).unwrap();
622 let action = &commit_state.action;
623
624 // TODO: The graph can be misaligned with the text because sometimes `renderdag`
625 // inserts a line of edges before the line with the node and we assume the node
626 // is the first line emitted.
627 let edges = commit_state
628 .parents
629 .iter()
630 .map(|parent| {
631 if state.commits.contains_key(parent) {
632 Ancestor::Parent(parent)
633 } else {
634 Ancestor::Anonymous
635 }
636 })
637 .collect_vec();
638 let glyph = match action {
639 UiAction::Abandon => "×",
640 UiAction::Keep => "○",
641 };
642
643 let is_context_node =
644 state.external_children.contains(id) || state.external_parents.contains(id);
645 if !is_context_node {
646 let action_text = match action {
647 UiAction::Abandon => "abandon",
648 UiAction::Keep => "keep",
649 };
650 Text::from(action_text).render(action_area, buf);
651 }
652
653 let text_lines = render_commit(&commit_state.commit, is_context_node);
654 let text = ansi_to_tui::IntoText::into_text(&text_lines).unwrap();
655 text.render(text_area, buf);
656
657 // Make graph as tall as the text
658 let graph_message = "\n".repeat(text_lines.lines().count());
659 let graph_lines = row_renderer.next_row(id, edges, glyph.to_string(), graph_message);
660 let graph_text = Text::from(graph_lines);
661 row_area = row_area
662 .offset(Offset {
663 x: 0,
664 y: graph_text.height() as i32,
665 })
666 .intersection(main_area);
667 graph_text.render(graph_area, buf);
668 }
669 }
670
671 #[cfg(test)]
672 mod tests {
673 use indoc::indoc;
674 use maplit::hashset;
675 use pollster::FutureExt as _;
676 use testutils::CommitBuilderExt as _;
677 use testutils::TestRepo;
678 use testutils::TestResult;
679
680 use super::*;
681
682 fn no_op_plan(commits: &[&Commit]) -> RewritePlan {
683 let rewrites = commits
684 .iter()
685 .map(|commit| {
686 (
687 commit.id().clone(),
688 Rewrite {
689 old_commit: (*commit).clone(),
690 new_parents: commit.parent_ids().to_vec(),
691 action: RewriteAction::Keep,
692 },
693 )
694 })
695 .collect();
696 RewritePlan { rewrites }
697 }
698
699 #[test]
700 fn test_update_commit_order_empty() -> TestResult {
701 let mut state = State::new(vec![], vec![]).block_on()?;
702 assert_eq!(state.head_order, vec![]);
703 state.update_commit_order();
704 assert_eq!(state.current_order, vec![]);
705 Ok(())
706 }
707
708 #[test]
709 fn test_update_commit_order_reorder() -> TestResult {
710 let test_repo = TestRepo::init();
711 let store = test_repo.repo.store();
712 let empty_tree = store.empty_merged_tree();
713
714 // Move A on top of C:
715 // D C A
716 // |/ |
717 // B => C D
718 // | |/
719 // A B
720 let mut tx = test_repo.repo.start_transaction();
721 let mut create_commit = |parents| {
722 tx.repo_mut()
723 .new_commit(parents, empty_tree.clone())
724 .write_unwrap()
725 };
726 let commit_a = create_commit(vec![store.root_commit_id().clone()]);
727 let commit_b = create_commit(vec![commit_a.id().clone()]);
728 let commit_c = create_commit(vec![commit_b.id().clone()]);
729 let commit_d = create_commit(vec![commit_b.id().clone()]);
730
731 let mut state = State::new(
732 vec![
733 commit_d.clone(),
734 commit_c.clone(),
735 commit_b.clone(),
736 commit_a.clone(),
737 ],
738 vec![],
739 )
740 .block_on()?;
741
742 // The initial head order is determined by the input order
743 assert_eq!(
744 state.head_order,
745 vec![commit_d.id().clone(), commit_c.id().clone()]
746 );
747
748 // We get the original order before we make any changes
749 assert_eq!(
750 state.current_order,
751 vec![
752 commit_d.id().clone(),
753 commit_c.id().clone(),
754 commit_b.id().clone(),
755 commit_a.id().clone(),
756 ]
757 );
758
759 // Update parents and head order and check that the commit order changes.
760 state.commits.get_mut(commit_a.id()).unwrap().parents = vec![commit_c.id().clone()];
761 state.commits.get_mut(commit_b.id()).unwrap().parents =
762 vec![store.root_commit_id().clone()];
763 state.head_order = vec![commit_d.id().clone(), commit_a.id().clone()];
764 state.update_commit_order();
765 assert_eq!(
766 state.current_order,
767 vec![
768 commit_d.id().clone(),
769 commit_a.id().clone(),
770 commit_c.id().clone(),
771 commit_b.id().clone(),
772 ]
773 );
774
775 Ok(())
776 }
777
778 #[test]
779 fn test_swap_commits() -> TestResult {
780 let test_repo = TestRepo::init();
781 let store = test_repo.repo.store();
782 let empty_tree = store.empty_merged_tree();
783
784 // Construct the graph:
785 // f
786 // |
787 // D e
788 // |\|
789 // B C
790 // |/
791 // A
792 // |
793 // root
794 //
795 // Lowercase nodes are external to the set
796 let mut tx = test_repo.repo.start_transaction();
797 let mut create_commit = |parents| {
798 tx.repo_mut()
799 .new_commit(parents, empty_tree.clone())
800 .write_unwrap()
801 };
802 let commit_a = create_commit(vec![store.root_commit_id().clone()]);
803 let commit_b = create_commit(vec![commit_a.id().clone()]);
804 let commit_c = create_commit(vec![commit_a.id().clone()]);
805 let commit_d = create_commit(vec![commit_b.id().clone(), commit_c.id().clone()]);
806 let commit_e = create_commit(vec![commit_c.id().clone()]);
807 let commit_f = create_commit(vec![commit_d.id().clone()]);
808
809 let mut state = State::new(
810 vec![
811 commit_d.clone(),
812 commit_c.clone(),
813 commit_b.clone(),
814 commit_a.clone(),
815 ],
816 vec![commit_e.clone(), commit_f.clone()],
817 )
818 .block_on()?;
819 assert_eq!(state.head_order, vec![commit_d.id().clone()]);
820 assert_eq!(
821 state.current_order,
822 vec![
823 commit_d.id().clone(),
824 commit_b.id().clone(),
825 commit_c.id().clone(),
826 commit_a.id().clone()
827 ]
828 );
829
830 // Swap D and C:
831 // f f
832 // | |
833 // D e C e
834 // |\| |\|
835 // B C => B D
836 // |/ |/
837 // A A
838 // | |
839 // root root
840 //
841 state.swap_commits(commit_d.id(), commit_c.id());
842 assert_eq!(state.head_order, vec![commit_c.id().clone()]);
843 assert_eq!(
844 state.current_order,
845 vec![
846 commit_c.id().clone(),
847 commit_b.id().clone(),
848 commit_d.id().clone(),
849 commit_a.id().clone()
850 ]
851 );
852 assert_eq!(state.current_selection, 2);
853 assert_eq!(
854 *state.commits.get(commit_c.id()).unwrap().parents,
855 vec![commit_b.id().clone(), commit_d.id().clone()],
856 );
857 assert_eq!(
858 *state.commits.get(commit_d.id()).unwrap().parents,
859 vec![commit_a.id().clone()],
860 );
861 assert_eq!(
862 *state.commits.get(commit_e.id()).unwrap().parents,
863 vec![commit_d.id().clone()],
864 );
865 assert_eq!(
866 *state.commits.get(commit_f.id()).unwrap().parents,
867 vec![commit_c.id().clone()],
868 );
869
870 // Swap B and D:
871 // f f
872 // | |
873 // C e C e
874 // |\| |\|
875 // B D => D B
876 // |/ |/
877 // A A
878 // | |
879 // root root
880 //
881 state.swap_commits(commit_b.id(), commit_d.id());
882 assert_eq!(state.head_order, vec![commit_c.id().clone()]);
883 assert_eq!(
884 state.current_order,
885 vec![
886 commit_c.id().clone(),
887 commit_d.id().clone(),
888 commit_b.id().clone(),
889 commit_a.id().clone()
890 ]
891 );
892 assert_eq!(state.current_selection, 1);
893 assert_eq!(
894 *state.commits.get(commit_c.id()).unwrap().parents,
895 vec![commit_d.id().clone(), commit_b.id().clone()],
896 );
897 assert_eq!(
898 *state.commits.get(commit_d.id()).unwrap().parents,
899 vec![commit_a.id().clone()],
900 );
901 assert_eq!(
902 *state.commits.get(commit_b.id()).unwrap().parents,
903 vec![commit_a.id().clone()],
904 );
905 assert_eq!(
906 *state.commits.get(commit_e.id()).unwrap().parents,
907 vec![commit_b.id().clone()],
908 );
909
910 // Swap A and C:
911 // f f
912 // | |
913 // C e A e
914 // |\| |\|
915 // D B => D B
916 // |/ |/
917 // A C
918 // | |
919 // root root
920 //
921 state.swap_commits(commit_a.id(), commit_c.id());
922 assert_eq!(state.head_order, vec![commit_a.id().clone()]);
923 assert_eq!(
924 state.current_order,
925 vec![
926 commit_a.id().clone(),
927 commit_d.id().clone(),
928 commit_b.id().clone(),
929 commit_c.id().clone()
930 ]
931 );
932 assert_eq!(state.current_selection, 1);
933 assert_eq!(
934 *state.commits.get(commit_a.id()).unwrap().parents,
935 vec![commit_d.id().clone(), commit_b.id().clone()],
936 );
937 assert_eq!(
938 *state.commits.get(commit_d.id()).unwrap().parents,
939 vec![commit_c.id().clone()],
940 );
941 assert_eq!(
942 *state.commits.get(commit_b.id()).unwrap().parents,
943 vec![commit_c.id().clone()],
944 );
945 assert_eq!(
946 *state.commits.get(commit_f.id()).unwrap().parents,
947 vec![commit_a.id().clone()],
948 );
949
950 // No-op swap
951 state.swap_commits(commit_a.id(), commit_a.id());
952 assert_eq!(state.current_selection, 1);
953 assert_eq!(
954 state.current_order,
955 vec![
956 commit_a.id().clone(),
957 commit_d.id().clone(),
958 commit_b.id().clone(),
959 commit_c.id().clone()
960 ]
961 );
962 Ok(())
963 }
964
965 #[test]
966 fn test_swap_selection_down() -> TestResult {
967 let test_repo = TestRepo::init();
968 let store = test_repo.repo.store();
969 let empty_tree = store.empty_merged_tree();
970
971 // Construct the graph:
972 // f
973 // |
974 // D e
975 // |\|
976 // B C
977 // |/
978 // A
979 // |
980 // root
981 //
982 // Lowercase nodes are external to the set
983 let mut tx = test_repo.repo.start_transaction();
984 let mut create_commit = |parents| {
985 tx.repo_mut()
986 .new_commit(parents, empty_tree.clone())
987 .write_unwrap()
988 };
989 let commit_a = create_commit(vec![store.root_commit_id().clone()]);
990 let commit_b = create_commit(vec![commit_a.id().clone()]);
991 let commit_c = create_commit(vec![commit_a.id().clone()]);
992 let commit_d = create_commit(vec![commit_b.id().clone(), commit_c.id().clone()]);
993 let commit_e = create_commit(vec![commit_c.id().clone()]);
994 let commit_f = create_commit(vec![commit_d.id().clone()]);
995
996 let mut state = State::new(
997 vec![
998 commit_d.clone(),
999 commit_c.clone(),
1000 commit_b.clone(),
1001 commit_a.clone(),
1002 ],
1003 vec![commit_e.clone(), commit_f.clone()],
1004 )
1005 .block_on()?;
1006 assert_eq!(
1007 state.current_order,
1008 vec![
1009 commit_d.id().clone(),
1010 commit_b.id().clone(),
1011 commit_c.id().clone(),
1012 commit_a.id().clone(),
1013 ]
1014 );
1015
1016 // Attempting to swap D down should have no effect because it has two parents
1017 state.current_selection = 0;
1018 assert_eq!(state.current_id(), commit_d.id());
1019 let state_before = state.clone();
1020 state.swap_selection_down();
1021 assert_eq!(state, state_before);
1022
1023 // Swap B down:
1024 // f f
1025 // | |
1026 // D e D e
1027 // |\| |\|
1028 // B C => A C
1029 // |/ |/
1030 // A B
1031 // | |
1032 // root root
1033 //
1034 state.current_selection = 1;
1035 assert_eq!(state.current_id(), commit_b.id());
1036 state.swap_selection_down();
1037 assert_eq!(
1038 state.current_order,
1039 vec![
1040 commit_d.id().clone(),
1041 commit_a.id().clone(),
1042 commit_c.id().clone(),
1043 commit_b.id().clone(),
1044 ]
1045 );
1046 assert_eq!(state.current_selection, 3);
1047
1048 // Swap C down:
1049 // f f
1050 // | |
1051 // D e D e
1052 // |\| |\|
1053 // A C => A B
1054 // |/ |/
1055 // B C
1056 // | |
1057 // root root
1058 //
1059 state.current_selection = 2;
1060 assert_eq!(state.current_id(), commit_c.id());
1061 state.swap_selection_down();
1062 assert_eq!(
1063 state.current_order,
1064 vec![
1065 commit_d.id().clone(),
1066 commit_a.id().clone(),
1067 commit_b.id().clone(),
1068 commit_c.id().clone(),
1069 ]
1070 );
1071 assert_eq!(state.current_selection, 3);
1072
1073 // Attempting to swap C down should have no effect because it would move outside
1074 // of range
1075 state.current_selection = 3;
1076 assert_eq!(state.current_id(), commit_c.id());
1077 let state_before = state.clone();
1078 state.swap_selection_down();
1079 assert_eq!(state, state_before);
1080
1081 Ok(())
1082 }
1083
1084 #[test]
1085 fn test_swap_selection_up() -> TestResult {
1086 let test_repo = TestRepo::init();
1087 let store = test_repo.repo.store();
1088 let empty_tree = store.empty_merged_tree();
1089
1090 // Construct the graph:
1091 // f
1092 // |
1093 // D e
1094 // |\|
1095 // B C
1096 // |/
1097 // A
1098 // |
1099 // root
1100 //
1101 // Lowercase nodes are external to the set
1102 let mut tx = test_repo.repo.start_transaction();
1103 let mut create_commit = |parents| {
1104 tx.repo_mut()
1105 .new_commit(parents, empty_tree.clone())
1106 .write_unwrap()
1107 };
1108 let commit_a = create_commit(vec![store.root_commit_id().clone()]);
1109 let commit_b = create_commit(vec![commit_a.id().clone()]);
1110 let commit_c = create_commit(vec![commit_a.id().clone()]);
1111 let commit_d = create_commit(vec![commit_b.id().clone(), commit_c.id().clone()]);
1112 let commit_e = create_commit(vec![commit_c.id().clone()]);
1113 let commit_f = create_commit(vec![commit_d.id().clone()]);
1114
1115 let mut state = State::new(
1116 vec![
1117 commit_d.clone(),
1118 commit_c.clone(),
1119 commit_b.clone(),
1120 commit_a.clone(),
1121 ],
1122 vec![commit_e.clone(), commit_f.clone()],
1123 )
1124 .block_on()?;
1125 assert_eq!(
1126 state.current_order,
1127 vec![
1128 commit_d.id().clone(),
1129 commit_b.id().clone(),
1130 commit_c.id().clone(),
1131 commit_a.id().clone(),
1132 ]
1133 );
1134
1135 // Attempting to swap A up should have no effect because it has two children
1136 state.current_selection = 3;
1137 assert_eq!(state.current_id(), commit_a.id());
1138 let state_before = state.clone();
1139 state.swap_selection_up();
1140 assert_eq!(state, state_before);
1141
1142 // Attempting to swap C up should have no effect because it has two children
1143 // even though one is external. We could change this to ignore the external
1144 // child.
1145 state.current_selection = 2;
1146 assert_eq!(state.current_id(), commit_c.id());
1147 let state_before = state.clone();
1148 state.swap_selection_up();
1149 assert_eq!(state, state_before);
1150
1151 // Swap B up:
1152 // f f
1153 // | |
1154 // D e B e
1155 // |\| |\|
1156 // B C => D C
1157 // |/ |/
1158 // A A
1159 // | |
1160 // root root
1161 //
1162 state.current_selection = 1;
1163 assert_eq!(state.current_id(), commit_b.id());
1164 state.swap_selection_up();
1165 assert_eq!(
1166 state.current_order,
1167 vec![
1168 commit_b.id().clone(),
1169 commit_d.id().clone(),
1170 commit_c.id().clone(),
1171 commit_a.id().clone(),
1172 ]
1173 );
1174 assert_eq!(state.current_selection, 0);
1175
1176 // Attempting to swap B up should have no effect because it would move outside
1177 // of range
1178 state.current_selection = 0;
1179 assert_eq!(state.current_id(), commit_b.id());
1180 let state_before = state.clone();
1181 state.swap_selection_up();
1182 assert_eq!(state, state_before);
1183
1184 Ok(())
1185 }
1186
1187 #[test]
1188 fn test_execute_plan_reorder() -> TestResult {
1189 let test_repo = TestRepo::init();
1190 let store = test_repo.repo.store();
1191 let empty_tree = store.empty_merged_tree();
1192
1193 // Move A between C and D, let E follow:
1194 // F F E
1195 // | |/
1196 // D C A
1197 // |/ |
1198 // B E => D C
1199 // |/ |/
1200 // A B
1201 // | |
1202 // root root
1203 let mut tx = test_repo.repo.start_transaction();
1204 let mut create_commit = |parents| {
1205 tx.repo_mut()
1206 .new_commit(parents, empty_tree.clone())
1207 .write_unwrap()
1208 };
1209 let commit_a = create_commit(vec![store.root_commit_id().clone()]);
1210 let commit_b = create_commit(vec![commit_a.id().clone()]);
1211 let commit_c = create_commit(vec![commit_b.id().clone()]);
1212 let commit_d = create_commit(vec![commit_b.id().clone()]);
1213 let commit_e = create_commit(vec![commit_a.id().clone()]);
1214 let commit_f = create_commit(vec![commit_c.id().clone()]);
1215 let mut plan = no_op_plan(&[
1216 &commit_a, &commit_b, &commit_c, &commit_d, &commit_e, &commit_f,
1217 ]);
1218
1219 // Update the plan with the new parents
1220 plan.rewrites.get_mut(commit_a.id()).unwrap().new_parents = vec![commit_c.id().clone()];
1221 plan.rewrites.get_mut(commit_b.id()).unwrap().new_parents =
1222 vec![store.root_commit_id().clone()];
1223 plan.rewrites.get_mut(commit_f.id()).unwrap().new_parents = vec![commit_a.id().clone()];
1224
1225 let rewritten = plan.execute(tx.repo_mut()).block_on().unwrap();
1226 tx.repo_mut().rebase_descendants().block_on()?;
1227 assert_eq!(
1228 rewritten.keys().collect::<HashSet<_>>(),
1229 hashset![
1230 commit_a.id(),
1231 commit_b.id(),
1232 commit_c.id(),
1233 commit_d.id(),
1234 commit_e.id(),
1235 commit_f.id(),
1236 ]
1237 );
1238 let new_commit_a = rewritten.get(commit_a.id()).unwrap();
1239 let new_commit_b = rewritten.get(commit_b.id()).unwrap();
1240 let new_commit_c = rewritten.get(commit_c.id()).unwrap();
1241 let new_commit_d = rewritten.get(commit_d.id()).unwrap();
1242 let new_commit_e = rewritten.get(commit_e.id()).unwrap();
1243 let new_commit_f = rewritten.get(commit_f.id()).unwrap();
1244 assert_eq!(new_commit_b.parent_ids(), &[store.root_commit_id().clone()]);
1245 assert_eq!(new_commit_c.parent_ids(), &[new_commit_b.id().clone()]);
1246 assert_eq!(new_commit_a.parent_ids(), &[new_commit_c.id().clone()]);
1247 assert_eq!(new_commit_d.parent_ids(), &[new_commit_b.id().clone()]);
1248 assert_eq!(new_commit_e.parent_ids(), &[new_commit_a.id().clone()]);
1249 assert_eq!(new_commit_f.parent_ids(), &[new_commit_a.id().clone()]);
1250 Ok(())
1251 }
1252
1253 #[test]
1254 fn test_execute_plan_abandon() -> TestResult {
1255 let test_repo = TestRepo::init();
1256 let store = test_repo.repo.store();
1257 let empty_tree = store.empty_merged_tree();
1258
1259 // Move C onto A and abandon it:
1260 // D D
1261 // | |
1262 // C C (abandoned)
1263 // | |
1264 // B => B |
1265 // | |/
1266 // A A
1267 // | |
1268 // root root
1269 let mut tx = test_repo.repo.start_transaction();
1270 let mut create_commit = |parents| {
1271 tx.repo_mut()
1272 .new_commit(parents, empty_tree.clone())
1273 .write_unwrap()
1274 };
1275 let commit_a = create_commit(vec![store.root_commit_id().clone()]);
1276 let commit_b = create_commit(vec![commit_a.id().clone()]);
1277 let commit_c = create_commit(vec![commit_b.id().clone()]);
1278 let commit_d = create_commit(vec![commit_c.id().clone()]);
1279 let mut plan = no_op_plan(&[&commit_a, &commit_b, &commit_c, &commit_d]);
1280
1281 // Update parents and action, then apply the changes.
1282 *plan.rewrites.get_mut(commit_c.id()).unwrap() = Rewrite {
1283 old_commit: commit_c.clone(),
1284 new_parents: vec![commit_a.id().clone()],
1285 action: RewriteAction::Abandon,
1286 };
1287
1288 let rewritten = plan.execute(tx.repo_mut()).block_on().unwrap();
1289 tx.repo_mut().rebase_descendants().block_on()?;
1290 assert_eq!(rewritten.keys().sorted().collect_vec(), vec![commit_d.id()]);
1291 let new_commit_d = rewritten.get(commit_d.id()).unwrap();
1292 assert_eq!(new_commit_d.parent_ids(), &[commit_a.id().clone()]);
1293 assert_eq!(
1294 *tx.repo_mut().view().heads(),
1295 hashset![commit_b.id().clone(), new_commit_d.id().clone()]
1296 );
1297 Ok(())
1298 }
1299
1300 fn render_commit(commit: &Commit, is_context_node: bool) -> Vec<u8> {
1301 let mut text = commit.description().to_owned();
1302 if is_context_node {
1303 text = format!("(context) {text}");
1304 }
1305 text.into_bytes()
1306 }
1307
1308 fn buffer_to_string(buf: &Buffer) -> String {
1309 let mut res = String::new();
1310 for y in 0..buf.area.height {
1311 let mut line = String::new();
1312 for x in 0..buf.area.width {
1313 let cell = &buf[(x, y)];
1314 line.push_str(cell.symbol());
1315 }
1316 res.push_str(line.trim_end());
1317 res.push('\n');
1318 }
1319 res
1320 }
1321
1322 fn render_to_string(state: &State, width: u16, height: u16) -> String {
1323 let mut buf = Buffer::empty(Rect::new(0, 0, width, height));
1324 let mut state = state.clone();
1325 state.clamp_scroll(height);
1326 render(
1327 &state,
1328 render_commit,
1329 &mut buf,
1330 Rect::new(0, 0, width, height),
1331 );
1332 buffer_to_string(&buf)
1333 }
1334
1335 #[test]
1336 fn test_render_single_commit_with_context() -> TestResult {
1337 let test_repo = TestRepo::init();
1338 let store = test_repo.repo.store();
1339 let empty_tree = store.empty_merged_tree();
1340
1341 let mut tx = test_repo.repo.start_transaction();
1342 let mut create_commit = |parents, description: &str| {
1343 tx.repo_mut()
1344 .new_commit(parents, empty_tree.clone())
1345 .set_description(description)
1346 .write_unwrap()
1347 };
1348 let commit_a = create_commit(vec![store.root_commit_id().clone()], "commit A");
1349 let commit_b = create_commit(vec![commit_a.id().clone()], "commit B");
1350 let commit_c = create_commit(vec![commit_b.id().clone()], "commit C");
1351
1352 let state = State::new(vec![commit_b.clone()], vec![commit_c.clone()]).block_on()?;
1353 insta::assert_snapshot!(render_to_string(&state, 80, 50), @"
1354 ○ (context) commit C
1355 │
1356 ▶ ○ keep commit B
1357 │
1358 ○ (context) commit A
1359 │
1360 ~
1361 ");
1362
1363 Ok(())
1364 }
1365
1366 #[test]
1367 fn test_render_abandon() -> TestResult {
1368 let test_repo = TestRepo::init();
1369 let store = test_repo.repo.store();
1370 let empty_tree = store.empty_merged_tree();
1371
1372 let mut tx = test_repo.repo.start_transaction();
1373 let mut create_commit = |parents, description: &str| {
1374 tx.repo_mut()
1375 .new_commit(parents, empty_tree.clone())
1376 .set_description(description)
1377 .write_unwrap()
1378 };
1379 let commit_a = create_commit(vec![store.root_commit_id().clone()], "commit A");
1380
1381 let mut state = State::new(vec![commit_a.clone()], vec![]).block_on()?;
1382 state.commits.get_mut(commit_a.id()).unwrap().action = UiAction::Abandon;
1383 insta::assert_snapshot!(render_to_string(&state, 80, 50), @"
1384 ▶ × abandon commit A
1385 │
1386 ○ (context)
1387 ");
1388
1389 Ok(())
1390 }
1391 #[test]
1392 fn test_render_long_description() -> TestResult {
1393 let test_repo = TestRepo::init();
1394 let store = test_repo.repo.store();
1395 let empty_tree = store.empty_merged_tree();
1396
1397 let mut tx = test_repo.repo.start_transaction();
1398 let mut create_commit = |parents, description: &str| {
1399 tx.repo_mut()
1400 .new_commit(parents, empty_tree.clone())
1401 .set_description(description)
1402 .write_unwrap()
1403 };
1404 let commit_a = create_commit(
1405 vec![store.root_commit_id().clone()],
1406 indoc! {"
1407 commit A line 1
1408 commit A line 2
1409 commit A line 3
1410 commit A line 4
1411 commit A line 5
1412 "},
1413 );
1414
1415 let state = State::new(vec![commit_a.clone()], vec![]).block_on()?;
1416 insta::assert_snapshot!(render_to_string(&state, 80, 50), @"
1417 ▶ ○ keep commit A line 1
1418 │ commit A line 2
1419 │ commit A line 3
1420 │ commit A line 4
1421 │ commit A line 5
1422 ○ (context)
1423 ");
1424
1425 Ok(())
1426 }
1427
1428 #[test]
1429 fn test_render_multiple_commits_and_selection() -> TestResult {
1430 let test_repo = TestRepo::init();
1431 let store = test_repo.repo.store();
1432 let empty_tree = store.empty_merged_tree();
1433
1434 let mut tx = test_repo.repo.start_transaction();
1435 let mut create_commit = |parents, description: &str| {
1436 tx.repo_mut()
1437 .new_commit(parents, empty_tree.clone())
1438 .set_description(description)
1439 .write_unwrap()
1440 };
1441 let commit_a = create_commit(vec![store.root_commit_id().clone()], "commit A");
1442 let commit_b = create_commit(vec![commit_a.id().clone()], "commit B");
1443 let commit_c = create_commit(vec![commit_b.id().clone()], "commit C");
1444
1445 let mut state = State::new(
1446 vec![commit_c.clone(), commit_b.clone(), commit_a.clone()],
1447 vec![],
1448 )
1449 .block_on()?;
1450
1451 state.current_selection = 0;
1452 insta::assert_snapshot!(render_to_string(&state, 80, 50), @"
1453 ▶ ○ keep commit C
1454 │
1455 ○ keep commit B
1456 │
1457 ○ keep commit A
1458 │
1459 ○ (context)
1460 ");
1461
1462 state.current_selection = 1;
1463 insta::assert_snapshot!(&render_to_string(&state, 80, 50), @"
1464 ○ keep commit C
1465 │
1466 ▶ ○ keep commit B
1467 │
1468 ○ keep commit A
1469 │
1470 ○ (context)
1471 ");
1472
1473 Ok(())
1474 }
1475
1476 #[test]
1477 fn test_render_more_commits_than_fit() -> TestResult {
1478 let test_repo = TestRepo::init();
1479 let store = test_repo.repo.store();
1480 let empty_tree = store.empty_merged_tree();
1481
1482 let mut tx = test_repo.repo.start_transaction();
1483 let mut create_commit = |parents, description: &str| {
1484 tx.repo_mut()
1485 .new_commit(parents, empty_tree.clone())
1486 .set_description(description)
1487 .write_unwrap()
1488 };
1489 let commit_a = create_commit(vec![store.root_commit_id().clone()], "commit A");
1490 let commit_b = create_commit(vec![commit_a.id().clone()], "commit B");
1491 let commit_c = create_commit(vec![commit_b.id().clone()], "commit C");
1492 let commit_d = create_commit(vec![commit_c.id().clone()], "commit D");
1493 let commit_e = create_commit(vec![commit_d.id().clone()], "commit E");
1494 let commit_f = create_commit(vec![commit_e.id().clone()], "commit F");
1495 let commit_g = create_commit(vec![commit_f.id().clone()], "commit G");
1496
1497 let mut state = State::new(
1498 vec![
1499 commit_a.clone(),
1500 commit_b.clone(),
1501 commit_c.clone(),
1502 commit_d.clone(),
1503 commit_e.clone(),
1504 commit_f.clone(),
1505 commit_g.clone(),
1506 ],
1507 vec![],
1508 )
1509 .block_on()?;
1510 state.current_selection = 5;
1511 state.clamp_scroll(10);
1512 insta::assert_snapshot!(render_to_string(&state, 80, 10), @"
1513 ○ keep commit F
1514 │
1515 ○ keep commit E
1516 │
1517 ○ keep commit D
1518 │
1519 ○ keep commit C
1520 │
1521 ▶ ○ keep commit B
1522 │
1523 ");
1524
1525 Ok(())
1526 }
1527
1528 #[test]
1529 fn test_render_scrolls_viewport_to_keep_selection_visible() -> TestResult {
1530 let test_repo = TestRepo::init();
1531 let store = test_repo.repo.store();
1532 let empty_tree = store.empty_merged_tree();
1533
1534 let mut tx = test_repo.repo.start_transaction();
1535 let mut create_commit = |parents, description: &str| {
1536 tx.repo_mut()
1537 .new_commit(parents, empty_tree.clone())
1538 .set_description(description)
1539 .write_unwrap()
1540 };
1541 let commit_a = create_commit(vec![store.root_commit_id().clone()], "commit A");
1542 let commit_b = create_commit(vec![commit_a.id().clone()], "commit B");
1543 let commit_c = create_commit(vec![commit_b.id().clone()], "commit C");
1544 let commit_d = create_commit(vec![commit_c.id().clone()], "commit D");
1545 let commit_e = create_commit(vec![commit_d.id().clone()], "commit E");
1546 let commit_f = create_commit(vec![commit_e.id().clone()], "commit F");
1547 let commit_g = create_commit(vec![commit_f.id().clone()], "commit G");
1548
1549 let mut state = State::new(
1550 vec![
1551 commit_a.clone(),
1552 commit_b.clone(),
1553 commit_c.clone(),
1554 commit_d.clone(),
1555 commit_e.clone(),
1556 commit_f.clone(),
1557 commit_g.clone(),
1558 ],
1559 vec![],
1560 )
1561 .block_on()?;
1562
1563 // Viewport can only show 5 commits; selection starts at top.
1564 state.current_selection = 0;
1565 state.clamp_scroll(10);
1566 insta::assert_snapshot!(render_to_string(&state, 80, 10), @"
1567 ▶ ○ keep commit G
1568 │
1569 ○ keep commit F
1570 │
1571 ○ keep commit E
1572 │
1573 ○ keep commit D
1574 │
1575 ○ keep commit C
1576 │
1577 ");
1578
1579 // Move selection to a commit that would fall below the viewport.
1580 state.current_selection = 6;
1581 state.clamp_scroll(10);
1582 insta::assert_snapshot!(render_to_string(&state, 80, 10), @"
1583 ○ keep commit E
1584 │
1585 ○ keep commit D
1586 │
1587 ○ keep commit C
1588 │
1589 ○ keep commit B
1590 │
1591 ▶ ○ keep commit A
1592 │
1593 ");
1594
1595 Ok(())
1596 }
1597
1598 /// Regression test for terminal resize. The original scrolling
1599 /// implementation only reclamped after state-changing input, which left the
1600 /// selected commit outside a smaller viewport.
1601 #[test]
1602 fn test_scroll_keeps_selection_visible_after_viewport_shrinks() -> TestResult {
1603 let test_repo = TestRepo::init();
1604 let store = test_repo.repo.store();
1605 let empty_tree = store.empty_merged_tree();
1606
1607 let mut tx = test_repo.repo.start_transaction();
1608 let mut create_commit = |parents, description: &str| {
1609 tx.repo_mut()
1610 .new_commit(parents, empty_tree.clone())
1611 .set_description(description)
1612 .write_unwrap()
1613 };
1614 let commit_a = create_commit(vec![store.root_commit_id().clone()], "commit A");
1615 let commit_b = create_commit(vec![commit_a.id().clone()], "commit B");
1616 let commit_c = create_commit(vec![commit_b.id().clone()], "commit C");
1617
1618 // Model a resize between input events: the scroll position was computed
1619 // when all three commits fit, but the next draw has only four rows. No
1620 // navigation event occurs to clamp it again.
1621 let mut state = State::new(vec![commit_a, commit_b, commit_c], vec![]).block_on()?;
1622 state.current_selection = 2;
1623 state.clamp_scroll(6);
1624
1625 insta::assert_snapshot!(render_to_string(&state, 80, 4), @"
1626 ○ keep commit B
1627 │
1628 ▶ ○ keep commit A
1629 │
1630 ");
1631 Ok(())
1632 }
1633
1634 #[test]
1635 fn test_render_wide_graph() -> TestResult {
1636 let test_repo = TestRepo::init();
1637 let store = test_repo.repo.store();
1638 let empty_tree = store.empty_merged_tree();
1639
1640 let mut tx = test_repo.repo.start_transaction();
1641 let mut create_commit = |parents, description: &str| {
1642 tx.repo_mut()
1643 .new_commit(parents, empty_tree.clone())
1644 .set_description(description)
1645 .write_unwrap()
1646 };
1647 let commit_a = create_commit(vec![store.root_commit_id().clone()], "commit A");
1648 let commit_b = create_commit(vec![store.root_commit_id().clone()], "commit B");
1649 let commit_c = create_commit(vec![store.root_commit_id().clone()], "commit C");
1650 let commit_d = create_commit(vec![store.root_commit_id().clone()], "commit D");
1651 let commit_e = create_commit(vec![store.root_commit_id().clone()], "commit E");
1652 let commit_f = create_commit(vec![store.root_commit_id().clone()], "commit F");
1653 let commit_g = create_commit(
1654 vec![
1655 commit_a.id().clone(),
1656 commit_b.id().clone(),
1657 commit_c.id().clone(),
1658 commit_d.id().clone(),
1659 commit_e.id().clone(),
1660 commit_f.id().clone(),
1661 ],
1662 "commit G",
1663 );
1664
1665 let state = State::new(
1666 vec![
1667 commit_a.clone(),
1668 commit_b.clone(),
1669 commit_c.clone(),
1670 commit_d.clone(),
1671 commit_e.clone(),
1672 commit_f.clone(),
1673 commit_g.clone(),
1674 ],
1675 vec![],
1676 )
1677 .block_on()?;
1678 // TODO: Dynamically adjust the space allocated to the graph so it fits
1679 insta::assert_snapshot!(render_to_string(&state, 80, 50), @"
1680 ▶ ○ keep commit G
1681 ├─┬─┬─┬─┬─
1682 ○ │ │ │ │ keep commit A
1683 │ │ │ │ │
1684 │ ○ │ │ │ keep commit B
1685 ├─╯ │ │ │
1686 │ ○ │ │ keep commit C
1687 ├───╯ │ │
1688 │ ○ │ keep commit D
1689 ├─────╯ │
1690 │ ○ keep commit E
1691 ├───────╯
1692 │ keep commit F
1693 ├─────────
1694 ○ (context)
1695 ");
1696
1697 Ok(())
1698 }
1699 }