| 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::fs; |
| 16 |
use std::io; |
| 17 |
use std::io::Write as _; |
| 18 |
use std::num::NonZeroU32; |
| 19 |
use std::path::Path; |
| 20 |
|
| 21 |
use itertools::Itertools as _; |
| 22 |
use jj_lib::file_util; |
| 23 |
use jj_lib::git; |
| 24 |
use jj_lib::git::GitFetch; |
| 25 |
use jj_lib::git::GitFetchRefExpression; |
| 26 |
use jj_lib::git::GitImportOptions; |
| 27 |
use jj_lib::git::GitSettings; |
| 28 |
use jj_lib::git::expand_fetch_refspecs; |
| 29 |
use jj_lib::ref_name::RefName; |
| 30 |
use jj_lib::ref_name::RefNameBuf; |
| 31 |
use jj_lib::ref_name::RemoteName; |
| 32 |
use jj_lib::ref_name::RemoteNameBuf; |
| 33 |
use jj_lib::repo::Repo as _; |
| 34 |
use jj_lib::str_util::StringExpression; |
| 35 |
use jj_lib::workspace::Workspace; |
| 36 |
|
| 37 |
use super::ObjectHash; |
| 38 |
use super::RepoPresets; |
| 39 |
use super::write_repo_presets; |
| 40 |
use crate::cli_util::CommandHelper; |
| 41 |
use crate::cli_util::WorkspaceCommandHelper; |
| 42 |
use crate::command_error::CommandError; |
| 43 |
use crate::command_error::cli_error; |
| 44 |
use crate::command_error::user_error; |
| 45 |
use crate::command_error::user_error_with_message; |
| 46 |
use crate::commands::git::maybe_add_gitignore; |
| 47 |
use crate::config::ConfigEnv; |
| 48 |
use crate::git_util::GitSubprocessUi; |
| 49 |
use crate::git_util::absolute_git_url; |
| 50 |
use crate::git_util::load_git_import_options; |
| 51 |
use crate::git_util::print_git_import_stats; |
| 52 |
use crate::revset_util::parse_remote_fetch_bookmarks; |
| 53 |
use crate::revset_util::parse_remote_fetch_tags; |
| 54 |
use crate::revset_util::parse_union_name_patterns; |
| 55 |
use crate::ui::Ui; |
| 56 |
|
| 57 |
/// Create a new repo backed by a clone of a Git repo |
| 58 |
#[derive(clap::Args, Clone, Debug)] |
| 59 |
pub struct GitCloneArgs { |
| 60 |
/// URL or path of the Git repo to clone |
| 61 |
/// |
| 62 |
/// Local path will be resolved to absolute form. |
| 63 |
#[arg(value_hint = clap::ValueHint::Url)] |
| 64 |
source: String, |
| 65 |
|
| 66 |
/// Specifies the target directory for the Jujutsu repository clone. |
| 67 |
/// If not provided, defaults to a directory named after the last component |
| 68 |
/// of the source URL. The full directory path will be created if it |
| 69 |
/// doesn't exist. |
| 70 |
#[arg(value_hint = clap::ValueHint::DirPath)] |
| 71 |
destination: Option<String>, |
| 72 |
|
| 73 |
/// Name of the newly created remote |
| 74 |
#[arg(long = "remote", default_value = "origin")] |
| 75 |
remote_name: RemoteNameBuf, |
| 76 |
|
| 77 |
/// Colocate the Jujutsu repo with the git repo |
| 78 |
/// |
| 79 |
/// Specifies that the `jj` repo should also be a valid `git` repo, allowing |
| 80 |
/// the use of both `jj` and `git` commands in the same directory. |
| 81 |
/// |
| 82 |
/// The repository will contain a `.git` dir in the top-level. Regular Git |
| 83 |
/// tools will be able to operate on the repo. |
| 84 |
/// |
| 85 |
/// **This is the default**, and this option has no effect, unless the |
| 86 |
/// [git.colocate config] is set to `false`. |
| 87 |
/// |
| 88 |
/// [git.colocate config]: |
| 89 |
/// https://docs.jj-vcs.dev/latest/config/#default-colocation |
| 90 |
#[arg(long)] |
| 91 |
colocate: bool, |
| 92 |
|
| 93 |
/// Disable colocation of the Jujutsu repo with the git repo |
| 94 |
/// |
| 95 |
/// Prevent Git tools that are unaware of `jj` and regular Git commands from |
| 96 |
/// operating on the repo. The Git repository that stores most of the repo |
| 97 |
/// data will be hidden inside a sub-directory of the `.jj` directory. |
| 98 |
/// |
| 99 |
/// See [colocation docs] for some minor advantages of non-colocated |
| 100 |
/// workspaces. |
| 101 |
/// |
| 102 |
/// [colocation docs]: |
| 103 |
/// https://docs.jj-vcs.dev/latest/git-compatibility/#colocated-jujutsugit-repos |
| 104 |
#[arg(long, conflicts_with = "colocate")] |
| 105 |
no_colocate: bool, |
| 106 |
|
| 107 |
/// Create a shallow clone of the given depth |
| 108 |
#[arg(long)] |
| 109 |
depth: Option<NonZeroU32>, |
| 110 |
|
| 111 |
/// Name of the branch to fetch and use as the parent of the working-copy |
| 112 |
/// change (can be repeated) |
| 113 |
/// |
| 114 |
/// If not present, all branches are fetched and the repository's default |
| 115 |
/// branch is used as parent of the working-copy change. |
| 116 |
/// |
| 117 |
/// By default, the specified pattern matches branch names with glob syntax, |
| 118 |
/// but only `*` is expanded. Other wildcard characters such as `?` are |
| 119 |
/// *not* supported. Patterns can be repeated or combined with [logical |
| 120 |
/// operators] to specify multiple branches, but only union and negative |
| 121 |
/// intersection are supported. If there are multiple matching branches, the |
| 122 |
/// first exact branch name is used as the working-copy parent. |
| 123 |
/// |
| 124 |
/// Examples: `push-*`, `(push-* | foo/*) ~ foo/unwanted` |
| 125 |
/// |
| 126 |
/// [logical operators]: |
| 127 |
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns |
| 128 |
#[arg(long = "branch", short, alias = "bookmark", value_name = "BRANCH")] |
| 129 |
branches: Option<Vec<String>>, |
| 130 |
|
| 131 |
/// Fetch only some of the tags (can be repeated) |
| 132 |
/// |
| 133 |
/// By default, the specified pattern matches tag names with glob syntax, |
| 134 |
/// but only `*` is expanded. Other wildcard characters such as `?` are |
| 135 |
/// *not* supported. Patterns can be repeated or combined with [logical |
| 136 |
/// operators] to specify multiple tags, but only union and negative |
| 137 |
/// intersection are supported. |
| 138 |
/// |
| 139 |
/// [logical operators]: |
| 140 |
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns |
| 141 |
#[arg(long = "tag", short, value_name = "TAG")] |
| 142 |
tags: Option<Vec<String>>, |
| 143 |
|
| 144 |
/// Object hash algorithm for the local Git repository. |
| 145 |
/// |
| 146 |
/// *Must* match the remote's hash algorithm, otherwise the operation will |
| 147 |
/// fail. Most existing repositories today still use the classic SHA-1 |
| 148 |
/// format, which is also the default if not configured otherwise by the |
| 149 |
/// [git.object-hash config]. |
| 150 |
/// |
| 151 |
/// See also Git's [hash-function-transition] document for an in-depth |
| 152 |
/// explanation of the migration towards stronger hash functions. |
| 153 |
/// |
| 154 |
/// [git.object-hash config]: |
| 155 |
/// https://docs.jj-vcs.dev/latest/config/#default-object-hash-format |
| 156 |
/// [hash-function-transition]: |
| 157 |
/// https://git-scm.com/docs/hash-function-transition |
| 158 |
#[arg(long, value_enum)] |
| 159 |
object_hash: Option<ObjectHash>, |
| 160 |
} |
| 161 |
|
| 162 |
fn clone_destination_for_source(source: &str) -> Option<&str> { |
| 163 |
let destination = source.strip_suffix(".git").unwrap_or(source); |
| 164 |
let destination = destination.strip_suffix('/').unwrap_or(destination); |
| 165 |
destination |
| 166 |
.rsplit_once(&['/', '\\', ':'][..]) |
| 167 |
.map(|(_, name)| name) |
| 168 |
} |
| 169 |
|
| 170 |
pub async fn cmd_git_clone( |
| 171 |
ui: &mut Ui, |
| 172 |
command: &CommandHelper, |
| 173 |
args: &GitCloneArgs, |
| 174 |
) -> Result<(), CommandError> { |
| 175 |
let remote_name = &args.remote_name; |
| 176 |
if command.global_args().at_operation.is_some() { |
| 177 |
return Err(cli_error("--at-op is not respected")); |
| 178 |
} |
| 179 |
let source = absolute_git_url(command.cwd(), &args.source)?; |
| 180 |
let wc_path_str = args |
| 181 |
.destination |
| 182 |
.as_deref() |
| 183 |
.or_else(|| clone_destination_for_source(&source)) |
| 184 |
.ok_or_else(|| user_error("No destination specified and wasn't able to guess it"))?; |
| 185 |
let wc_path = command.cwd().join(wc_path_str); |
| 186 |
|
| 187 |
let wc_path_existed = wc_path.exists(); |
| 188 |
if wc_path_existed && !file_util::is_empty_dir(&wc_path)? { |
| 189 |
return Err(user_error( |
| 190 |
"Destination path exists and is not an empty directory", |
| 191 |
)); |
| 192 |
} |
| 193 |
|
| 194 |
// will create a tree dir in case if was deleted after last check |
| 195 |
fs::create_dir_all(&wc_path) |
| 196 |
.map_err(|err| user_error_with_message(format!("Failed to create {wc_path_str}"), err))?; |
| 197 |
|
| 198 |
let colocate = if command.settings().get_bool("git.colocate")? { |
| 199 |
!args.no_colocate |
| 200 |
} else { |
| 201 |
args.colocate |
| 202 |
}; |
| 203 |
let is_specific = args.branches.is_some() || args.tags.is_some(); |
| 204 |
let specific_bookmark_expr = match &args.branches { |
| 205 |
Some(texts) => Some(parse_union_name_patterns(ui, texts)?), |
| 206 |
None => is_specific.then(StringExpression::none), |
| 207 |
}; |
| 208 |
let specific_tag_expr = match &args.tags { |
| 209 |
Some(texts) => Some(parse_union_name_patterns(ui, texts)?), |
| 210 |
None => is_specific.then(StringExpression::none), |
| 211 |
}; |
| 212 |
let object_hash = args.object_hash.map_or_else( |
| 213 |
|| command.settings().get::<ObjectHash>("git.object-hash"), |
| 214 |
Result::Ok, |
| 215 |
)?; |
| 216 |
|
| 217 |
// Canonicalize because fs::remove_dir_all() doesn't seem to like e.g. |
| 218 |
// `/some/path/.` |
| 219 |
let canonical_wc_path = dunce::canonicalize(&wc_path) |
| 220 |
.map_err(|err| user_error_with_message(format!("Failed to create {wc_path_str}"), err))?; |
| 221 |
|
| 222 |
let clone_result: Result<_, CommandError> = async { |
| 223 |
let (workspace_command, config_env) = init_workspace( |
| 224 |
ui, |
| 225 |
command, |
| 226 |
&canonical_wc_path, |
| 227 |
colocate, |
| 228 |
object_hash.into(), |
| 229 |
) |
| 230 |
.await?; |
| 231 |
let remote_settings = workspace_command.settings().remote_settings()?; |
| 232 |
let bookmark = if let Some(expr) = &specific_bookmark_expr { |
| 233 |
expr.clone() |
| 234 |
} else if let Some(expr) = parse_remote_fetch_bookmarks(ui, &remote_settings, remote_name)? |
| 235 |
{ |
| 236 |
expr |
| 237 |
} else { |
| 238 |
StringExpression::all() |
| 239 |
}; |
| 240 |
let tag = if let Some(expr) = specific_tag_expr { |
| 241 |
expr |
| 242 |
} else if let Some(expr) = parse_remote_fetch_tags(ui, &remote_settings, remote_name)? { |
| 243 |
expr |
| 244 |
} else { |
| 245 |
StringExpression::all() |
| 246 |
}; |
| 247 |
let mut workspace_command = |
| 248 |
configure_remote(ui, command, workspace_command, remote_name, &source).await?; |
| 249 |
let ref_expr = GitFetchRefExpression { bookmark, tag }; |
| 250 |
let default_branch = fetch_new_remote( |
| 251 |
ui, |
| 252 |
&mut workspace_command, |
| 253 |
remote_name, |
| 254 |
&ref_expr, |
| 255 |
args.depth, |
| 256 |
) |
| 257 |
.await?; |
| 258 |
Ok((workspace_command, default_branch, config_env)) |
| 259 |
} |
| 260 |
.await; |
| 261 |
if clone_result.is_err() { |
| 262 |
let clean_up_dirs = || -> io::Result<()> { |
| 263 |
let sub_dirs = [Some(".jj"), colocate.then_some(".git")]; |
| 264 |
for &name in sub_dirs.iter().flatten() { |
| 265 |
let dir = canonical_wc_path.join(name); |
| 266 |
fs::remove_dir_all(&dir).or_else(|err| match err.kind() { |
| 267 |
io::ErrorKind::NotFound => Ok(()), |
| 268 |
_ => Err(err), |
| 269 |
})?; |
| 270 |
} |
| 271 |
if !wc_path_existed { |
| 272 |
fs::remove_dir(&canonical_wc_path)?; |
| 273 |
} |
| 274 |
Ok(()) |
| 275 |
}; |
| 276 |
if let Err(err) = clean_up_dirs() { |
| 277 |
writeln!( |
| 278 |
ui.warning_default(), |
| 279 |
"Failed to clean up {}: {}", |
| 280 |
canonical_wc_path.display(), |
| 281 |
err |
| 282 |
) |
| 283 |
.ok(); |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
let (mut workspace_command, (working_branch, working_is_default), config_env) = clone_result?; |
| 288 |
|
| 289 |
write_repo_presets( |
| 290 |
ui, |
| 291 |
&config_env, |
| 292 |
RepoPresets { |
| 293 |
remote: remote_name, |
| 294 |
fetch_bookmarks: is_specific.then_some(args.branches.as_deref().unwrap_or(&[])), |
| 295 |
fetch_tags: is_specific.then_some(args.tags.as_deref().unwrap_or(&[])), |
| 296 |
trunk: working_branch |
| 297 |
.as_deref() |
| 298 |
.filter(|_| working_is_default) |
| 299 |
.map(|name| name.to_remote_symbol(remote_name)), |
| 300 |
}, |
| 301 |
)?; |
| 302 |
|
| 303 |
if let Some(name) = &working_branch { |
| 304 |
let working_symbol = name.to_remote_symbol(remote_name); |
| 305 |
let working_branch_remote_ref = workspace_command |
| 306 |
.repo() |
| 307 |
.view() |
| 308 |
.get_remote_bookmark(working_symbol); |
| 309 |
if let Some(commit_id) = working_branch_remote_ref.target.as_normal().cloned() { |
| 310 |
let mut tx = workspace_command.start_transaction(); |
| 311 |
if let Ok(commit) = tx.repo().store().get_commit_async(&commit_id).await { |
| 312 |
tx.check_out(&commit)?; |
| 313 |
} |
| 314 |
tx.finish( |
| 315 |
ui, |
| 316 |
format!("check out git remote's branch: {}", name.as_symbol()), |
| 317 |
) |
| 318 |
.await?; |
| 319 |
} |
| 320 |
} |
| 321 |
|
| 322 |
Ok(()) |
| 323 |
} |
| 324 |
|
| 325 |
async fn init_workspace( |
| 326 |
ui: &Ui, |
| 327 |
command: &CommandHelper, |
| 328 |
wc_path: &Path, |
| 329 |
colocate: bool, |
| 330 |
object_hash: gix::hash::Kind, |
| 331 |
) -> Result<(WorkspaceCommandHelper, ConfigEnv), CommandError> { |
| 332 |
let (settings, config_env) = command.settings_for_new_workspace(ui, wc_path)?; |
| 333 |
let (workspace, repo) = if colocate { |
| 334 |
Workspace::init_colocated_git(&settings, wc_path, object_hash).await? |
| 335 |
} else { |
| 336 |
Workspace::init_internal_git(&settings, wc_path, object_hash).await? |
| 337 |
}; |
| 338 |
let workspace_command = command.for_workable_repo(ui, workspace, repo)?; |
| 339 |
maybe_add_gitignore(&workspace_command)?; |
| 340 |
Ok((workspace_command, config_env)) |
| 341 |
} |
| 342 |
|
| 343 |
async fn configure_remote( |
| 344 |
ui: &Ui, |
| 345 |
command: &CommandHelper, |
| 346 |
mut workspace_command: WorkspaceCommandHelper, |
| 347 |
remote_name: &RemoteName, |
| 348 |
source: &str, |
| 349 |
) -> Result<WorkspaceCommandHelper, CommandError> { |
| 350 |
let mut tx = workspace_command.start_transaction(); |
| 351 |
git::add_remote(tx.repo_mut(), remote_name, source, None)?; |
| 352 |
tx.finish(ui, format!("add git remote {}", remote_name.as_symbol())) |
| 353 |
.await?; |
| 354 |
// Reload workspace to apply new remote configuration to |
| 355 |
// gix::ThreadSafeRepository behind the store. |
| 356 |
let workspace = command.load_workspace_at( |
| 357 |
workspace_command.workspace_root(), |
| 358 |
workspace_command.settings(), |
| 359 |
)?; |
| 360 |
let op = workspace |
| 361 |
.repo_loader() |
| 362 |
.load_operation(workspace_command.repo().op_id()) |
| 363 |
.await?; |
| 364 |
let repo = workspace.repo_loader().load_at(&op).await?; |
| 365 |
command.for_workable_repo(ui, workspace, repo) |
| 366 |
} |
| 367 |
|
| 368 |
async fn fetch_new_remote( |
| 369 |
ui: &Ui, |
| 370 |
workspace_command: &mut WorkspaceCommandHelper, |
| 371 |
remote_name: &RemoteName, |
| 372 |
ref_expr: &GitFetchRefExpression, |
| 373 |
depth: Option<NonZeroU32>, |
| 374 |
) -> Result<(Option<RefNameBuf>, bool), CommandError> { |
| 375 |
writeln!( |
| 376 |
ui.status(), |
| 377 |
r#"Fetching into new repo in "{}""#, |
| 378 |
workspace_command.workspace_root().display() |
| 379 |
)?; |
| 380 |
let settings = workspace_command.settings(); |
| 381 |
let git_settings = GitSettings::from_settings(settings)?; |
| 382 |
let remote_settings = settings.remote_settings()?; |
| 383 |
let subprocess_options = git_settings.to_subprocess_options(); |
| 384 |
let import_options = GitImportOptions { |
| 385 |
// There may be a large number of new commits. Don't record synthetic |
| 386 |
// predecessors. |
| 387 |
record_synthetic_predecessors: false, |
| 388 |
..load_git_import_options(ui, &git_settings, &remote_settings)? |
| 389 |
}; |
| 390 |
let should_track_default = settings.get_bool("git.track-default-bookmark-on-clone")?; |
| 391 |
let mut tx = workspace_command.start_transaction(); |
| 392 |
let (default_branch, import_stats) = { |
| 393 |
let mut git_fetch = GitFetch::new(tx.repo_mut(), subprocess_options, &import_options)?; |
| 394 |
|
| 395 |
let fetch_refspecs = expand_fetch_refspecs(remote_name, ref_expr.clone())?; |
| 396 |
|
| 397 |
git_fetch.fetch( |
| 398 |
remote_name, |
| 399 |
fetch_refspecs, |
| 400 |
&mut GitSubprocessUi::new(ui), |
| 401 |
depth, |
| 402 |
)?; |
| 403 |
|
| 404 |
let import_stats = git_fetch.import_refs().await?; |
| 405 |
|
| 406 |
let default_branch = git_fetch.get_default_branch(remote_name)?; |
| 407 |
(default_branch, import_stats) |
| 408 |
}; |
| 409 |
|
| 410 |
// Warn unmatched exact patterns, and record the first matching branch as |
| 411 |
// the working branch. If there are no matching exact patterns, use the |
| 412 |
// default branch of the remote. |
| 413 |
let mut missing_branches = vec![]; |
| 414 |
let mut working_branch = None; |
| 415 |
let bookmark_matcher = ref_expr.bookmark.to_matcher(); |
| 416 |
let exact_bookmarks = ref_expr |
| 417 |
.bookmark |
| 418 |
.exact_strings() |
| 419 |
.filter(|name| bookmark_matcher.is_match(name)) // exclude negative patterns |
| 420 |
.map(RefName::new); |
| 421 |
for name in exact_bookmarks { |
| 422 |
let symbol = name.to_remote_symbol(remote_name); |
| 423 |
if tx.repo().view().get_remote_bookmark(symbol).is_absent() { |
| 424 |
missing_branches.push(name); |
| 425 |
} else if working_branch.is_none() { |
| 426 |
working_branch = Some(name); |
| 427 |
} |
| 428 |
} |
| 429 |
if working_branch.is_none() { |
| 430 |
working_branch = default_branch.as_deref().filter(|name| { |
| 431 |
let symbol = name.to_remote_symbol(remote_name); |
| 432 |
tx.repo().view().get_remote_bookmark(symbol).is_present() |
| 433 |
}); |
| 434 |
} |
| 435 |
if !missing_branches.is_empty() { |
| 436 |
writeln!( |
| 437 |
ui.warning_default(), |
| 438 |
"No matching branches found on remote: {}", |
| 439 |
missing_branches |
| 440 |
.iter() |
| 441 |
.map(|name| name.as_symbol()) |
| 442 |
.join(", ") |
| 443 |
)?; |
| 444 |
} |
| 445 |
// TODO: warn missing tags if we add --tag=pattern |
| 446 |
|
| 447 |
let working_is_default = working_branch == default_branch.as_deref(); |
| 448 |
if let Some(name) = working_branch |
| 449 |
&& working_is_default |
| 450 |
&& should_track_default |
| 451 |
{ |
| 452 |
// For convenience, create local bookmark as Git would do. |
| 453 |
let remote_symbol = name.to_remote_symbol(remote_name); |
| 454 |
tx.repo_mut().track_remote_bookmark(remote_symbol).await?; |
| 455 |
} |
| 456 |
print_git_import_stats(ui, &tx, &import_stats)?; |
| 457 |
tx.finish(ui, "fetch from git remote into empty repo") |
| 458 |
.await?; |
| 459 |
Ok((working_branch.map(ToOwned::to_owned), working_is_default)) |
| 460 |
} |