Debian Codegraph @

cli/src/commands/commit.rs

raw
1 // Copyright 2020 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 clap_complete::ArgValueCandidates;
16 use clap_complete::ArgValueCompleter;
17 use indoc::writedoc;
18 use jj_lib::merge::Diff;
19 use jj_lib::object_id::ObjectId as _;
20 use jj_lib::repo::Repo as _;
21 use tracing::instrument;
22
23 use crate::cli_util::CommandHelper;
24 use crate::command_error::CommandError;
25 use crate::command_error::user_error;
26 use crate::complete;
27 use crate::description_util::add_trailers;
28 use crate::description_util::description_template;
29 use crate::description_util::edit_description;
30 use crate::description_util::join_message_paragraphs;
31 use crate::ui::Ui;
32
33 /// Update the description and create a new change on top [default alias: ci]
34 ///
35 /// When called without path arguments or `--interactive`, `jj commit` is
36 /// equivalent to `jj describe` followed by `jj new`.
37 ///
38 /// When using `--interactive` or path arguments, the selected changes stay in
39 /// the current commit while the remaining changes are moved to a new
40 /// working-copy commit on top. This is very similar to `jj split`. Differences
41 /// include:
42 ///
43 /// * `jj commit` is not interactive by default (it selects all changes).
44 ///
45 /// * `jj commit` doesn't have a `-r` option. It always acts on the working-copy
46 /// commit (@).
47 ///
48 /// * `jj split` (without `-o`/`-A`/`-B`) will move bookmarks forward from the
49 /// old change to the child change. `jj commit` doesn't move bookmarks
50 /// forward.
51 ///
52 /// * `jj split` allows you to move the selected changes to a different
53 /// destination with `-o`/`-A`/`-B`.
54 #[derive(clap::Args, Clone, Debug)]
55 pub(crate) struct CommitArgs {
56 /// Interactively choose which changes to include in the current commit
57 #[arg(short, long)]
58 interactive: bool,
59
60 /// Specify diff editor to be used (implies --interactive)
61 #[arg(long, value_name = "NAME")]
62 #[arg(add = ArgValueCandidates::new(complete::diff_editors))]
63 tool: Option<String>,
64
65 /// The change description to use (don't open editor)
66 #[arg(long = "message", short, value_name = "MESSAGE")]
67 message_paragraphs: Option<Vec<String>>,
68
69 /// Open an editor to edit the change description
70 ///
71 /// Forces an editor to open when using `--message` to allow the
72 /// message to be edited afterwards.
73 #[arg(long)]
74 editor: bool,
75
76 /// Put these paths in the current commit
77 #[arg(value_name = "FILESETS", value_hint = clap::ValueHint::AnyPath)]
78 #[arg(add = ArgValueCompleter::new(complete::modified_files))]
79 paths: Vec<String>,
80 }
81
82 #[instrument(skip_all)]
83 pub(crate) async fn cmd_commit(
84 ui: &mut Ui,
85 command: &CommandHelper,
86 args: &CommitArgs,
87 ) -> Result<(), CommandError> {
88 let mut workspace_command = command.workspace_helper(ui).await?;
89
90 let commit_id = workspace_command
91 .get_wc_commit_id()
92 .ok_or_else(|| user_error("This command requires a working copy"))?;
93 let commit = workspace_command
94 .repo()
95 .store()
96 .get_commit_async(commit_id)
97 .await?;
98 let matcher = workspace_command
99 .parse_file_patterns(ui, &args.paths)?
100 .to_matcher();
101 let advanceable_bookmarks =
102 workspace_command.get_advanceable_bookmarks(ui, commit.parent_ids())?;
103 let diff_selector =
104 workspace_command.diff_selector(ui, args.tool.as_deref(), args.interactive)?;
105 let text_editor = workspace_command.text_editor()?;
106 let mut tx = workspace_command.start_transaction();
107 let base_tree = commit.parent_tree(tx.repo()).await?;
108 let format_instructions = || {
109 format!(
110 "\
111 You are splitting the working-copy commit: {}
112
113 The diff initially shows all changes. Adjust the right side until it shows the
114 contents you want for the first commit. The remainder will be included in the
115 new working-copy commit.
116 ",
117 tx.format_commit_summary(&commit)
118 )
119 };
120 let tree = diff_selector
121 .select(
122 ui,
123 Diff::new(&base_tree, &commit.tree()),
124 Diff::new(
125 commit.parents_conflict_label().await?,
126 commit.conflict_label(),
127 ),
128 matcher.as_ref(),
129 format_instructions,
130 )
131 .await?;
132 if !args.paths.is_empty() && tree.tree_ids() == base_tree.tree_ids() {
133 writeln!(
134 ui.warning_default(),
135 "The given paths do not match any file: {}",
136 args.paths.join(" ")
137 )?;
138 }
139
140 let mut commit_builder = tx.repo_mut().rewrite_commit(&commit).detach();
141 commit_builder.set_tree(tree);
142
143 let use_editor = args.message_paragraphs.is_none() || args.editor;
144 let description = match &args.message_paragraphs {
145 Some(paragraphs) => join_message_paragraphs(paragraphs),
146 None => commit_builder.description().to_owned(),
147 };
148 // The first trailer would become the first line of the description. Also, a
149 // commit with no description is treated in a special way in jujutsu: it can
150 // be discarded as soon as it's no longer the working copy. Adding a trailer
151 // to an empty description would break that logic.
152 let description = if !description.is_empty() || use_editor {
153 commit_builder.set_description(description);
154 add_trailers(ui, &tx, &commit_builder).await?
155 } else {
156 description
157 };
158 let description = if use_editor {
159 commit_builder.set_description(description);
160 let temp_commit = commit_builder.write_hidden().await?;
161 let intro = "";
162 let description = description_template(ui, &tx, intro, &temp_commit)?;
163 let description = edit_description(&text_editor, &description)?;
164 if description.is_empty() {
165 writedoc!(
166 ui.hint_default(),
167 "
168 The commit message was left empty.
169 If this was not intentional, run `jj undo` to restore the previous state.
170 Or run `jj desc @-` to add a description to the parent commit.
171 "
172 )?;
173 }
174 description
175 } else {
176 description
177 };
178 commit_builder.set_description(description);
179 let new_commit = commit_builder.write(tx.repo_mut()).await?;
180
181 let workspace_names = tx.repo().view().workspaces_for_wc_commit_id(commit.id());
182 if !workspace_names.is_empty() {
183 let new_wc_commit = tx
184 .repo_mut()
185 .new_commit(vec![new_commit.id().clone()], commit.tree())
186 .write()
187 .await?;
188
189 // Does nothing if there's no bookmarks to advance.
190 tx.advance_bookmarks(advanceable_bookmarks, new_commit.id())
191 .await?;
192
193 for name in workspace_names {
194 tx.repo_mut().edit(name, &new_wc_commit).await.unwrap();
195 }
196 }
197 tx.finish(ui, format!("commit {}", commit.id().hex()))
198 .await?;
199 Ok(())
200 }