Debian Codegraph @

cli/src/commands/workspace/add.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 std::fs;
16
17 use futures::future::try_join_all;
18 use itertools::Itertools as _;
19 use jj_lib::commit::CommitIteratorExt as _;
20 use jj_lib::file_util;
21 use jj_lib::file_util::IoResultExt as _;
22 use jj_lib::ref_name::WorkspaceNameBuf;
23 use jj_lib::repo::Repo as _;
24 use jj_lib::rewrite::merge_commit_trees;
25 use jj_lib::workspace::Workspace;
26 use tracing::instrument;
27
28 use crate::cli_util::CommandHelper;
29 use crate::cli_util::RevisionArg;
30 use crate::command_error::CommandError;
31 use crate::command_error::internal_error_with_message;
32 use crate::command_error::user_error;
33 use crate::description_util::add_trailers;
34 use crate::description_util::join_message_paragraphs;
35 use crate::ui::Ui;
36
37 /// How to handle sparse patterns when creating a new workspace.
38 #[derive(clap::ValueEnum, Clone, Debug, Eq, PartialEq)]
39 enum SparseInheritance {
40 /// Copy all sparse patterns from the current workspace.
41 Copy,
42 /// Include all files in the new workspace.
43 Full,
44 /// Clear all files from the workspace (it will be empty).
45 Empty,
46 }
47
48 /// Add a workspace
49 ///
50 /// By default, the new workspace inherits the sparse patterns of the current
51 /// workspace. You can override this with the `--sparse-patterns` option.
52 #[derive(clap::Args, Clone, Debug)]
53 pub struct WorkspaceAddArgs {
54 /// Where to create the new workspace
55 #[arg(value_hint = clap::ValueHint::DirPath)]
56 destination: String,
57
58 /// A name for the workspace
59 ///
60 /// To override the default, which is the basename of the destination
61 /// directory.
62 #[arg(long)]
63 name: Option<WorkspaceNameBuf>,
64
65 /// A list of parent revisions for the working-copy commit of the newly
66 /// created workspace. You may specify nothing, or any number of parents.
67 ///
68 /// If no revisions are specified, the new workspace will be created, and
69 /// its working-copy commit will exist on top of the parent(s) of the
70 /// working-copy commit in the current workspace, i.e. they will share the
71 /// same parent(s).
72 ///
73 /// If any revisions are specified, the new workspace will be created, and
74 /// the new working-copy commit will be created with all these revisions as
75 /// parents, i.e. the working-copy commit will exist as if you had run `jj
76 /// new r1 r2 r3 ...`.
77 #[arg(long = "revision", short, value_name = "REVSETS", alias = "revisions")]
78 revisions: Vec<RevisionArg>,
79
80 /// The change description to use
81 #[arg(long = "message", short, value_name = "MESSAGE")]
82 message_paragraphs: Vec<String>,
83
84 /// How to handle sparse patterns when creating a new workspace.
85 #[arg(long, value_enum, default_value_t = SparseInheritance::Copy)]
86 sparse_patterns: SparseInheritance,
87 }
88
89 #[instrument(skip_all)]
90 pub async fn cmd_workspace_add(
91 ui: &mut Ui,
92 command: &CommandHelper,
93 args: &WorkspaceAddArgs,
94 ) -> Result<(), CommandError> {
95 let old_workspace_command = command.workspace_helper(ui).await?;
96 let destination_path = command.cwd().join(&args.destination);
97 let workspace_name = if let Some(name) = &args.name {
98 name.to_owned()
99 } else {
100 let file_name = destination_path.file_name().unwrap();
101 file_name
102 .to_str()
103 .ok_or_else(|| user_error("Destination path is not valid UTF-8"))?
104 .into()
105 };
106 if workspace_name.as_str().is_empty() {
107 return Err(user_error("New workspace name cannot be empty"));
108 }
109
110 let repo = old_workspace_command.repo();
111 if repo.view().get_wc_commit_id(&workspace_name).is_some() {
112 return Err(user_error(format!(
113 "Workspace named '{name}' already exists",
114 name = workspace_name.as_symbol()
115 )));
116 }
117 if !destination_path.exists() {
118 fs::create_dir(&destination_path).context(&destination_path)?;
119 } else if !file_util::is_empty_dir(&destination_path)? {
120 return Err(user_error(
121 "Destination path exists and is not an empty directory",
122 ));
123 }
124
125 let working_copy_factory = command.get_working_copy_factory()?;
126 let repo_path = old_workspace_command.repo_path();
127 // If we add per-workspace configuration, we'll need to reload settings for
128 // the new workspace.
129 let (new_workspace, repo) = Workspace::init_workspace_with_existing_repo(
130 &destination_path,
131 repo_path,
132 repo,
133 working_copy_factory,
134 workspace_name.clone(),
135 )
136 .await?;
137 writeln!(
138 ui.status(),
139 "Created workspace in \"{}\"",
140 file_util::relative_path(command.cwd(), &destination_path).display()
141 )?;
142 // Show a warning if the user passed a path without a separator, since they
143 // may have intended the argument to only be the name for the workspace.
144 if !args.destination.contains(std::path::is_separator) {
145 writeln!(
146 ui.warning_default(),
147 r#"Workspace created inside current directory. If this was unintentional, delete the "{}" directory and run `jj workspace forget {name}` to remove it."#,
148 args.destination,
149 name = workspace_name.as_symbol()
150 )?;
151 }
152
153 let mut new_workspace_command = command.for_workable_repo(ui, new_workspace, repo)?;
154
155 let sparsity = match args.sparse_patterns {
156 SparseInheritance::Full => None,
157 SparseInheritance::Empty => Some(vec![]),
158 SparseInheritance::Copy => {
159 let sparse_patterns = old_workspace_command
160 .working_copy()
161 .sparse_patterns()?
162 .to_vec();
163 Some(sparse_patterns)
164 }
165 };
166
167 if let Some(sparse_patterns) = sparsity {
168 let (mut locked_ws, _wc_commit) =
169 new_workspace_command.start_working_copy_mutation().await?;
170 locked_ws
171 .locked_wc()
172 .set_sparse_patterns(sparse_patterns)
173 .await
174 .map_err(|err| internal_error_with_message("Failed to set sparse patterns", err))?;
175 let operation_id = locked_ws.locked_wc().old_operation_id().clone();
176 locked_ws.finish(operation_id).await?;
177 }
178
179 let mut tx = new_workspace_command.start_transaction();
180
181 // If no parent revisions are specified, create a working-copy commit based
182 // on the parent of the current working-copy commit.
183 let parents = if args.revisions.is_empty() {
184 // Check out parents of the current workspace's working-copy commit, or the
185 // root if there is no working-copy commit in the current workspace.
186 if let Some(old_wc_commit_id) = tx
187 .base_repo()
188 .view()
189 .get_wc_commit_id(old_workspace_command.workspace_name())
190 {
191 tx.repo()
192 .store()
193 .get_commit_async(old_wc_commit_id)
194 .await?
195 .parents()
196 .await?
197 } else {
198 vec![tx.repo().store().root_commit()]
199 }
200 } else {
201 try_join_all(
202 old_workspace_command
203 .resolve_some_revsets(ui, &args.revisions)
204 .await?
205 .iter()
206 .map(|id| tx.repo().store().get_commit_async(id)),
207 )
208 .await?
209 };
210
211 let tree = merge_commit_trees(tx.repo(), &parents).await?;
212 let parent_ids = parents.iter().ids().cloned().collect_vec();
213 let mut commit_builder = tx.repo_mut().new_commit(parent_ids, tree).detach();
214 let mut description = join_message_paragraphs(&args.message_paragraphs);
215 if !description.is_empty() {
216 // The first trailer would become the first line of the description.
217 // Also, a commit with no description is treated in a special way in jujutsu: it
218 // can be discarded as soon as it's no longer the working copy. Adding a
219 // trailer to an empty description would break that logic.
220 commit_builder.set_description(description);
221 description = add_trailers(ui, &tx, &commit_builder).await?;
222 }
223 commit_builder.set_description(&description);
224 let new_wc_commit = commit_builder.write(tx.repo_mut()).await?;
225
226 tx.edit(&new_wc_commit)?;
227 tx.finish(
228 ui,
229 format!(
230 "create initial working-copy commit in workspace {name}",
231 name = workspace_name.as_symbol()
232 ),
233 )
234 .await?;
235 Ok(())
236 }