Debian Codegraph @

cli/src/commands/git/colocation.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 std::io::ErrorKind;
16 use std::io::Write as _;
17
18 use itertools::Itertools as _;
19 use jj_lib::commit::Commit;
20 use jj_lib::file_util::IoResultExt as _;
21 use jj_lib::git;
22 use jj_lib::op_store::RefTarget;
23 use jj_lib::repo::Repo as _;
24
25 use crate::cli_util::CommandHelper;
26 use crate::cli_util::WorkspaceCommandHelper;
27 use crate::command_error::CommandError;
28 use crate::command_error::user_error;
29 use crate::command_error::user_error_with_message;
30 use crate::commands::git::maybe_add_gitignore;
31 use crate::git_util::is_colocated_git_workspace;
32 use crate::ui::Ui;
33
34 /// Show the current colocation status
35 #[derive(clap::Args, Clone, Debug)]
36 pub struct GitColocationStatusArgs {}
37
38 /// Convert into a colocated Jujutsu/Git repository
39 ///
40 /// This moves the underlying Git repository that is found inside the .jj
41 /// directory to the root of the Jujutsu workspace. This allows you to
42 /// use Git commands directly in the Jujutsu workspace.
43 #[derive(clap::Args, Clone, Debug)]
44 pub struct GitColocationEnableArgs {}
45
46 /// Convert into a non-colocated Jujutsu/Git repository
47 ///
48 /// This moves the Git repository that is at the root of the Jujutsu
49 /// workspace into the .jj directory. Once this is done you will no longer
50 /// be able to use Git commands directly in the Jujutsu workspace.
51 #[derive(clap::Args, Clone, Debug)]
52 pub struct GitColocationDisableArgs {}
53
54 /// Manage Jujutsu repository colocation with Git
55 #[derive(clap::Subcommand, Clone, Debug)]
56 pub enum GitColocationCommand {
57 Disable(GitColocationDisableArgs),
58 Enable(GitColocationEnableArgs),
59 Status(GitColocationStatusArgs),
60 }
61
62 pub async fn cmd_git_colocation(
63 ui: &mut Ui,
64 command: &CommandHelper,
65 subcommand: &GitColocationCommand,
66 ) -> Result<(), CommandError> {
67 match subcommand {
68 GitColocationCommand::Disable(args) => cmd_git_colocation_disable(ui, command, args).await,
69 GitColocationCommand::Enable(args) => cmd_git_colocation_enable(ui, command, args).await,
70 GitColocationCommand::Status(args) => cmd_git_colocation_status(ui, command, args).await,
71 }
72 }
73
74 /// Check that the repository supports colocation commands
75 /// which means that the repo is backed by Git and is a main workspace
76 fn workspace_supports_git_colocation_commands(
77 workspace_command: &WorkspaceCommandHelper,
78 ) -> Result<(), CommandError> {
79 // Check if backend is Git (will show an error otherwise)
80 git::get_git_backend(workspace_command.repo().store())?;
81
82 // Ensure that this is the main workspace
83 let repo_dir = workspace_command.workspace_root().join(".jj").join("repo");
84 if repo_dir.is_file() {
85 return Err(user_error(
86 "This command cannot be used in a non-main Jujutsu workspace",
87 ));
88 }
89 Ok(())
90 }
91
92 async fn cmd_git_colocation_status(
93 ui: &mut Ui,
94 command: &CommandHelper,
95 _args: &GitColocationStatusArgs,
96 ) -> Result<(), CommandError> {
97 let workspace_command = command.workspace_helper(ui).await?;
98
99 // Make sure that the workspace supports git colocation commands
100 workspace_supports_git_colocation_commands(&workspace_command)?;
101
102 let is_colocated = is_colocated_git_workspace(workspace_command.workspace())?;
103 let workspace_name = workspace_command.workspace_name();
104 let git_head = workspace_command.repo().view().git_head(workspace_name);
105
106 if is_colocated {
107 writeln!(ui.stdout(), "Workspace is currently colocated with Git.")?;
108 } else {
109 writeln!(
110 ui.stdout(),
111 "Workspace is currently not colocated with Git."
112 )?;
113 }
114
115 // git_head should be absent in non-colocated workspace, but print the
116 // actual status so we can debug problems.
117 writeln!(
118 ui.stdout(),
119 "Last imported/exported Git HEAD: {}",
120 git_head
121 .as_merge()
122 .iter()
123 .map(|maybe_id| match maybe_id {
124 Some(id) => id.to_string(),
125 None => "(none)".to_owned(),
126 })
127 .join(", ")
128 )?;
129
130 if is_colocated {
131 writeln!(
132 ui.hint_default(),
133 "To disable colocation, run: `jj git colocation disable`"
134 )?;
135 } else if !workspace_command
136 .repo_path()
137 .join("store")
138 .join("git")
139 .exists()
140 {
141 writeln!(
142 ui.hint_default(),
143 "Colocation cannot be enabled because the workspace is backed by an external Git \
144 repository."
145 )?;
146 } else {
147 writeln!(
148 ui.hint_default(),
149 "To enable colocation, run: `jj git colocation enable`"
150 )?;
151 }
152
153 Ok(())
154 }
155
156 async fn cmd_git_colocation_enable(
157 ui: &mut Ui,
158 command: &CommandHelper,
159 _args: &GitColocationEnableArgs,
160 ) -> Result<(), CommandError> {
161 let workspace_command = command.workspace_helper(ui).await?;
162
163 // Make sure that the workspace supports git colocation commands
164 workspace_supports_git_colocation_commands(&workspace_command)?;
165
166 // Then ensure that the workspace is not already colocated before proceeding
167 if is_colocated_git_workspace(workspace_command.workspace())? {
168 writeln!(ui.status(), "Workspace is already colocated with Git.")?;
169 return Ok(());
170 }
171
172 // And that it has a working copy (whose parent we'll use later to set the git
173 // HEAD)
174 let wc_commit_id = workspace_command
175 .get_wc_commit_id()
176 .ok_or_else(|| user_error("This command requires a working copy"))?
177 .clone();
178
179 let workspace_root = workspace_command.workspace_root();
180 let jj_repo_path = workspace_command.repo_path();
181 let git_store_path = jj_repo_path.join("store").join("git");
182 let git_target_path = jj_repo_path.join("store").join("git_target");
183 let dot_git_path = workspace_root.join(".git");
184
185 // Move the git repository from .jj/repo/store/git to .git
186 std::fs::rename(&git_store_path, &dot_git_path).map_err(|err| match err.kind() {
187 ErrorKind::AlreadyExists | ErrorKind::DirectoryNotEmpty => {
188 user_error("A .git directory already exists in the workspace root. Cannot colocate.")
189 }
190 // An external Git repository (e.g. created by `jj git init
191 // --git-repo=<path>`) isn't managed by jj and cannot be moved.
192 // workspace_supports_git_colocation_commands() already ensured that
193 // the backend is Git.
194 ErrorKind::NotFound => {
195 let git_backend = git::get_git_backend(workspace_command.repo().store()).unwrap();
196 user_error(format!(
197 "Cannot colocate a workspace backed by an external Git repository at {}",
198 git_backend.git_repo_path().display()
199 ))
200 }
201 _ => user_error_with_message(
202 "Failed to move Git repository from .jj/repo/store/git to workspace root directory.",
203 err,
204 ),
205 })?;
206
207 // Update the git_target file to point to the new location of the git repo
208 let git_target_content = "../../../.git";
209 std::fs::write(&git_target_path, git_target_content).context(git_target_path)?;
210
211 // Then we must make the Git repository non-bare
212 set_git_repo_bare(&dot_git_path, false)?;
213
214 // Reload the workspace command helper to ensure it picks up the changes
215 let mut workspace_command = reload_workspace_helper(ui, command, workspace_command).await?;
216
217 // Add a .jj/.gitignore file (if needed) to ensure that the colocated Git
218 // repository does not track Jujutsu's repository
219 maybe_add_gitignore(&workspace_command)?;
220
221 // Finally, update git HEAD to point to the working-copy commit's parent
222 let wc_commit = workspace_command
223 .repo()
224 .store()
225 .get_commit_async(&wc_commit_id)
226 .await?;
227 set_git_head_to_wc_parent(ui, &mut workspace_command, &wc_commit).await?;
228
229 writeln!(
230 ui.status(),
231 "Workspace successfully converted into a colocated Jujutsu/Git workspace."
232 )?;
233
234 Ok(())
235 }
236
237 async fn cmd_git_colocation_disable(
238 ui: &mut Ui,
239 command: &CommandHelper,
240 _args: &GitColocationDisableArgs,
241 ) -> Result<(), CommandError> {
242 let workspace_command = command.workspace_helper(ui).await?;
243
244 // Make sure that the repository supports git colocation commands
245 workspace_supports_git_colocation_commands(&workspace_command)?;
246
247 // Then ensure that the repo is colocated before proceeding
248 if !is_colocated_git_workspace(workspace_command.workspace())? {
249 writeln!(ui.status(), "Workspace is already not colocated with Git.")?;
250 return Ok(());
251 }
252
253 let workspace_root = workspace_command.workspace_root();
254 let dot_jj_path = workspace_root.join(".jj");
255 let git_store_path = workspace_command.repo_path().join("store").join("git");
256 let git_target_path = workspace_command
257 .repo_path()
258 .join("store")
259 .join("git_target");
260 let dot_git_path = workspace_root.join(".git");
261 let jj_gitignore_path = dot_jj_path.join(".gitignore");
262
263 // Move the Git repository from .git into .jj/repo/store/git
264 std::fs::rename(&dot_git_path, &git_store_path).map_err(|e| {
265 user_error_with_message("Failed to move Git repository to .jj/repo/store/git", e)
266 })?;
267
268 // Make the Git repository bare
269 set_git_repo_bare(&git_store_path, true)?;
270
271 // Update the git_target file to point to the internal git store
272 let git_target_content = "git";
273 std::fs::write(&git_target_path, git_target_content).context(&git_target_path)?;
274
275 // Remove the .jj/.gitignore file if it exists
276 std::fs::remove_file(&jj_gitignore_path).ok();
277
278 // Reload the workspace command helper to ensure it picks up the changes
279 let mut workspace_command = reload_workspace_helper(ui, command, workspace_command).await?;
280
281 // And finally, remove the git HEAD reference
282 remove_git_head(ui, &mut workspace_command).await?;
283
284 writeln!(
285 ui.status(),
286 "Workspace successfully converted into a non-colocated Jujutsu/Git workspace."
287 )?;
288
289 Ok(())
290 }
291
292 /// Set the Git repository at `path` to be bare or non-bare
293 fn set_git_repo_bare(path: &std::path::Path, bare: bool) -> Result<(), CommandError> {
294 let bare_str = if bare { "true" } else { "false" };
295 let config_path = path.join("config");
296 let mut config_file =
297 gix::config::File::from_path_no_includes(config_path.clone(), gix::config::Source::Local)
298 .map_err(|err| user_error_with_message("Failed to open Git config file.", err))?;
299
300 config_file
301 .set_raw_value("core.bare", bare_str)
302 .map_err(|err| {
303 user_error_with_message(
304 format!("Failed to set core.bare to {bare_str} in Git config."),
305 err,
306 )
307 })?;
308
309 git::save_git_config(&config_file).map_err(|err| {
310 user_error_with_message(
311 format!(
312 "Failed to write to Git config file at {}.",
313 config_path.display()
314 ),
315 err,
316 )
317 })?;
318 Ok(())
319 }
320
321 /// Set the git HEAD to the working copy commit's parent
322 async fn set_git_head_to_wc_parent(
323 ui: &mut Ui,
324 workspace_command: &mut WorkspaceCommandHelper,
325 wc_commit: &Commit,
326 ) -> Result<(), CommandError> {
327 let workspace_name = workspace_command.workspace_name().to_owned();
328 let workspace_root = workspace_command.workspace_root().to_owned();
329 let mut tx = workspace_command.start_transaction();
330 git::reset_head(tx.repo_mut(), &workspace_name, &workspace_root, wc_commit).await?;
331 if tx.repo().has_changes() {
332 tx.finish(ui, "set git head to working copy parent").await?;
333 }
334 Ok(())
335 }
336
337 /// Remove the git HEAD reference
338 async fn remove_git_head(
339 ui: &mut Ui,
340 workspace_command: &mut WorkspaceCommandHelper,
341 ) -> Result<(), CommandError> {
342 let workspace_name = workspace_command.workspace_name().to_owned();
343 let mut tx = workspace_command.start_transaction();
344 tx.repo_mut()
345 .set_git_head_target(&workspace_name, RefTarget::absent());
346 if tx.repo().has_changes() {
347 tx.finish(ui, "remove git head reference").await?;
348 }
349 Ok(())
350 }
351
352 /// Gets an up to date workspace helper to pick up changes made to the repo
353 async fn reload_workspace_helper(
354 ui: &mut Ui,
355 command: &CommandHelper,
356 workspace_command: WorkspaceCommandHelper,
357 ) -> Result<WorkspaceCommandHelper, CommandError> {
358 let workspace = command.load_workspace_at(
359 workspace_command.workspace_root(),
360 workspace_command.settings(),
361 )?;
362 let op = workspace
363 .repo_loader()
364 .load_operation(workspace_command.repo().op_id())
365 .await?;
366 let repo = workspace.repo_loader().load_at(&op).await?;
367 let workspace_command = command.for_workable_repo(ui, workspace, repo)?;
368 Ok(workspace_command)
369 }