| 1 |
// Copyright 2020-2023 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; |
| 16 |
use std::io::Write as _; |
| 17 |
use std::path::Path; |
| 18 |
use std::path::PathBuf; |
| 19 |
use std::sync::Arc; |
| 20 |
|
| 21 |
use indoc::writedoc; |
| 22 |
use itertools::Itertools as _; |
| 23 |
use jj_lib::file_util; |
| 24 |
use jj_lib::git; |
| 25 |
use jj_lib::git::GitImportOptions; |
| 26 |
use jj_lib::git::GitRefKind; |
| 27 |
use jj_lib::git::GitSettings; |
| 28 |
use jj_lib::git::parse_git_ref; |
| 29 |
use jj_lib::repo::ReadonlyRepo; |
| 30 |
use jj_lib::repo::Repo as _; |
| 31 |
use jj_lib::view::View; |
| 32 |
use jj_lib::workspace::Workspace; |
| 33 |
|
| 34 |
use super::ObjectHash; |
| 35 |
use super::RepoPresets; |
| 36 |
use super::write_repo_presets; |
| 37 |
use crate::cli_util::CommandHelper; |
| 38 |
use crate::cli_util::shell_quote; |
| 39 |
use crate::cli_util::start_repo_transaction; |
| 40 |
use crate::command_error::CommandError; |
| 41 |
use crate::command_error::cli_error; |
| 42 |
use crate::command_error::internal_error; |
| 43 |
use crate::command_error::user_error; |
| 44 |
use crate::command_error::user_error_with_message; |
| 45 |
use crate::commands::git::maybe_add_gitignore; |
| 46 |
use crate::config::ConfigEnv; |
| 47 |
use crate::formatter::FormatterExt as _; |
| 48 |
use crate::git_util::is_colocated_git_workspace; |
| 49 |
use crate::git_util::load_git_import_options; |
| 50 |
use crate::git_util::print_git_export_stats; |
| 51 |
use crate::git_util::print_git_import_stats_summary; |
| 52 |
use crate::ui::Ui; |
| 53 |
|
| 54 |
/// Create a new Git backed repo. |
| 55 |
#[derive(clap::Args, Clone, Debug)] |
| 56 |
pub struct GitInitArgs { |
| 57 |
/// The destination directory where the `jj` repo will be created. |
| 58 |
/// If the directory does not exist, it will be created. |
| 59 |
/// If no directory is given, the current directory is used. |
| 60 |
/// |
| 61 |
/// By default the `git` repo is under `$destination/.jj` |
| 62 |
#[arg(default_value = ".", value_hint = clap::ValueHint::DirPath)] |
| 63 |
destination: String, |
| 64 |
|
| 65 |
/// Colocate the Jujutsu repo with the git repo |
| 66 |
/// |
| 67 |
/// Specifies that the `jj` repo should also be a valid `git` repo, allowing |
| 68 |
/// the use of both `jj` and `git` commands in the same directory. |
| 69 |
/// |
| 70 |
/// The repository will contain a `.git` dir in the top-level. Regular Git |
| 71 |
/// tools will be able to operate on the repo. |
| 72 |
/// |
| 73 |
/// **This is the default**, and this option has no effect, unless the |
| 74 |
/// [git.colocate config] is set to `false`. |
| 75 |
/// |
| 76 |
/// This option is mutually exclusive with `--git-repo`. |
| 77 |
/// |
| 78 |
/// [git.colocate config]: |
| 79 |
/// https://docs.jj-vcs.dev/latest/config/#default-colocation |
| 80 |
#[arg(long, conflicts_with = "git_repo")] |
| 81 |
colocate: bool, |
| 82 |
|
| 83 |
/// Disable colocation of the Jujutsu repo with the git repo |
| 84 |
/// |
| 85 |
/// Prevent Git tools that are unaware of `jj` and regular Git commands from |
| 86 |
/// operating on the repo. The Git repository that stores most of the repo |
| 87 |
/// data will be hidden inside a sub-directory of the `.jj` directory. |
| 88 |
/// |
| 89 |
/// See [colocation docs] for some minor advantages of non-colocated |
| 90 |
/// workspaces. |
| 91 |
/// |
| 92 |
/// [colocation docs]: |
| 93 |
/// https://docs.jj-vcs.dev/latest/git-compatibility/#colocated-jujutsugit-repos |
| 94 |
#[arg(long, conflicts_with = "colocate")] |
| 95 |
no_colocate: bool, |
| 96 |
|
| 97 |
/// Object hash algorithm for the newly created Git repository. |
| 98 |
/// |
| 99 |
/// Corresponds to `git init`'s `--object-format` option. If not given, the |
| 100 |
/// [git.object-hash config] determines the default value. |
| 101 |
/// |
| 102 |
/// Note that the object hash cannot currently be changed for an existing |
| 103 |
/// repo, and not all code forges support SHA-256 repositories yet. See also |
| 104 |
/// Git's [hash-function-transition] document for an in-depth explanation of |
| 105 |
/// the migration towards stronger hash functions. |
| 106 |
/// |
| 107 |
/// [git.object-hash config]: |
| 108 |
/// https://docs.jj-vcs.dev/latest/config/#default-object-hash-format |
| 109 |
/// [hash-function-transition]: |
| 110 |
/// https://git-scm.com/docs/hash-function-transition |
| 111 |
#[arg(long, value_enum, conflicts_with = "git_repo")] |
| 112 |
object_hash: Option<ObjectHash>, |
| 113 |
|
| 114 |
/// Specifies a path to an **existing** git repository to be |
| 115 |
/// used as the backing git repo for the newly created `jj` repo. |
| 116 |
/// |
| 117 |
/// If the specified `--git-repo` path happens to be the same as |
| 118 |
/// the `jj` repo path (both .jj and .git directories are in the |
| 119 |
/// same working directory), then both `jj` and `git` commands |
| 120 |
/// will work on the same repo. This is called a colocated workspace. |
| 121 |
/// |
| 122 |
/// This option is mutually exclusive with `--colocate`, and so if passed, |
| 123 |
/// turns colocation off. |
| 124 |
#[arg( |
| 125 |
long, |
| 126 |
conflicts_with_all = ["colocate", "object_hash"], |
| 127 |
value_hint = clap::ValueHint::DirPath, |
| 128 |
)] |
| 129 |
git_repo: Option<String>, |
| 130 |
} |
| 131 |
|
| 132 |
pub async fn cmd_git_init( |
| 133 |
ui: &mut Ui, |
| 134 |
command: &CommandHelper, |
| 135 |
args: &GitInitArgs, |
| 136 |
) -> Result<(), CommandError> { |
| 137 |
if command.global_args().no_integrate_operation { |
| 138 |
return Err(cli_error("--no-integrate-operation is not respected")); |
| 139 |
} |
| 140 |
if command.global_args().ignore_working_copy { |
| 141 |
return Err(cli_error("--ignore-working-copy is not respected")); |
| 142 |
} |
| 143 |
if command.global_args().at_operation.is_some() { |
| 144 |
return Err(cli_error("--at-op is not respected")); |
| 145 |
} |
| 146 |
let cwd = command.cwd(); |
| 147 |
let wc_path = cwd.join(&args.destination); |
| 148 |
let wc_path = file_util::create_or_reuse_dir(&wc_path) |
| 149 |
.and_then(|_| dunce::canonicalize(wc_path)) |
| 150 |
.map_err(|e| user_error_with_message("Failed to create workspace", e))?; |
| 151 |
|
| 152 |
let colocate = if command.settings().get_bool("git.colocate")? { |
| 153 |
!args.no_colocate |
| 154 |
} else { |
| 155 |
args.colocate |
| 156 |
}; |
| 157 |
|
| 158 |
let object_hash = args.object_hash.map_or_else( |
| 159 |
|| command.settings().get::<ObjectHash>("git.object-hash"), |
| 160 |
Result::Ok, |
| 161 |
)?; |
| 162 |
do_init( |
| 163 |
ui, |
| 164 |
command, |
| 165 |
&wc_path, |
| 166 |
colocate, |
| 167 |
object_hash.into(), |
| 168 |
args.git_repo.as_deref(), |
| 169 |
) |
| 170 |
.await?; |
| 171 |
|
| 172 |
let relative_wc_path = file_util::relative_path(cwd, &wc_path); |
| 173 |
writeln!( |
| 174 |
ui.status(), |
| 175 |
r#"Initialized repo in "{}""#, |
| 176 |
relative_wc_path.display() |
| 177 |
)?; |
| 178 |
|
| 179 |
Ok(()) |
| 180 |
} |
| 181 |
|
| 182 |
async fn do_init( |
| 183 |
ui: &mut Ui, |
| 184 |
command: &CommandHelper, |
| 185 |
workspace_root: &Path, |
| 186 |
colocate: bool, |
| 187 |
object_hash: gix::hash::Kind, |
| 188 |
git_repo: Option<&str>, |
| 189 |
) -> Result<(), CommandError> { |
| 190 |
#[derive(Clone, Debug)] |
| 191 |
enum GitInitMode { |
| 192 |
Colocate, |
| 193 |
External(PathBuf), |
| 194 |
Internal, |
| 195 |
} |
| 196 |
|
| 197 |
let colocated_git_repo_path = workspace_root.join(".git"); |
| 198 |
let init_mode = if let Some(path_str) = git_repo { |
| 199 |
let mut git_repo_path = command.cwd().join(path_str); |
| 200 |
if !git_repo_path.ends_with(".git") { |
| 201 |
git_repo_path.push(".git"); |
| 202 |
// Undo if .git doesn't exist - likely a bare repo. |
| 203 |
if !git_repo_path.exists() { |
| 204 |
git_repo_path.pop(); |
| 205 |
} |
| 206 |
} |
| 207 |
GitInitMode::External(git_repo_path) |
| 208 |
} else if colocate { |
| 209 |
if colocated_git_repo_path.exists() { |
| 210 |
// Refuse to colocate inside a Git worktree |
| 211 |
if is_linked_git_worktree(workspace_root) { |
| 212 |
return Err( |
| 213 |
user_error("Cannot create a colocated jj repo inside a Git worktree.").hinted( |
| 214 |
"Run `jj git init` in the main Git repository instead, or use `jj \ |
| 215 |
workspace add` to create additional jj workspaces.", |
| 216 |
), |
| 217 |
); |
| 218 |
} |
| 219 |
GitInitMode::External(colocated_git_repo_path) |
| 220 |
} else { |
| 221 |
GitInitMode::Colocate |
| 222 |
} |
| 223 |
} else { |
| 224 |
if colocated_git_repo_path.exists() { |
| 225 |
return Err(user_error( |
| 226 |
"Did not create a jj repo because there is an existing Git repo in this directory.", |
| 227 |
) |
| 228 |
.hinted( |
| 229 |
"To create a repo backed by the existing Git repo, run `jj git init --colocate` \ |
| 230 |
instead.", |
| 231 |
)); |
| 232 |
} |
| 233 |
GitInitMode::Internal |
| 234 |
}; |
| 235 |
|
| 236 |
let (settings, config_env) = command.settings_for_new_workspace(ui, workspace_root)?; |
| 237 |
match &init_mode { |
| 238 |
GitInitMode::Colocate => { |
| 239 |
let (workspace, repo) = |
| 240 |
Workspace::init_colocated_git(&settings, workspace_root, object_hash).await?; |
| 241 |
let workspace_command = command.for_workable_repo(ui, workspace, repo)?; |
| 242 |
maybe_add_gitignore(&workspace_command)?; |
| 243 |
} |
| 244 |
GitInitMode::External(git_repo_path) => { |
| 245 |
let (workspace, repo) = |
| 246 |
Workspace::init_external_git(&settings, workspace_root, git_repo_path).await?; |
| 247 |
// Import refs first so all the reachable commits are indexed in |
| 248 |
// chronological order. |
| 249 |
let colocated = is_colocated_git_workspace(&workspace)?; |
| 250 |
let repo = |
| 251 |
init_git_refs(ui, repo, command.string_args(), &workspace, colocated).await?; |
| 252 |
let mut workspace_command = command.for_workable_repo(ui, workspace, repo)?; |
| 253 |
maybe_add_gitignore(&workspace_command)?; |
| 254 |
workspace_command.maybe_snapshot(ui).await?; |
| 255 |
maybe_set_repository_level_trunk_alias( |
| 256 |
ui, |
| 257 |
&git::get_git_repo(workspace_command.repo().store())?, |
| 258 |
&config_env, |
| 259 |
)?; |
| 260 |
if !workspace_command.working_copy_shared_with_git() { |
| 261 |
let mut tx = workspace_command.start_transaction(); |
| 262 |
if let Some(git_head_commit) = git::import_head_commit(tx.repo_mut()).await? { |
| 263 |
tx.check_out(&git_head_commit)?; |
| 264 |
} |
| 265 |
if tx.repo().has_changes() { |
| 266 |
tx.finish(ui, "import git head").await?; |
| 267 |
} |
| 268 |
} |
| 269 |
print_trackable_remote_bookmarks(ui, workspace_command.repo().view())?; |
| 270 |
} |
| 271 |
GitInitMode::Internal => { |
| 272 |
Workspace::init_internal_git(&settings, workspace_root, object_hash).await?; |
| 273 |
} |
| 274 |
} |
| 275 |
Ok(()) |
| 276 |
} |
| 277 |
|
| 278 |
/// Imports branches and tags from the underlying Git repo, exports changes if |
| 279 |
/// the repo is colocated. |
| 280 |
/// |
| 281 |
/// This is similar to `WorkspaceCommandHelper::import_git_refs()`, but never |
| 282 |
/// moves the Git HEAD to the working copy parent. |
| 283 |
async fn init_git_refs( |
| 284 |
ui: &mut Ui, |
| 285 |
repo: Arc<ReadonlyRepo>, |
| 286 |
string_args: &[String], |
| 287 |
workspace: &Workspace, |
| 288 |
colocated: bool, |
| 289 |
) -> Result<Arc<ReadonlyRepo>, CommandError> { |
| 290 |
let git_settings = GitSettings::from_settings(repo.settings())?; |
| 291 |
let remote_settings = repo.settings().remote_settings()?; |
| 292 |
let import_options = GitImportOptions { |
| 293 |
// There should be no old refs to abandon, but enforce it. |
| 294 |
abandon_unreachable_commits: false, |
| 295 |
// There may be a large number of new commits. Don't record synthetic |
| 296 |
// predecessors. |
| 297 |
record_synthetic_predecessors: false, |
| 298 |
..load_git_import_options(ui, &git_settings, &remote_settings)? |
| 299 |
}; |
| 300 |
let mut tx = start_repo_transaction(&repo, workspace.workspace_name(), string_args); |
| 301 |
let stats = git::import_refs(tx.repo_mut(), &import_options).await?; |
| 302 |
print_git_import_stats_summary(ui, &stats)?; |
| 303 |
if !tx.repo().has_changes() { |
| 304 |
return Ok(repo); |
| 305 |
} |
| 306 |
if colocated { |
| 307 |
// If remotes.<name>.auto-track-bookmarks is set, local bookmarks could |
| 308 |
// be created for the imported remote branches. |
| 309 |
let stats = git::export_refs(tx.repo_mut())?; |
| 310 |
print_git_export_stats(ui, &stats)?; |
| 311 |
} |
| 312 |
let repo = tx.commit("import git refs").await?; |
| 313 |
writeln!( |
| 314 |
ui.status(), |
| 315 |
"Done importing changes from the underlying Git repo." |
| 316 |
)?; |
| 317 |
Ok(repo) |
| 318 |
} |
| 319 |
|
| 320 |
// Set repository level `trunk()` alias to the default branch. |
| 321 |
// Checks "upstream" first, then "origin" as fallback. |
| 322 |
pub fn maybe_set_repository_level_trunk_alias( |
| 323 |
ui: &Ui, |
| 324 |
git_repo: &gix::Repository, |
| 325 |
config_env: &ConfigEnv, |
| 326 |
) -> Result<(), CommandError> { |
| 327 |
// Try "upstream" first, then fall back to "origin" |
| 328 |
for remote in ["upstream", "origin"] { |
| 329 |
let ref_name = format!("refs/remotes/{remote}/HEAD"); |
| 330 |
if let Some(reference) = git_repo |
| 331 |
.try_find_reference(&ref_name) |
| 332 |
.map_err(internal_error)? |
| 333 |
{ |
| 334 |
// Found a HEAD reference for this remote. Even if we can't parse it, |
| 335 |
// we should stop here and not try other remotes because it doesn't |
| 336 |
// really make sense if "origin" were to be set as the default if we |
| 337 |
// know "upstream" exists. |
| 338 |
if let Some(reference_name) = reference.target().try_name() |
| 339 |
&& let Some((GitRefKind::Bookmark, symbol)) = |
| 340 |
str::from_utf8(reference_name.as_bstr()) |
| 341 |
.ok() |
| 342 |
.and_then(|name| parse_git_ref(name.as_ref())) |
| 343 |
{ |
| 344 |
// TODO: Can we assume the symbolic target points to the same remote? |
| 345 |
let symbol = symbol.name.to_remote_symbol(remote.as_ref()); |
| 346 |
write_repo_presets( |
| 347 |
ui, |
| 348 |
config_env, |
| 349 |
RepoPresets { |
| 350 |
remote: remote.as_ref(), |
| 351 |
fetch_bookmarks: None, |
| 352 |
fetch_tags: None, |
| 353 |
trunk: Some(symbol), |
| 354 |
}, |
| 355 |
)?; |
| 356 |
} |
| 357 |
return Ok(()); |
| 358 |
} |
| 359 |
} |
| 360 |
|
| 361 |
Ok(()) |
| 362 |
} |
| 363 |
|
| 364 |
fn print_trackable_remote_bookmarks(ui: &Ui, view: &View) -> io::Result<()> { |
| 365 |
let remote_bookmark_symbols = view |
| 366 |
.bookmarks() |
| 367 |
.filter(|(_, bookmark_target)| bookmark_target.local_target.is_present()) |
| 368 |
.flat_map(|(name, bookmark_target)| { |
| 369 |
bookmark_target |
| 370 |
.remote_refs |
| 371 |
.into_iter() |
| 372 |
.filter(|&(_, remote_ref)| !remote_ref.is_tracked()) |
| 373 |
.map(move |(remote, _)| name.to_remote_symbol(remote)) |
| 374 |
}) |
| 375 |
.collect_vec(); |
| 376 |
if remote_bookmark_symbols.is_empty() { |
| 377 |
return Ok(()); |
| 378 |
} |
| 379 |
|
| 380 |
if let Some(mut formatter) = ui.status_formatter() { |
| 381 |
writeln!( |
| 382 |
formatter.labeled("hint").with_heading("Hint: "), |
| 383 |
"The following remote bookmarks aren't associated with the existing local bookmarks:" |
| 384 |
)?; |
| 385 |
for symbol in &remote_bookmark_symbols { |
| 386 |
write!(formatter, " ")?; |
| 387 |
writeln!(formatter.labeled("bookmark"), "{symbol}")?; |
| 388 |
} |
| 389 |
writedoc!( |
| 390 |
formatter.labeled("hint").with_heading("Hint: "), |
| 391 |
" |
| 392 |
Run the following command to keep local bookmarks updated on future pulls: |
| 393 |
jj bookmark track {syms} |
| 394 |
", |
| 395 |
syms = remote_bookmark_symbols |
| 396 |
.iter() |
| 397 |
.map(|s| shell_quote(&s.to_string()).into_owned()) |
| 398 |
.join(" ") |
| 399 |
)?; |
| 400 |
} |
| 401 |
Ok(()) |
| 402 |
} |
| 403 |
|
| 404 |
/// Returns `true` if the path is inside a linked Git worktree. |
| 405 |
fn is_linked_git_worktree(workspace_root: &Path) -> bool { |
| 406 |
let Ok(repo) = gix::open(workspace_root) else { |
| 407 |
return false; |
| 408 |
}; |
| 409 |
// In linked worktrees, git_dir points to .git/worktrees/<name> while |
| 410 |
// common_dir points to the main .git directory |
| 411 |
repo.git_dir() != repo.common_dir() |
| 412 |
} |