Debian Codegraph @

cli/src/commands/undo.rs

raw
1 // Copyright 2025 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 itertools::Itertools as _;
16 use jj_lib::object_id::ObjectId as _;
17 use jj_lib::op_store::OperationId;
18
19 use crate::cli_util::CommandHelper;
20 use crate::command_error::CommandError;
21 use crate::command_error::internal_error;
22 use crate::command_error::user_error;
23 #[cfg(feature = "git")]
24 use crate::commands::git::is_push_operation;
25 use crate::commands::operation::DEFAULT_REVERT_WHAT;
26 use crate::commands::operation::view_with_desired_portions_restored;
27 use crate::ui::Ui;
28
29 /// Undo the last operation
30 ///
31 /// If used once after a normal (non-`undo`) operation, this will undo that last
32 /// operation by restoring its parent. If `jj undo` is used repeatedly, it will
33 /// restore increasingly older operations, going further back into the past.
34 ///
35 /// There is also a complementary `jj redo` command that would instead move in
36 /// the direction of the future after one or more `jj undo`s.
37 ///
38 /// Use `jj op log` to visualize the log of past operations, including a
39 /// detailed description of any past undo/redo operations. See also `jj op
40 /// restore` to explicitly restore an older operation by its id (available in
41 /// the operation log).
42 #[derive(clap::Args, Clone, Debug)]
43 pub struct UndoArgs {}
44
45 pub(crate) const UNDO_OP_DESC_PREFIX: &str = "undo: restore to operation ";
46
47 pub async fn cmd_undo(
48 ui: &mut Ui,
49 command: &CommandHelper,
50 _: &UndoArgs,
51 ) -> Result<(), CommandError> {
52 let mut workspace_command = command.workspace_helper(ui).await?;
53
54 let mut target_op = workspace_command.repo().operation().clone();
55
56 // Growing the "undo-stack" works as follows. See also the
57 // [redo-stack](./redo.rs), which works in a similar way.
58 //
59 // - If the operation to undo is a regular one (not an undo-operation), simply
60 // undo it (== restore its parent).
61 // - If the operation to undo is an undo-operation itself, undo that operation
62 // to which the previous undo-operation restored the repo.
63 // - If the operation to restore to is an undo-operation, restore directly to
64 // the original operation. This avoids creating a linked list of
65 // undo-operations, which subsequently may have to be walked with an
66 // inefficient loop.
67 //
68 // This described behavior leads to "jumping over" old undo-stacks if the
69 // current one grows into it. Consider this op-log example:
70 //
71 // * G "undo: restore A" -------+
72 // | |
73 // * F "undo: restore B" -----+ |
74 // | | |
75 // * E | |
76 // | | |
77 // * D "undo: restore B" -+ | |
78 // | | | |
79 // * C | | |
80 // | | | |
81 // * B <----------------+ <-+ |
82 // | |
83 // * A <----------------------+
84 //
85 // It was produced by the following sequence of events:
86 // - do normal operations A, B and C
87 // - undo C, restoring to B
88 // - do normal operation E
89 // - undo E, restoring to B again (NOT to D)
90 // - undo F, restoring to A
91 //
92 // Notice that running `undo` after having undone E leads to A being
93 // restored (as opposed to C). The undo-stack spanning from F to B was
94 // "jumped over".
95 //
96 if let Some(target_op_hex) = target_op
97 .metadata()
98 .description
99 .strip_prefix(UNDO_OP_DESC_PREFIX)
100 {
101 let target_op_id = OperationId::try_from_hex(target_op_hex).ok_or_else(|| {
102 internal_error("Failed to parse ID of target operation in undo-stack")
103 })?;
104 target_op = workspace_command
105 .repo()
106 .loader()
107 .load_operation(&target_op_id)
108 .await?;
109 }
110 #[cfg(feature = "git")]
111 if is_push_operation(&target_op) {
112 writeln!(
113 ui.warning_default(),
114 "Undoing a push operation often leads to conflicted bookmarks."
115 )?;
116 writeln!(ui.hint_default(), "To avoid this, run `jj redo` now.")?;
117 }
118
119 let mut target_op_parent = match target_op.parents().await?.into_iter().at_most_one() {
120 Ok(Some(op)) => op,
121 Ok(None) => return Err(user_error("Cannot undo root operation")),
122 Err(_) => {
123 return Err(user_error("Cannot undo a merge operation")
124 .hinted("Consider using `jj op restore` instead"));
125 }
126 };
127
128 // Avoid the creation of a linked list by restoring to the original
129 // operation directly, if we're about to restore an undo-operation. If we
130 // didn't do this, repeated calls of `jj new ; jj undo` would create an
131 // ever-growing linked list of undo-operations that restore each other.
132 // Calling `jj undo` one more time would have to restore to the operation
133 // at the very beginning of the linked list, which would require walking the
134 // entire thing unnecessarily.
135 if let Some(target_op_parent_hex) = target_op_parent
136 .metadata()
137 .description
138 .strip_prefix(UNDO_OP_DESC_PREFIX)
139 {
140 let target_op_parent_id =
141 OperationId::try_from_hex(target_op_parent_hex).ok_or_else(|| {
142 internal_error("Failed to parse ID of target operation's parent in undo-stack")
143 })?;
144 target_op_parent = workspace_command
145 .repo()
146 .loader()
147 .load_operation(&target_op_parent_id)
148 .await?;
149 }
150
151 let mut tx = workspace_command.start_transaction();
152 let new_view = view_with_desired_portions_restored(
153 target_op_parent.view().await?.store_view(),
154 tx.base_repo().view().store_view(),
155 &DEFAULT_REVERT_WHAT,
156 );
157 tx.repo_mut().set_view(new_view);
158 if let Some(mut formatter) = ui.status_formatter() {
159 let template = tx.base_workspace_helper().operation_summary_template();
160
161 write!(formatter, "Undid operation: ")?;
162 template.format(&target_op, formatter.as_mut())?;
163 writeln!(formatter)?;
164
165 write!(formatter, "Restored to operation: ")?;
166 template.format(&target_op_parent, formatter.as_mut())?;
167 writeln!(formatter)?;
168 }
169 tx.finish(
170 ui,
171 format!("{UNDO_OP_DESC_PREFIX}{}", target_op_parent.id().hex()),
172 )
173 .await?;
174
175 Ok(())
176 }