From 1a37eadc67033d6b76c913b21f9141bb6cec19d2 Mon Sep 17 00:00:00 2001 From: Mustafa Officewala Date: Sun, 30 Aug 2026 08:10:05 +0530 Subject: [PATCH 1/2] fmt: Ran `cargo +nightly fmt --all` after new nightly release. --- cli/build.rs | 12 +- cli/examples/custom-backend/main.rs | 4 +- cli/src/cleanup_guard.rs | 5 +- cli/src/cli_util.rs | 147 +++++----- cli/src/commands/arrange.rs | 43 +-- cli/src/commands/bisect/run.rs | 3 +- cli/src/commands/bookmark/forget.rs | 7 +- cli/src/commands/bookmark/list.rs | 12 +- cli/src/commands/bookmark/mod.rs | 6 +- cli/src/commands/bookmark/set.rs | 5 +- cli/src/commands/bookmark/untrack.rs | 4 +- cli/src/commands/config/set.rs | 4 +- cli/src/commands/converge.rs | 36 +-- cli/src/commands/debug/object.rs | 4 +- cli/src/commands/debug/tree.rs | 5 +- cli/src/commands/describe.rs | 7 +- cli/src/commands/file/untrack.rs | 9 +- cli/src/commands/fix.rs | 19 +- cli/src/commands/gerrit/upload.rs | 11 +- cli/src/commands/git/colocation.rs | 4 +- cli/src/commands/git/init.rs | 12 +- cli/src/commands/git/push.rs | 15 +- cli/src/commands/git/remote/add.rs | 4 +- cli/src/commands/log.rs | 15 +- cli/src/commands/new.rs | 14 +- cli/src/commands/operation/diff.rs | 5 +- cli/src/commands/operation/integrate.rs | 3 +- cli/src/commands/operation/show.rs | 4 +- cli/src/commands/parallelize.rs | 17 +- cli/src/commands/redo.rs | 14 +- cli/src/commands/revert.rs | 13 +- cli/src/commands/run.rs | 15 +- cli/src/commands/split.rs | 3 +- cli/src/commands/squash.rs | 12 +- cli/src/commands/status.rs | 3 +- cli/src/commands/tag/list.rs | 3 +- cli/src/commands/undo.rs | 12 +- cli/src/commands/util/markdown_help.rs | 4 +- cli/src/commands/workspace/add.rs | 12 +- cli/src/commit_ref_list.rs | 7 +- cli/src/commit_templater.rs | 18 +- cli/src/complete.rs | 14 +- cli/src/config.rs | 17 +- cli/src/description_util.rs | 7 +- cli/src/diff_util.rs | 25 +- cli/src/formatter.rs | 36 +-- cli/src/git_util.rs | 17 +- cli/src/merge_tools/builtin.rs | 48 ++-- cli/src/merge_tools/diff_working_copies.rs | 16 +- cli/src/merge_tools/external.rs | 29 +- cli/src/merge_tools/mod.rs | 11 +- cli/src/template_builder.rs | 7 +- cli/src/template_parser.rs | 15 +- cli/src/text_util.rs | 21 +- cli/src/time_util.rs | 3 +- cli/src/ui.rs | 13 +- cli/testing/fake-bisector.rs | 5 +- cli/testing/fake-editor.rs | 4 +- cli/tests/common/test_environment.rs | 12 +- cli/tests/test_abandon_command.rs | 16 +- cli/tests/test_absorb_command.rs | 10 +- cli/tests/test_advance_bookmarks.rs | 23 +- cli/tests/test_bookmark_command.rs | 33 +-- cli/tests/test_commit_command.rs | 7 +- cli/tests/test_completion.rs | 25 +- cli/tests/test_concurrent_operations.rs | 4 +- cli/tests/test_config_command.rs | 10 +- cli/tests/test_converge_command.rs | 101 +++---- cli/tests/test_debug_command.rs | 3 +- cli/tests/test_describe_command.rs | 4 +- cli/tests/test_diff_command.rs | 13 +- cli/tests/test_diffedit_command.rs | 27 +- cli/tests/test_duplicate_command.rs | 50 ++-- cli/tests/test_file_chmod_command.rs | 4 +- cli/tests/test_file_track_untrack_commands.rs | 11 +- cli/tests/test_fix_command.rs | 109 ++++---- cli/tests/test_gerrit_upload.rs | 16 +- cli/tests/test_git_colocated.rs | 51 ++-- cli/tests/test_git_fetch.rs | 48 ++-- cli/tests/test_git_import_export.rs | 11 +- cli/tests/test_git_init.rs | 16 +- cli/tests/test_git_push.rs | 86 +++--- cli/tests/test_git_remotes.rs | 3 +- cli/tests/test_gitignores.rs | 7 +- cli/tests/test_global_opts.rs | 21 +- cli/tests/test_help_command.rs | 3 +- cli/tests/test_identical_commits.rs | 8 +- cli/tests/test_immutable_commits.rs | 7 +- cli/tests/test_interdiff_command.rs | 3 +- cli/tests/test_log_command.rs | 21 +- cli/tests/test_metaedit_command.rs | 3 +- cli/tests/test_new_command.rs | 3 +- cli/tests/test_next_prev_commands.rs | 7 +- cli/tests/test_op_integrate_command.rs | 12 +- cli/tests/test_op_revert_command.rs | 29 +- cli/tests/test_operations.rs | 10 +- cli/tests/test_rebase_command.rs | 132 ++++----- cli/tests/test_resolve_command.rs | 42 +-- cli/tests/test_restore_command.rs | 4 +- cli/tests/test_run_command.rs | 36 +-- cli/tests/test_split_command.rs | 40 +-- cli/tests/test_squash_command.rs | 54 ++-- cli/tests/test_status_command.rs | 19 +- cli/tests/test_util_command.rs | 3 +- cli/tests/test_working_copy.rs | 12 +- cli/tests/test_workspaces.rs | 61 +++-- core/proc-macros/src/content_hash.rs | 3 +- core/src/dag_walk.rs | 6 +- core/src/dag_walk_async.rs | 45 ++-- core/src/diff.rs | 51 ++-- core/src/file_util.rs | 14 +- core/src/graph.rs | 34 +-- core/src/matchers.rs | 14 +- core/src/merge.rs | 25 +- core/src/repo_path.rs | 4 +- core/src/str_util.rs | 37 +-- lib/src/bisect.rs | 10 +- lib/src/commit_builder.rs | 4 +- lib/src/config_resolver.rs | 4 +- lib/src/conflicts.rs | 72 ++--- lib/src/converge.rs | 75 +++--- lib/src/copies.rs | 92 ++++--- lib/src/default_index/composite.rs | 17 +- lib/src/default_index/mod.rs | 30 ++- lib/src/default_index/mutable.rs | 5 +- lib/src/default_index/readonly.rs | 5 +- lib/src/default_index/rev_walk.rs | 24 +- lib/src/default_index/revset_engine.rs | 38 +-- .../default_index/revset_graph_iterator.rs | 13 +- lib/src/default_index/store.rs | 4 +- lib/src/diff_presentation/mod.rs | 10 +- lib/src/dsl_util.rs | 4 +- lib/src/eol.rs | 14 +- lib/src/files.rs | 29 +- lib/src/fileset.rs | 9 +- lib/src/fileset_parser.rs | 9 +- lib/src/fix.rs | 78 +++--- lib/src/fsmonitor.rs | 11 +- lib/src/git.rs | 189 +++++++------ lib/src/git_backend.rs | 107 ++++---- lib/src/git_subprocess.rs | 15 +- lib/src/graph_dominators.rs | 115 ++++---- lib/src/id_prefix.rs | 38 +-- lib/src/local_working_copy.rs | 133 +++++---- lib/src/lock/unix.rs | 9 +- lib/src/merged_tree.rs | 73 ++--- lib/src/merged_tree_builder.rs | 24 +- lib/src/op_heads_store.rs | 4 +- lib/src/op_walk.rs | 8 +- lib/src/refs.rs | 4 +- lib/src/repo.rs | 88 +++--- lib/src/revset.rs | 69 ++--- lib/src/revset_parser.rs | 16 +- lib/src/rewrite.rs | 254 +++++++++--------- lib/src/secure_config.rs | 14 +- lib/src/settings.rs | 4 +- lib/src/simple_backend.rs | 5 +- lib/src/simple_op_heads_store.rs | 7 +- lib/src/simple_op_store.rs | 12 +- lib/src/ssh_signing.rs | 13 +- lib/src/stacked_table.rs | 40 +-- lib/src/trailer.rs | 5 +- lib/src/tree.rs | 3 +- lib/src/tree_builder.rs | 7 +- lib/src/tree_merge.rs | 35 +-- lib/src/view.rs | 14 +- lib/src/working_copy.rs | 19 +- lib/src/workspace.rs | 22 +- lib/tests/test_bad_locking.rs | 33 +-- lib/tests/test_bisect.rs | 10 +- lib/tests/test_commit_builder.rs | 4 +- lib/tests/test_commit_concurrent.rs | 12 +- lib/tests/test_conflicts.rs | 44 +-- .../test_default_revset_graph_iterator.rs | 14 +- lib/tests/test_eol.rs | 59 ++-- lib/tests/test_fix.rs | 4 +- lib/tests/test_git.rs | 171 ++++++------ lib/tests/test_git_backend.rs | 14 +- lib/tests/test_gpg.rs | 3 +- lib/tests/test_id_prefix.rs | 10 +- lib/tests/test_index.rs | 24 +- lib/tests/test_load_repo.rs | 4 +- lib/tests/test_local_working_copy.rs | 51 ++-- .../test_local_working_copy_concurrent.rs | 22 +- lib/tests/test_local_working_copy_sparse.rs | 18 +- lib/tests/test_merged_tree.rs | 73 ++--- lib/tests/test_mut_repo.rs | 43 +-- lib/tests/test_operations.rs | 21 +- lib/tests/test_revset.rs | 72 ++--- lib/tests/test_rewrite.rs | 136 +++++----- lib/tests/test_view.rs | 31 ++- lib/tests/test_workspace.rs | 3 +- lib/testutils/src/git.rs | 4 +- lib/testutils/src/lib.rs | 9 +- lib/testutils/src/proptest.rs | 4 +- lib/testutils/src/test_backend.rs | 9 +- 196 files changed, 2812 insertions(+), 2296 deletions(-) diff --git a/cli/build.rs b/cli/build.rs index ff60bd7053c..ac755fbb750 100644 --- a/cli/build.rs +++ b/cli/build.rs @@ -24,11 +24,12 @@ fn main() { println!("cargo:rerun-if-env-changed=NIX_JJ_GIT_HASH"); let git_hash = get_git_hash_from_nix().or_else(|| { if Path::new(GIT_HEAD_PATH).exists() { - // In colocated workspace, .git/HEAD should reflect the working-copy parent. + // In colocated workspace, .git/HEAD should reflect the working-copy + // parent. println!("cargo:rerun-if-changed={GIT_HEAD_PATH}"); } else if Path::new(JJ_OP_HEADS_PATH).exists() { - // op_heads changes when working-copy files are mutated, which is way more - // frequent than .git/HEAD. + // op_heads changes when working-copy files are mutated, which is + // way more frequent than .git/HEAD. println!("cargo:rerun-if-changed={JJ_OP_HEADS_PATH}"); } get_git_hash_from_jj().or_else(get_git_hash_from_git) @@ -70,8 +71,9 @@ fn get_git_hash_from_jj() -> Option { .filter(|output| output.status.success()) .map(|output| { let mut parent_commits = String::from_utf8(output.stdout).unwrap(); - // If a development version of `jj` is compiled at a merge commit, this will - // result in several commit ids separated by `-`s. + // If a development version of `jj` is compiled at a merge commit, + // this will result in several commit ids separated by + // `-`s. parent_commits.truncate(parent_commits.trim_end_matches('-').len()); parent_commits }) diff --git a/cli/examples/custom-backend/main.rs b/cli/examples/custom-backend/main.rs index ca62d57f77b..5a84f050a33 100644 --- a/cli/examples/custom-backend/main.rs +++ b/cli/examples/custom-backend/main.rs @@ -57,8 +57,8 @@ enum CustomCommand { fn create_store_factories() -> StoreFactories { let mut store_factories = StoreFactories::empty(); - // Register the backend so it can be loaded when the repo is loaded. The name - // must match `Backend::name()`. + // Register the backend so it can be loaded when the repo is loaded. The + // name must match `Backend::name()`. store_factories.add_backend( "jit", Box::new(|settings, store_path| Ok(Box::new(JitBackend::load(settings, store_path)?))), diff --git a/cli/src/cleanup_guard.rs b/cli/src/cleanup_guard.rs index 79a30154242..7797080e002 100644 --- a/cli/src/cleanup_guard.rs +++ b/cli/src/cleanup_guard.rs @@ -12,8 +12,9 @@ type GuardTable = Slab>; /// Prepare to run [`CleanupGuard`]s on `SIGINT`/`SIGTERM`/`SIGHUP` pub fn init() { if let Err(e) = ctrlc::set_handler(|| { - // We must hold the lock for the remainder of the process's lifetime to avoid a - // race where a guard is created after we unlock but before we exit. + // We must hold the lock for the remainder of the process's lifetime to + // avoid a race where a guard is created after we unlock but + // before we exit. let guards = &mut *LIVE_GUARDS.lock().unwrap(); if let Err(e) = std::panic::catch_unwind(AssertUnwindSafe(|| { for guard in guards.drain() { diff --git a/cli/src/cli_util.rs b/cli/src/cli_util.rs index d716ef7a108..4b535ae4f99 100644 --- a/cli/src/cli_util.rs +++ b/cli/src/cli_util.rs @@ -284,7 +284,8 @@ impl TracingSubscription { .modify(|filter| { // The default is INFO. // jj-lib and jj-cli are whitelisted for DEBUG logging. - // This ensures that other crates' logging doesn't show up by default. + // This ensures that other crates' logging doesn't show up by + // default. *filter = tracing_subscriber::EnvFilter::builder() .with_default_directive(tracing::metadata::LevelFilter::INFO.into()) .with_env_var(Self::ENV_VAR_NAME) @@ -501,10 +502,11 @@ impl CommandHelper { return Err(err); } - // We detected the working copy was stale and the client is configured to - // auto-update-stale, so let's do that now. We need to do it up here, not at a - // lower level (e.g. inside snapshot_working_copy()) to avoid recursive locking - // of the working copy. + // We detected the working copy was stale and the client is + // configured to auto-update-stale, so let's do + // that now. We need to do it up here, not at a + // lower level (e.g. inside snapshot_working_copy()) to avoid + // recursive locking of the working copy. let WorkspaceCommandHelper { workspace, env, .. } = workspace_command; self.recover_stale_working_copy_impl(ui, workspace, env, &git_import_export_lock) .await? @@ -644,10 +646,12 @@ impl CommandHelper { )?; workspace_command.check_working_copy_writable()?; - // Snapshot the current working copy on top of the last known working-copy - // operation, then merge the divergent operations. The wc_commit_id of the - // merged repo wouldn't change because the old one wins, but it's probably - // fine if we picked the new wc_commit_id. + // Snapshot the current working copy on top of the last known + // working-copy operation, then merge the + // divergent operations. The wc_commit_id of the + // merged repo wouldn't change because the old one wins, but + // it's probably fine if we picked the new + // wc_commit_id. let stale_stats = workspace_command .snapshot_working_copy(ui, git_import_export_lock) .await @@ -813,7 +817,8 @@ impl CommandHelper { ui.status(), "Concurrent modification detected, resolving automatically.", )?; - // TODO: It may be helpful to print each operation we're merging here + // TODO: It may be helpful to print each operation we're + // merging here let transaction_description = "reconcile divergent operations"; merge_operations( Some(ui), @@ -1404,9 +1409,9 @@ impl WorkspaceCommandHelper { .check_out(workspace_name, &new_git_head_commit) .await?; let mut locked_ws = self.workspace.start_working_copy_mutation().await?; - // The working copy was presumably updated by the git command that updated - // HEAD, so we just need to reset our working copy - // state to it without updating working copy files. + // The working copy was presumably updated by the git command that + // updated HEAD, so we just need to reset our working + // copy state to it without updating working copy files. locked_ws.locked_wc().reset(&wc_commit).await?; tx.repo_mut().rebase_descendants().await?; self.user_repo = ReadonlyUserRepo::new( @@ -1670,14 +1675,15 @@ to the current parents may contain changes from multiple commits. #[instrument(skip_all)] pub fn base_ignores(&self) -> Result, GitIgnoreError> { let get_excludes_file_path = |config: &gix::config::File| -> Option { - // TODO: maybe use path() and interpolate(), which can process non-utf-8 - // path on Unix. + // TODO: maybe use path() and interpolate(), which can process + // non-utf-8 path on Unix. if let Some(value) = config.string("core.excludesFile") { let path = str::from_utf8(&value) .ok() .map(jj_lib::file_util::expand_home_path)?; - // The configured path is usually absolute, but if it's relative, - // the "git" command would read the file at the work-tree directory. + // The configured path is usually absolute, but if it's + // relative, the "git" command would read the + // file at the work-tree directory. Some(self.workspace_root().join(path)) } else { xdg_config_home().map(|x| x.join("git").join("ignore")) @@ -2097,7 +2103,8 @@ to the current parents may contain changes from multiple commits. .snapshot_options_with_start_tracking_matcher(&auto_tracking_matcher) .map_err(snapshot_command_error)?; - // Compare working-copy tree and operation with repo's, and reload as needed. + // Compare working-copy tree and operation with repo's, and reload as + // needed. let mut locked_ws = self .workspace .start_working_copy_mutation() @@ -2107,8 +2114,8 @@ to the current parents may contain changes from multiple commits. let Some((repo, wc_commit)) = handle_stale_working_copy(locked_ws.locked_wc(), repo, &workspace_name).await? else { - // If the workspace has been deleted, it's unclear what to do, so we just skip - // committing the working copy. + // If the workspace has been deleted, it's unclear what to do, so we + // just skip committing the working copy. return Ok(SnapshotStats::default()); }; @@ -2184,7 +2191,8 @@ to the current parents may contain changes from multiple commits. { let workspace_root = self.env.workspace_root(); if wc_immutable { - // New working-copy commit is created on top. Reset Git HEAD and index. + // New working-copy commit is created on top. Reset Git HEAD + // and index. try_reset_git_head( ui, mut_repo, @@ -2195,8 +2203,9 @@ to the current parents may contain changes from multiple commits. ) .await .map_err(snapshot_command_error)?; - // export_refs() is probably unnecessary because there should be no - // rewritten descendants, but it's harmless. + // export_refs() is probably unnecessary because there + // should be no rewritten descendants, + // but it's harmless. let stats = jj_lib::git::export_refs(mut_repo).map_err(snapshot_command_error)?; crate::git_util::print_git_export_stats(ui, &stats) @@ -2499,11 +2508,13 @@ to the current parents may contain changes from multiple commits. let old_heads = RevsetExpression::commits(old_view.heads().iter().cloned().collect()); let new_heads = RevsetExpression::commits(new_view.heads().iter().cloned().collect()); - // Filter the revsets by conflicts instead of reading all commits and doing the - // filtering here. That way, we can afford to evaluate the revset even if there - // are millions of commits added to the repo, assuming the revset engine can - // efficiently skip non-conflicting commits. Filter out empty commits mostly so - // `jj new ` doesn't result in a message about new conflicts. + // Filter the revsets by conflicts instead of reading all commits and + // doing the filtering here. That way, we can afford to evaluate + // the revset even if there are millions of commits added to the + // repo, assuming the revset engine can efficiently skip + // non-conflicting commits. Filter out empty commits mostly so + // `jj new ` doesn't result in a message about new + // conflicts. let conflicts = RevsetExpression::filter(RevsetFilterPredicate::HasConflict) .filtered(RevsetFilterPredicate::File(FilesetExpression::all())); let removed_conflicts_expr = new_heads.range(&old_heads).intersection(&conflicts); @@ -2541,8 +2552,9 @@ to the current parents may contain changes from multiple commits. // TODO: Also report new divergence and maybe resolved divergence if !resolved_conflicts_by_change_id.is_empty() { // TODO: Report resolved and abandoned numbers separately. However, - // that involves resolving the change_id among the visible commits in the new - // repo, which isn't currently supported by Google's revset engine. + // that involves resolving the change_id among the visible commits + // in the new repo, which isn't currently supported by + // Google's revset engine. let num_resolved: usize = resolved_conflicts_by_change_id .values() .map(|commits| commits.len()) @@ -2565,15 +2577,17 @@ to the current parents may contain changes from multiple commits. )?; } - // Hint that the user might want to `jj new` to the first conflict commit to - // resolve conflicts. Only show the hints if there were any new or resolved - // conflicts, and only if there are still some conflicts. + // Hint that the user might want to `jj new` to the first conflict + // commit to resolve conflicts. Only show the hints if there + // were any new or resolved conflicts, and only if there are + // still some conflicts. if !(added_conflict_commits.is_empty() || resolved_conflicts_by_change_id.is_empty() && new_conflicts_by_change_id.is_empty()) { - // If the user just resolved some conflict and squashed them in, there won't be - // any new conflicts. Clarify to them that there are still some other conflicts - // to resolve. (We don't mention conflicts in commits that weren't affected by + // If the user just resolved some conflict and squashed them in, + // there won't be any new conflicts. Clarify to them + // that there are still some other conflicts to resolve. + // (We don't mention conflicts in commits that weren't affected by // the operation, however.) if new_conflicts_by_change_id.is_empty() { writeln!( @@ -2618,7 +2632,8 @@ to the current parents may contain changes from multiple commits. .try_collect() .await?; - // The common part of these strings is not extracted, to avoid i18n issues. + // The common part of these strings is not extracted, to avoid i18n + // issues. let instruction = if only_one_conflicted_commit { indoc! {" To resolve the conflicts, start by creating a commit on top of @@ -2734,9 +2749,10 @@ async fn try_reset_git_head( // Export Git HEAD while holding the git-head lock to prevent races: // - Between two finish_transaction calls updating HEAD // - With import_git_head importing HEAD concurrently - // This can still fail if HEAD was updated concurrently by another JJ process - // (overlapping transaction) or a non-JJ process (e.g., git checkout). In that - // case, the actual state will be imported on the next snapshot. + // This can still fail if HEAD was updated concurrently by another JJ + // process (overlapping transaction) or a non-JJ process (e.g., git + // checkout). In that case, the actual state will be imported on the + // next snapshot. match jj_lib::git::reset_head(mut_repo, workspace_name, workspace_root, wc_commit).await { Ok(()) => Ok(()), Err(err @ jj_lib::git::GitResetHeadError::UpdateHeadRef(_)) => { @@ -2851,8 +2867,9 @@ impl WorkspaceCommandTransaction<'_> { if num_rebased > 0 { writeln!(ui.status(), "Rebased {num_rebased} descendant commits.")?; } - // Acquire git import/export lock before finishing the transaction to ensure - // Git HEAD export happens atomically with the transaction commit. + // Acquire git import/export lock before finishing the transaction to + // ensure Git HEAD export happens atomically with the + // transaction commit. let git_import_export_lock = helper.lock_git_import_export()?; helper .finish_transaction(ui, tx, description, &git_import_export_lock) @@ -2951,8 +2968,8 @@ fn command_args_to_transaction_attribute(command_args: &[String]) -> Vec<(String if command_args.is_empty() { return vec![]; } - // TODO: Either do better shell-escaping here or store the values in some list - // type (which we currently don't have). + // TODO: Either do better shell-escaping here or store the values in some + // list type (which we currently don't have). let shell_escape = |arg: &String| { if arg.as_bytes().iter().all(|b| { matches!(b, @@ -3136,8 +3153,8 @@ pub fn print_conflicted_paths( .map(|p| format!("{:width$}", p, width = max_path_len.min(32) + 3)); for ((_, conflict), formatted_path) in std::iter::zip(conflicts, formatted_paths) { - // TODO: Display the error for the path instead of failing the whole command if - // `conflict` is an error? + // TODO: Display the error for the path instead of failing the whole + // command if `conflict` is an error? let conflict = conflict?.simplify(); let sides = conflict.num_sides(); let n_adds = conflict.adds().flatten().count(); @@ -3154,8 +3171,8 @@ pub fn print_conflicted_paths( "normal", // Deletions don't interfere with `jj resolve` or diff display ); } - // TODO: We might decide it's OK for `jj resolve` to ignore special files in the - // `removes` of a conflict (see e.g. https://github.com/jj-vcs/jj/pull/978). In + // TODO: We might decide it's OK for `jj resolve` to ignore special + // files in the `removes` of a conflict (see e.g. https://github.com/jj-vcs/jj/pull/978). In // that case, `conflict.removes` should be removed below. for term in itertools::chain(conflict.removes(), conflict.adds()).flatten() { seen_objects.insert( @@ -3651,8 +3668,9 @@ pub async fn compute_commit_location( .map(|id| workspace_command.repo().store().get_commit_async(id)), ) .await?; - // Not using `RevsetExpression::parents` here to persist the order of parents - // specified in `before_commits`. + // Not using `RevsetExpression::parents` here to persist the + // order of parents specified in + // `before_commits`. let new_parent_ids = before_commits .iter() .flat_map(|commit| commit.parent_ids()) @@ -4040,7 +4058,8 @@ fn resolve_aliases( .map(|arg| arg.to_str().unwrap().to_string()) .collect_vec(); let Some(&alias_name) = defined_aliases.get(&*alias_name) else { - // Not a real command and not an alias, so return what we've resolved so far + // Not a real command and not an alias, so return what we've + // resolved so far return Ok(string_args); }; let alias_definition: Vec = match config.get(["aliases", alias_name]) { @@ -4161,8 +4180,8 @@ fn handle_shell_completion( let mut expanded_args = expand_args_for_completion(ui, app, padded_args.take(index + 1), config)?; - // Adjust env var to compensate for shift of the completion point in the - // expanded command line. + // Adjust env var to compensate for shift of the completion point in + // the expanded command line. // SAFETY: Program is running single-threaded at this point. unsafe { env::set_var( @@ -4171,8 +4190,8 @@ fn handle_shell_completion( ); } - // Remove extra padding again to align with clap_complete's expectations for - // zsh. + // Remove extra padding again to align with clap_complete's + // expectations for zsh. let split_off_padding = expanded_args.split_off(expanded_args.len() - pad_len); assert!( split_off_padding.iter().all(|s| s.is_empty()), @@ -4180,7 +4199,8 @@ fn handle_shell_completion( {split_off_padding:?}", ); - // Append the remaining arguments to the right of the completion point. + // Append the remaining arguments to the right of the completion + // point. expanded_args.extend(to_string_args(orig_args)?); expanded_args } else { @@ -4248,15 +4268,15 @@ fn expand_args_for_completion( let mut string_args = to_string_args(args_os)?; let aliases = load_aliases(ui, config, app)?; - // Resolution of subcommand aliases must not consider the argument that is being - // completed. + // Resolution of subcommand aliases must not consider the argument that is + // being completed. let cursor_arg = string_args.pop(); string_args = resolve_aliases(config, app, &aliases, string_args)?; string_args.extend(cursor_arg); - // If a subcommand has been given, including the potentially incomplete argument - // that is being completed, the default command is not resolved and the - // completion candidates for the subcommand are prioritized. + // If a subcommand has been given, including the potentially incomplete + // argument that is being completed, the default command is not resolved + // and the completion candidates for the subcommand are prioritized. string_args = resolve_default_command(ui, config, app, string_args)?; let cursor_arg = string_args.pop(); @@ -4567,8 +4587,9 @@ impl<'a> CliRunner<'a> { ui: &mut Ui, mut raw_config: RawConfig, ) -> Result<(), CommandError> { - // `cwd` is canonicalized for consistency with `Workspace::workspace_root()` and - // to easily compute relative paths between them. + // `cwd` is canonicalized for consistency with + // `Workspace::workspace_root()` and to easily compute relative + // paths between them. let cwd = env::current_dir() .and_then(dunce::canonicalize) .map_err(|_| { diff --git a/cli/src/commands/arrange.rs b/cli/src/commands/arrange.rs index 70fa8ed5c5d..b6be205af27 100644 --- a/cli/src/commands/arrange.rs +++ b/cli/src/commands/arrange.rs @@ -374,9 +374,9 @@ impl State { /// viewport. fn clamp_scroll(&mut self, viewport_rows: u16) { // `render()` configures the graph renderer with a minimum row height of - // two, so this estimates how many commits fit in the common case. Custom - // templates and graph topology can make a commit taller, so this is not - // a strict bound. + // two, so this estimates how many commits fit in the common case. + // Custom templates and graph topology can make a commit taller, + // so this is not a strict bound. let max_visible = (viewport_rows / 2).max(1) as usize; let total_commits = self.external_children.len() + self.current_order.len() + self.external_parents.len(); @@ -528,8 +528,8 @@ fn run_tui( if let Event::Key(event) = event::read().map_err(|e| internal_error(format!("Failed to read TUI events: {e}")))? { - // On Windows, we get Press and Release (and maybe Repeat) events, but on Linux - // we only get Press. + // On Windows, we get Press and Release (and maybe Repeat) events, + // but on Linux we only get Press. if event.is_release() { continue; } @@ -600,8 +600,8 @@ fn render( .chain(state.external_parents.iter()) .skip(state.scroll_top); for id in commits_to_render { - // TODO: Make the graph column width depend on what's needed to render the - // graph. + // TODO: Make the graph column width depend on what's needed to render + // the graph. let row_layout = Layout::horizontal([ Constraint::Min(2), Constraint::Min(10), @@ -621,9 +621,9 @@ fn render( let commit_state = state.commits.get(id).unwrap(); let action = &commit_state.action; - // TODO: The graph can be misaligned with the text because sometimes `renderdag` - // inserts a line of edges before the line with the node and we assume the node - // is the first line emitted. + // TODO: The graph can be misaligned with the text because sometimes + // `renderdag` inserts a line of edges before the line with the + // node and we assume the node is the first line emitted. let edges = commit_state .parents .iter() @@ -756,7 +756,8 @@ mod tests { ] ); - // Update parents and head order and check that the commit order changes. + // Update parents and head order and check that the commit order + // changes. state.commits.get_mut(commit_a.id()).unwrap().parents = vec![commit_c.id().clone()]; state.commits.get_mut(commit_b.id()).unwrap().parents = vec![store.root_commit_id().clone()]; @@ -1013,7 +1014,8 @@ mod tests { ] ); - // Attempting to swap D down should have no effect because it has two parents + // Attempting to swap D down should have no effect because it has two + // parents state.current_selection = 0; assert_eq!(state.current_id(), commit_d.id()); let state_before = state.clone(); @@ -1070,8 +1072,8 @@ mod tests { ); assert_eq!(state.current_selection, 3); - // Attempting to swap C down should have no effect because it would move outside - // of range + // Attempting to swap C down should have no effect because it would move + // outside of range state.current_selection = 3; assert_eq!(state.current_id(), commit_c.id()); let state_before = state.clone(); @@ -1132,16 +1134,17 @@ mod tests { ] ); - // Attempting to swap A up should have no effect because it has two children + // Attempting to swap A up should have no effect because it has two + // children state.current_selection = 3; assert_eq!(state.current_id(), commit_a.id()); let state_before = state.clone(); state.swap_selection_up(); assert_eq!(state, state_before); - // Attempting to swap C up should have no effect because it has two children - // even though one is external. We could change this to ignore the external - // child. + // Attempting to swap C up should have no effect because it has two + // children even though one is external. We could change this to + // ignore the external child. state.current_selection = 2; assert_eq!(state.current_id(), commit_c.id()); let state_before = state.clone(); @@ -1173,8 +1176,8 @@ mod tests { ); assert_eq!(state.current_selection, 0); - // Attempting to swap B up should have no effect because it would move outside - // of range + // Attempting to swap B up should have no effect because it would move + // outside of range state.current_selection = 0; assert_eq!(state.current_id(), commit_b.id()); let state_before = state.clone(); diff --git a/cli/src/commands/bisect/run.rs b/cli/src/commands/bisect/run.rs index 34492cf2ccb..0ef4e0a0189 100644 --- a/cli/src/commands/bisect/run.rs +++ b/cli/src/commands/bisect/run.rs @@ -188,7 +188,8 @@ pub(crate) async fn cmd_bisect_run( bisector.mark(commit.id().clone(), evaluation); } - // Reload the workspace because the evaluation command may run `jj` commands. + // Reload the workspace because the evaluation command may run + // `jj` commands. workspace_command = command.workspace_helper(ui).await?; } jj_lib::bisect::NextStep::Done(bisection_result) => { diff --git a/cli/src/commands/bookmark/forget.rs b/cli/src/commands/bookmark/forget.rs index ac997e83ec6..d778d551468 100644 --- a/cli/src/commands/bookmark/forget.rs +++ b/cli/src/commands/bookmark/forget.rs @@ -83,15 +83,16 @@ pub async fn cmd_bookmark_forget( .set_local_bookmark_target(name, RefTarget::absent()); for (remote, _) in &bookmark_target.remote_refs { let symbol = name.to_remote_symbol(remote); - // If `--include-remotes` is specified, we forget the corresponding remote - // bookmarks instead of untracking them + // If `--include-remotes` is specified, we forget the corresponding + // remote bookmarks instead of untracking them if args.include_remotes { tx.repo_mut() .set_remote_bookmark(symbol, RemoteRef::absent()); forgotten_remote += 1; continue; } - // Git-tracking remote bookmarks cannot be untracked currently, so skip them + // Git-tracking remote bookmarks cannot be untracked currently, so + // skip them if ignored_remote.is_some_and(|ignored| symbol.remote == ignored) { continue; } diff --git a/cli/src/commands/bookmark/list.rs b/cli/src/commands/bookmark/list.rs index d16c2fcbd27..080f1dba2d3 100644 --- a/cli/src/commands/bookmark/list.rs +++ b/cli/src/commands/bookmark/list.rs @@ -140,10 +140,11 @@ pub async fn cmd_bookmark_list( (None, None) => StringExpression::all(), }; let matched_local_targets: HashSet<_> = if let Some(revisions) = &args.revisions { - // Match against local targets only, which is consistent with "jj git push". + // Match against local targets only, which is consistent with "jj git + // push". let mut expression = workspace_command.parse_union_revsets(ui, revisions)?; - // Intersects with the set of local bookmark targets to minimize the lookup - // space. + // Intersects with the set of local bookmark targets to minimize the + // lookup space. expression.intersect_with(&RevsetExpression::bookmarks(StringExpression::all())); expression.evaluate_to_commit_ids()?.try_collect().await? } else { @@ -216,8 +217,9 @@ pub async fn cmd_bookmark_list( #[cfg(feature = "git")] if jj_lib::git::get_git_backend(repo.store()).is_ok() { - // Print only one of these hints. It's not important to mention unexported - // bookmarks, but user might wonder why deleted bookmarks are still listed. + // Print only one of these hints. It's not important to mention + // unexported bookmarks, but user might wonder why deleted + // bookmarks are still listed. let deleted_tracking = bookmark_list_items .iter() .filter(|item| item.primary.is_local() && item.primary.is_absent()) diff --git a/cli/src/commands/bookmark/mod.rs b/cli/src/commands/bookmark/mod.rs index dd99a563e31..61027f85f79 100644 --- a/cli/src/commands/bookmark/mod.rs +++ b/cli/src/commands/bookmark/mod.rs @@ -168,9 +168,9 @@ async fn is_fast_forward( new_target_id: &CommitId, ) -> Result { if old_target.is_present() { - // Strictly speaking, "all" old targets should be ancestors, but we allow - // conflict resolution by setting bookmark to "any" of the old target - // descendants. + // Strictly speaking, "all" old targets should be ancestors, but we + // allow conflict resolution by setting bookmark to "any" of the + // old target descendants. let found = fallible_any(old_target.added_ids(), async |old| { repo.index().is_ancestor(old, new_target_id).await }) diff --git a/cli/src/commands/bookmark/set.rs b/cli/src/commands/bookmark/set.rs index 36bbed3a70b..80cb31baa1c 100644 --- a/cli/src/commands/bookmark/set.rs +++ b/cli/src/commands/bookmark/set.rs @@ -73,8 +73,9 @@ pub async fn cmd_bookmark_set( let mut moved_bookmark_count = 0; for name in bookmark_names { let old_target = repo.view().get_local_bookmark(name); - // If a bookmark is absent locally but is still tracking remote bookmarks, - // we are resurrecting the local bookmark, not "creating" a new bookmark. + // If a bookmark is absent locally but is still tracking remote + // bookmarks, we are resurrecting the local bookmark, not + // "creating" a new bookmark. if old_target.is_absent() && !has_tracked_remote_bookmarks(repo, name) { new_bookmarks.insert(name); } else if old_target.as_normal() != Some(target_commit.id()) { diff --git a/cli/src/commands/bookmark/untrack.rs b/cli/src/commands/bookmark/untrack.rs index 9d13568b863..b6aae6abd2e 100644 --- a/cli/src/commands/bookmark/untrack.rs +++ b/cli/src/commands/bookmark/untrack.rs @@ -113,8 +113,8 @@ pub async fn cmd_bookmark_untrack( let mut symbols = Vec::new(); for (symbol, remote_ref) in matched_refs { if ignored_remote.is_some_and(|ignored| symbol.remote == ignored) { - // This restriction can be lifted if we want to support untracked @git - // bookmarks. + // This restriction can be lifted if we want to support untracked + // @git bookmarks. writeln!( ui.warning_default(), "Git-tracking bookmark cannot be untracked: {symbol}" diff --git a/cli/src/commands/config/set.rs b/cli/src/commands/config/set.rs index 0b32dc57698..c9b517095d7 100644 --- a/cli/src/commands/config/set.rs +++ b/cli/src/commands/config/set.rs @@ -70,8 +70,8 @@ pub async fn cmd_config_set( ) -> Result<(), CommandError> { let mut file = args.level.edit_config_file(ui, command)?; - // If the user is trying to change the author config, we should warn them that - // it won't affect the working copy author + // If the user is trying to change the author config, we should warn them + // that it won't affect the working copy author if args.name == ConfigNamePathBuf::from_iter(vec!["user", "name"]) { check_wc_author(ui, command, &args.value, AuthorChange::Name).await?; } else if args.name == ConfigNamePathBuf::from_iter(vec!["user", "email"]) { diff --git a/cli/src/commands/converge.rs b/cli/src/commands/converge.rs index bda1df93fae..bb4e27fac6f 100644 --- a/cli/src/commands/converge.rs +++ b/cli/src/commands/converge.rs @@ -216,10 +216,11 @@ impl<'a> Converge<'a> { short_change_hash(&self.change_id) )?; - // Call the library function to attempt to converge the change automatically. + // Call the library function to attempt to converge the change + // automatically. let automatic_converge_result = { - // Initially we start with zero knowledge about what the solution should look - // like. + // Initially we start with zero knowledge about what the solution + // should look like. let author = None; let description = None; let parents = None; @@ -234,8 +235,8 @@ impl<'a> Converge<'a> { .await? }; - // Now solve the author, description and parents, prompting the user for input - // if necessary. + // Now solve the author, description and parents, prompting the user for + // input if necessary. let author = self.generic_solver(automatic_converge_result.author, Self::choose_author)?; let description = self.generic_solver( automatic_converge_result.description, @@ -264,8 +265,9 @@ impl<'a> Converge<'a> { return Err(user_error("Could not converge change")); }; - // If we do not have a tree yet, call the converge_change library function - // again, now that we have the author, description and parents. + // If we do not have a tree yet, call the converge_change library + // function again, now that we have the author, description and + // parents. let tree = match automatic_converge_result.tree { Some(tree) => Ok(tree), None => { @@ -391,8 +393,9 @@ impl<'a> Converge<'a> { let value_fn = |commit: &Commit| commit.parent_ids().to_vec(); - // A function that takes one of the divergent commits and returns a string that - // displays that commit's id and then its parents (one parent per line) + // A function that takes one of the divergent commits and returns a + // string that displays that commit's id and then its parents + // (one parent per line) let display_fn = |commit: &Commit, _formatter: &mut dyn Formatter| { let mut display_string = String::new(); writeln!(display_string, "{}:", short_commit_hash(commit.id())) @@ -425,8 +428,8 @@ impl<'a> Converge<'a> { _excluded_divergent_commits: HashSet, ) -> Result { let distinct_values = { - // Add the values of the divergent commits to the map, deduplicating them as we - // go. + // Add the values of the divergent commits to the map, deduplicating + // them as we go. let mut distinct_values = IndexMap::new(); for commit in self.truncated_evolution_graph.divergent_commits() { distinct_values @@ -483,9 +486,10 @@ fn choose_change<'a>( if divergent_changes.len() == 1 { return Ok(Some(divergent_changes.keys().next().unwrap())); } - // TODO: consider using heuristics to automatically choose a "good" change-id to - // converge, falling back to prompting the user only if the heuristics are - // inconclusive. This is specially important in non-interactive mode. + // TODO: consider using heuristics to automatically choose a "good" + // change-id to converge, falling back to prompting the user only if the + // heuristics are inconclusive. This is specially important in + // non-interactive mode. if !interactive { return Err( user_error("Cannot automatically choose which change to converge").hinted( @@ -535,8 +539,8 @@ where { assert!(!divergent_commits.is_empty()); let distinct_values = { - // Add the values of the divergent commits to the map, deduplicating them as we - // go. + // Add the values of the divergent commits to the map, deduplicating + // them as we go. let mut distinct_values = IndexMap::new(); for commit in divergent_commits { distinct_values.entry(value_fn(commit)).or_insert(commit); diff --git a/cli/src/commands/debug/object.rs b/cli/src/commands/debug/object.rs index f44898480c4..ee1f7a956a1 100644 --- a/cli/src/commands/debug/object.rs +++ b/cli/src/commands/debug/object.rs @@ -108,8 +108,8 @@ pub async fn cmd_debug_object( command: &CommandHelper, args: &DebugObjectArgs, ) -> Result<(), CommandError> { - // Resolve the operation without loading the repo, so this command can be used - // even if e.g. the view object is broken. + // Resolve the operation without loading the repo, so this command can be + // used even if e.g. the view object is broken. let workspace = command.load_workspace()?; let repo_loader = workspace.repo_loader(); diff --git a/cli/src/commands/debug/tree.rs b/cli/src/commands/debug/tree.rs index e2780076074..a678a67caa7 100644 --- a/cli/src/commands/debug/tree.rs +++ b/cli/src/commands/debug/tree.rs @@ -65,8 +65,9 @@ pub async fn cmd_debug_tree( }; let store = workspace_command.repo().store(); let tree = store.get_tree(dir, &tree_id).await?; - // We can't use `MergedTree` here, since it only supports iterating from the - // root, but we support a `--dir` option to read trees at any path. + // We can't use `MergedTree` here, since it only supports iterating + // from the root, but we support a `--dir` option to + // read trees at any path. Box::new( tree.entries_matching(matcher.as_ref()) .map(|(path, value)| (path, Ok(Merge::normal(value)))), diff --git a/cli/src/commands/describe.rs b/cli/src/commands/describe.rs index 492499796fd..fca54c5715c 100644 --- a/cli/src/commands/describe.rs +++ b/cli/src/commands/describe.rs @@ -154,9 +154,10 @@ pub(crate) async fn cmd_describe( if let Some(trailer_template) = parse_trailers_template(ui, &tx)? { for commit_builder in &mut commit_builders { // The first trailer would become the first line of the description. - // Also, a commit with no description is treated in a special way in jujutsu: it - // can be discarded as soon as it's no longer the working copy. Adding a - // trailer to an empty description would break that logic. + // Also, a commit with no description is treated in a special way in + // jujutsu: it can be discarded as soon as it's no + // longer the working copy. Adding a trailer to an empty + // description would break that logic. if use_editor || !commit_builder.description().is_empty() { let temp_commit = commit_builder.write_hidden().await?; let new_description = add_trailers_with_template(&trailer_template, &temp_commit)?; diff --git a/cli/src/commands/file/untrack.rs b/cli/src/commands/file/untrack.rs index b445f6fe2e5..0040ef06cec 100644 --- a/cli/src/commands/file/untrack.rs +++ b/cli/src/commands/file/untrack.rs @@ -74,8 +74,8 @@ pub(crate) async fn cmd_file_untrack( .await?; // Reset the working copy to the new commit locked_ws.locked_wc().reset(&new_commit).await?; - // Commit the working copy again so we can inform the user if paths couldn't be - // untracked because they're not ignored. + // Commit the working copy again so we can inform the user if paths couldn't + // be untracked because they're not ignored. let (new_wc_tree, stats) = locked_ws.locked_wc().snapshot(&options).await?; if new_wc_tree.tree_ids() != new_commit.tree_ids() { let added_back = new_wc_tree.entries_matching(matcher.as_ref()).collect_vec(); @@ -97,8 +97,9 @@ pub(crate) async fn cmd_file_untrack( Make sure they're ignored, then try again.", )); } else { - // This means there were some concurrent changes made in the working copy. We - // don't want to mix those in, so reset the working copy again. + // This means there were some concurrent changes made in the working + // copy. We don't want to mix those in, so reset the + // working copy again. locked_ws.locked_wc().reset(&new_commit).await?; } } diff --git a/cli/src/commands/fix.rs b/cli/src/commands/fix.rs index 664167fc45b..525182ce041 100644 --- a/cli/src/commands/fix.rs +++ b/cli/src/commands/fix.rs @@ -298,8 +298,8 @@ async fn fix_one_file( // subsequent matching tool gets its input from the previous matching tool's // output. - // TODO: Consider adding a check for some max file size config or some global - // limit for both `old_content` and `base_content`. + // TODO: Consider adding a check for some max file size config or some + // global limit for both `old_content` and `base_content`. let mut old_content = vec![]; let mut read = store .read_file(&file_to_fix.repo_path, &file_to_fix.file_id) @@ -311,7 +311,8 @@ async fn fix_one_file( return Ok(None); } - // Load the base content from the file_to_fix (if exists) iff any tool needs it. + // Load the base content from the file_to_fix (if exists) iff any tool needs + // it. let base_content = if all_lines_arg { None } else { @@ -335,8 +336,9 @@ async fn fix_one_file( let RegionsToFormat::LineRanges(ranges) = compute_regions_to_format(base_content.as_deref(), &prev_content); if ranges.is_empty() && !tool_config.run_tool_if_zero_line_ranges { - // Don't run the tool if there are no line ranges to format and the tool is - // configured to not run in that case. + // Don't run the tool if there are no line ranges to format and + // the tool is configured to not run in that + // case. return prev_content; } @@ -383,11 +385,12 @@ pub fn compute_regions_to_format( current_content: &[u8], ) -> RegionsToFormat { if current_content.is_empty() { - // If the current file content is empty, then there are no regions to format. + // If the current file content is empty, then there are no regions to + // format. RegionsToFormat::LineRanges(vec![]) } else if let Some(base) = base_content { - // If the base file content is available, then compute the modified line ranges - // to format between the base and current file. + // If the base file content is available, then compute the modified line + // ranges to format between the base and current file. compute_changed_ranges(base, current_content) } else { // Otherwise, format the entire file. diff --git a/cli/src/commands/gerrit/upload.rs b/cli/src/commands/gerrit/upload.rs index e6e977ecad8..2b65d96ecda 100644 --- a/cli/src/commands/gerrit/upload.rs +++ b/cli/src/commands/gerrit/upload.rs @@ -476,9 +476,9 @@ pub async fn cmd_gerrit_upload( return Ok(()); } - // If you have the changes main -> A -> B, and then run `jj gerrit upload -r B`, - // then that uploads both A and B. Thus, we need to ensure that A also - // has a Change-ID. + // If you have the changes main -> A -> B, and then run `jj gerrit upload -r + // B`, then that uploads both A and B. Thus, we need to ensure that A + // also has a Change-ID. // We make an assumption here that all immutable commits already have a // Change-ID. let to_upload: Vec = workspace_command @@ -580,8 +580,9 @@ pub async fn cmd_gerrit_upload( original_commit.description().to_owned() } else { - // Gerrit change id is 40 chars, jj change id is 32, so we need padding. - // To be consistent with `format_gerrit_change_id_trailer``, we pad with + // Gerrit change id is 40 chars, jj change id is 32, so we need + // padding. To be consistent with + // `format_gerrit_change_id_trailer``, we pad with // 6a6a6964 (hex of "jjid"). let gerrit_change_id = format!("I{}6a6a6964", original_commit.change_id().hex()); diff --git a/cli/src/commands/git/colocation.rs b/cli/src/commands/git/colocation.rs index d74a4d89215..4d45d0639b2 100644 --- a/cli/src/commands/git/colocation.rs +++ b/cli/src/commands/git/colocation.rs @@ -169,8 +169,8 @@ async fn cmd_git_colocation_enable( return Ok(()); } - // And that it has a working copy (whose parent we'll use later to set the git - // HEAD) + // And that it has a working copy (whose parent we'll use later to set the + // git HEAD) let wc_commit_id = workspace_command .get_wc_commit_id() .ok_or_else(|| user_error("This command requires a working copy"))? diff --git a/cli/src/commands/git/init.rs b/cli/src/commands/git/init.rs index d33fbc76b4e..a47e12403fa 100644 --- a/cli/src/commands/git/init.rs +++ b/cli/src/commands/git/init.rs @@ -331,17 +331,19 @@ pub fn maybe_set_repository_level_trunk_alias( .try_find_reference(&ref_name) .map_err(internal_error)? { - // Found a HEAD reference for this remote. Even if we can't parse it, - // we should stop here and not try other remotes because it doesn't - // really make sense if "origin" were to be set as the default if we - // know "upstream" exists. + // Found a HEAD reference for this remote. Even if we can't parse + // it, we should stop here and not try other remotes + // because it doesn't really make sense if "origin" were + // to be set as the default if we know "upstream" + // exists. if let Some(reference_name) = reference.target().try_name() && let Some((GitRefKind::Bookmark, symbol)) = str::from_utf8(reference_name.as_bstr()) .ok() .and_then(|name| parse_git_ref(name.as_ref())) { - // TODO: Can we assume the symbolic target points to the same remote? + // TODO: Can we assume the symbolic target points to the same + // remote? let symbol = symbol.name.to_remote_symbol(remote.as_ref()); write_repo_presets( ui, diff --git a/cli/src/commands/git/push.rs b/cli/src/commands/git/push.rs index ef6de4769ef..d9f5c52a939 100644 --- a/cli/src/commands/git/push.rs +++ b/cli/src/commands/git/push.rs @@ -351,7 +351,8 @@ pub async fn cmd_git_push( } } } else if args.deleted { - // There shouldn't be new heads to push, but we run validation for consistency. + // There shouldn't be new heads to push, but we run validation for + // consistency. let mut commits_validator = CommitsValidator::new(ui, tx.base_workspace_helper(), remote, args)?; for (name, targets) in view.local_remote_bookmarks(remote) { @@ -1192,8 +1193,8 @@ async fn create_change_bookmarks( changes: &[RevisionArg], ) -> Result, CommandError> { if changes.is_empty() { - // NOTE: we don't want resolve_some_revsets_default_single to fail if the - // changes argument wasn't provided, so handle that + // NOTE: we don't want resolve_some_revsets_default_single to fail if + // the changes argument wasn't provided, so handle that return Ok(vec![]); } @@ -1252,8 +1253,8 @@ fn find_bookmarks_to_push<'a>( let matching_bookmarks = view .local_remote_bookmarks_matching(&bookmark_matcher, remote) .filter(|(_, targets)| { - // If the remote exists but is not tracked, the absent local shouldn't - // be considered a deleted bookmark. + // If the remote exists but is not tracked, the absent local + // shouldn't be considered a deleted bookmark. targets.local_target.is_present() || targets.remote_ref.is_tracked() }) .collect(); @@ -1287,8 +1288,8 @@ fn find_tags_to_push<'a>( let matching_tags = view .local_remote_tags_matching(&tag_matcher, remote) .filter(|(_, targets)| { - // If the remote exists but is not tracked, the absent local shouldn't - // be considered a deleted tag. + // If the remote exists but is not tracked, the absent local + // shouldn't be considered a deleted tag. targets.local_target.is_present() || targets.remote_ref.is_tracked() }) .collect(); diff --git a/cli/src/commands/git/remote/add.rs b/cli/src/commands/git/remote/add.rs index a84daeeafa7..dbfa348da1d 100644 --- a/cli/src/commands/git/remote/add.rs +++ b/cli/src/commands/git/remote/add.rs @@ -98,8 +98,8 @@ fn warn_if_remote_url_matches( .iter() .flatten() .any(|remote_url| remote_url == new_fetch_url || remote_url == new_push_url); - // Don't print the URL itself because remote URLs can contain credentials, - // such as user:password or token path segments. + // Don't print the URL itself because remote URLs can contain + // credentials, such as user:password or token path segments. if remote_url_matches { writeln!( ui.warning_default(), diff --git a/cli/src/commands/log.rs b/cli/src/commands/log.rs index 2a76fdbbb63..0d6d8547338 100644 --- a/cli/src/commands/log.rs +++ b/cli/src/commands/log.rs @@ -239,8 +239,9 @@ pub(crate) async fn cmd_log( } let forward_stream = topo_order.stream(); - // The input to TopoGroupedGraph shouldn't be truncated because the prioritized - // commit must exist in the input set. + // The input to TopoGroupedGraph shouldn't be truncated because + // the prioritized commit must exist in the + // input set. let forward_stream = forward_stream.take(args.limit.unwrap_or(usize::MAX)); if args.reversed { let nodes: Vec<_> = forward_stream.collect().await; @@ -253,9 +254,10 @@ pub(crate) async fn cmd_log( while let Some((commit_id, edges)) = stream.try_next().await? { // The graph is keyed by (CommitId, is_synthetic) let mut graphlog_edges = vec![]; - // TODO: Should we update revset.stream_graph() to yield a `has_missing` flag - // instead of all the missing edges since we don't care about - // where they point here anyway? + // TODO: Should we update revset.stream_graph() to yield a + // `has_missing` flag instead of all the missing + // edges since we don't care about where they + // point here anyway? let mut missing_edge_id = None; let mut elided_targets = vec![]; for edge in edges { @@ -384,7 +386,8 @@ pub(crate) async fn cmd_log( // to specify a revset. if let ([], [only_path]) = (args.revisions.as_slice(), args.paths.as_slice()) { if only_path == "." && workspace_command.parse_file_path(only_path)?.is_root() { - // For users of e.g. Mercurial, where `.` indicates the current commit. + // For users of e.g. Mercurial, where `.` indicates the current + // commit. writeln!( ui.warning_default(), "The argument {only_path:?} is being interpreted as a fileset expression, but \ diff --git a/cli/src/commands/new.rs b/cli/src/commands/new.rs index e92ff8c16ac..12ac7b4bd84 100644 --- a/cli/src/commands/new.rs +++ b/cli/src/commands/new.rs @@ -227,9 +227,10 @@ pub(crate) async fn cmd_new( }; if !description.is_empty() { // The first trailer would become the first line of the description. - // Also, a commit with no description is treated in a special way in jujutsu: it - // can be discarded as soon as it's no longer the working copy. Adding a - // trailer to an empty description would break that logic. + // Also, a commit with no description is treated in a special way in + // jujutsu: it can be discarded as soon as it's no longer the + // working copy. Adding a trailer to an empty description would + // break that logic. commit_builder.set_description(&description); let description = add_trailers(ui, &tx, &commit_builder).await?; commit_builder.set_description(&description); @@ -245,9 +246,10 @@ pub(crate) async fn cmd_new( let mut num_rebased = 0; for child_commit in child_commits { let mut new_parent_ids = IndexSet::new(); - // If the original parents of the children commits are the parents of the new - // commit, replace them with the new commit since we are "inserting" the new - // commit in between the parents and the children. + // If the original parents of the children commits are the parents of + // the new commit, replace them with the new commit since we are + // "inserting" the new commit in between the parents and the + // children. for old_parent_id in child_commit.parent_ids() { if parent_commit_ids_set.contains(old_parent_id) { new_parent_ids.insert(new_commit.id().clone()); diff --git a/cli/src/commands/operation/diff.rs b/cli/src/commands/operation/diff.rs index cbb513fc162..67a5d32948b 100644 --- a/cli/src/commands/operation/diff.rs +++ b/cli/src/commands/operation/diff.rs @@ -396,8 +396,9 @@ pub async fn show_op_diff( for (name, (from_commit, to_commit)) in changed_working_copies { with_content_format .write(formatter, async |formatter| { - // Usually, there is at most one working copy changed per operation, so we put - // the working copy name in the heading. + // Usually, there is at most one working copy changed per + // operation, so we put the working copy + // name in the heading. write!(formatter, "Changed working copy ")?; write!(formatter.labeled("working_copies"), "{}@", name.as_symbol())?; writeln!(formatter, ":")?; diff --git a/cli/src/commands/operation/integrate.rs b/cli/src/commands/operation/integrate.rs index e22cc810f53..d0b42ff0516 100644 --- a/cli/src/commands/operation/integrate.rs +++ b/cli/src/commands/operation/integrate.rs @@ -52,7 +52,8 @@ pub async fn cmd_op_integrate( repo_loader.op_heads_store().as_ref(), repo_loader.op_store(), async |op_heads| -> Result { - // TODO: It may be helpful to print each operation we're merging here + // TODO: It may be helpful to print each operation we're merging + // here let transaction_description = "reconcile divergent operations"; let merged_operation = merge_operations( Some(ui), diff --git a/cli/src/commands/operation/show.rs b/cli/src/commands/operation/show.rs index d4c8658a67a..5bc65a2292b 100644 --- a/cli/src/commands/operation/show.rs +++ b/cli/src/commands/operation/show.rs @@ -148,8 +148,8 @@ pub async fn cmd_op_show( template.format(&op, formatter.as_mut())?; if !args.no_op_diff { - // TODO: Merged repo may have newly rebased commits, which wouldn't exist in - // the index. (#4465) + // TODO: Merged repo may have newly rebased commits, which wouldn't + // exist in the index. (#4465) if parent_ops.len() > 1 { return Ok(()); } diff --git a/cli/src/commands/parallelize.rs b/cli/src/commands/parallelize.rs index bb2969419ad..b71e71fe14f 100644 --- a/cli/src/commands/parallelize.rs +++ b/cli/src/commands/parallelize.rs @@ -82,9 +82,9 @@ pub(crate) async fn cmd_parallelize( .try_collect() .await?; - // New parents for commits in the target set. Since commits in the set are now - // supposed to be independent, they inherit the parent's non-target parents, - // recursively. + // New parents for commits in the target set. Since commits in the set are + // now supposed to be independent, they inherit the parent's non-target + // parents, recursively. let mut new_target_parents: HashMap> = HashMap::new(); let mut needs_rewrite = Vec::new(); for commit in target_commits.iter().rev() { @@ -103,9 +103,10 @@ pub(crate) async fn cmd_parallelize( workspace_command.check_rewritable(needs_rewrite).await?; let mut tx = workspace_command.start_transaction(); - // If a commit outside the target set has a commit in the target set as parent, - // then - after the transformation - it should also have that commit's - // parents as direct parents, if those commits are also in the target set. + // If a commit outside the target set has a commit in the target set as + // parent, then - after the transformation - it should also have that + // commit's parents as direct parents, if those commits are also in the + // target set. let mut new_child_parents: HashMap> = HashMap::new(); for commit in target_commits.iter().rev() { let mut new_parents = IndexSet::new(); @@ -122,8 +123,8 @@ pub(crate) async fn cmd_parallelize( .transform_descendants( target_commits.iter().ids().cloned().collect_vec(), async |mut rewriter| { - // Commits in the target set do not depend on each other but they still depend - // on other parents + // Commits in the target set do not depend on each other but + // they still depend on other parents if let Some(new_parents) = new_target_parents.get(rewriter.old_commit().id()) { rewriter.set_new_rewritten_parents(new_parents); } else if rewriter diff --git a/cli/src/commands/redo.rs b/cli/src/commands/redo.rs index 2cc0ffd2725..ebf6c9ee013 100644 --- a/cli/src/commands/redo.rs +++ b/cli/src/commands/redo.rs @@ -54,13 +54,13 @@ pub async fn cmd_redo( // // - If the operation to redo is a regular one (neither an undo- or // redo-operation): Fail, because there is nothing to redo. - // - If the operation to redo is an undo-operation, try to redo it (by restoring - // its parent operation). - // - If the operation to redo is a redo-operation itself, redo the operation the - // early redo-operation restored to. - // - If the operation to restore to is a redo-operation itself, restore directly - // to the original operation. This avoids creating a linked list of - // redo-operations, which subsequently may have to be walked with an + // - If the operation to redo is an undo-operation, try to redo it (by + // restoring its parent operation). + // - If the operation to redo is a redo-operation itself, redo the operation + // the early redo-operation restored to. + // - If the operation to restore to is a redo-operation itself, restore + // directly to the original operation. This avoids creating a linked list + // of redo-operations, which subsequently may have to be walked with an // inefficient loop. // // This described behavior leads to "jumping over" old redo-stacks if the diff --git a/cli/src/commands/revert.rs b/cli/src/commands/revert.rs index 0aff2e132a7..cc7b949cd9c 100644 --- a/cli/src/commands/revert.rs +++ b/cli/src/commands/revert.rs @@ -201,18 +201,19 @@ pub(crate) async fn cmd_revert( if children_commit_ids_set.contains(rewriter.old_commit().id()) { let mut child_new_parent_ids = IndexSet::new(); for old_parent_id in rewriter.old_commit().parent_ids() { - // If the original parents of the new children are the new parents of - // `target_head_ids`, replace them with `new_head_ids` since we are - // "inserting" the new commits in between the new parents and the new - // children. + // If the original parents of the new children are the new + // parents of `target_head_ids`, replace + // them with `new_head_ids` since we are + // "inserting" the new commits in between the new parents + // and the new children. if original_parent_commit_ids.contains(old_parent_id) { child_new_parent_ids.extend(new_head_ids.clone()); } else { child_new_parent_ids.insert(old_parent_id.clone()); } } - // If not already present, add `new_head_ids` as parents of the new child - // commit. + // If not already present, add `new_head_ids` as parents of the + // new child commit. child_new_parent_ids.extend(new_head_ids.clone()); rewriter.set_new_parents(child_new_parent_ids.into_iter().collect()); } diff --git a/cli/src/commands/run.rs b/cli/src/commands/run.rs index 3e386a5e57c..46d620f7813 100644 --- a/cli/src/commands/run.rs +++ b/cli/src/commands/run.rs @@ -473,8 +473,8 @@ async fn rewrite_commit( working_copy_dir.clone() }; - // TODO: Later this should take some trait which allows `run` to integrate with - // something like Bazels RE protocol. + // TODO: Later this should take some trait which allows `run` to integrate + // with something like Bazels RE protocol. // e.g // ``` // let mut executor /* Arc */ = store.get_executor(); @@ -523,9 +523,10 @@ async fn rewrite_commit( if !output.status.success() { // Remove non-ignored untracked files left by the command. Ignored paths - // are absent from `untracked_paths` and survive for build-artifact reuse. - // This keeps the slot free of stale files that would cause silent - // `skipped_files` collisions in the next `check_out`. + // are absent from `untracked_paths` and survive for build-artifact + // reuse. This keeps the slot free of stale files that would + // cause silent `skipped_files` collisions in the next + // `check_out`. for path in stats.untracked_paths.keys() { let abs = path.to_fs_path_unchecked(&working_copy_dir); if let Err(err) = fs::remove_file(&abs) @@ -810,8 +811,8 @@ pub async fn cmd_run( if let Some(status) = res.status { // Emit the subprocess's captured streams. Acquiring // `ui.stdout()` / `ui.stderr()` for the duration of the - // write keeps each commit's output from interleaving with - // another's. + // write keeps each commit's output from interleaving + // with another's. if !res.stdout.is_empty() { let mut out = ui.stdout(); out.write_all(&res.stdout)?; diff --git a/cli/src/commands/split.rs b/cli/src/commands/split.rs index 4da3cc5f66f..41086cf141b 100644 --- a/cli/src/commands/split.rs +++ b/cli/src/commands/split.rs @@ -516,7 +516,8 @@ async fn rewrite_descendants( async |mut rewriter: CommitRewriter<'_>| { num_rebased += 1; if parallel && legacy_bookmark_behavior { - // The old_parent is the second commit due to the rewrite above. + // The old_parent is the second commit due to the rewrite + // above. rewriter.replace_parent( second_commit.id(), [first_commit.id(), second_commit.id()], diff --git a/cli/src/commands/squash.rs b/cli/src/commands/squash.rs index 3d67092a15a..f4a47800b1d 100644 --- a/cli/src/commands/squash.rs +++ b/cli/src/commands/squash.rs @@ -213,9 +213,9 @@ pub(crate) async fn cmd_squash( sources.retain(|source| source.id() != destination.id()); pre_existing_destination = Some(destination); } - // Reverse the set so we apply the oldest commits first. It shouldn't affect the - // result, but it avoids creating transient conflicts and is therefore probably - // a little faster. + // Reverse the set so we apply the oldest commits first. It shouldn't + // affect the result, but it avoids creating transient conflicts + // and is therefore probably a little faster. sources.reverse(); } else { let revision_arg = args.revision.as_ref().unwrap_or(&RevisionArg::AT); @@ -389,7 +389,8 @@ pub(crate) async fn cmd_squash( &commit_builder, ) .await?; - // It's weird that commit.description() contains "JJ: " lines, but works. + // It's weird that commit.description() contains "JJ: " lines, but + // works. commit_builder.set_description(combined); let temp_commit = commit_builder.write_hidden().await?; let intro = "Enter a description for the combined commit."; @@ -468,7 +469,8 @@ enum SquashedDescription { impl SquashedDescription { fn from_args(args: &SquashArgs) -> Self { - // These options are incompatible and Clap is configured to prevent this. + // These options are incompatible and Clap is configured to prevent + // this. assert!(args.message_paragraphs.is_none() || !args.use_destination_message); if let Some(paragraphs) = &args.message_paragraphs { diff --git a/cli/src/commands/status.rs b/cli/src/commands/status.rs index c38433961a4..675d84219f8 100644 --- a/cli/src/commands/status.rs +++ b/cli/src/commands/status.rs @@ -171,7 +171,8 @@ pub(crate) async fn cmd_status( let wc_revset = RevsetExpression::commit(status.commit.id().clone()); - // Ancestors with conflicts, excluding the current working copy commit. + // Ancestors with conflicts, excluding the current working copy + // commit. let ancestors_conflicts: Vec<_> = workspace_command .attach_revset_evaluator( wc_revset diff --git a/cli/src/commands/tag/list.rs b/cli/src/commands/tag/list.rs index 9fab3efec5b..6e104ef567f 100644 --- a/cli/src/commands/tag/list.rs +++ b/cli/src/commands/tag/list.rs @@ -143,7 +143,8 @@ pub async fn cmd_tag_list( (None, None) => StringExpression::all(), }; let matched_local_targets: HashSet<_> = if let Some(revisions) = &args.revisions { - // Match against local targets only, which is consistent with "jj git push". + // Match against local targets only, which is consistent with "jj git + // push". let mut expression = workspace_command.parse_union_revsets(ui, revisions)?; // Intersects with the set of local tag targets to minimize the lookup // space. diff --git a/cli/src/commands/undo.rs b/cli/src/commands/undo.rs index e2d400e11df..da45515f177 100644 --- a/cli/src/commands/undo.rs +++ b/cli/src/commands/undo.rs @@ -56,12 +56,12 @@ pub async fn cmd_undo( // Growing the "undo-stack" works as follows. See also the // [redo-stack](./redo.rs), which works in a similar way. // - // - If the operation to undo is a regular one (not an undo-operation), simply - // undo it (== restore its parent). - // - If the operation to undo is an undo-operation itself, undo that operation - // to which the previous undo-operation restored the repo. - // - If the operation to restore to is an undo-operation, restore directly to - // the original operation. This avoids creating a linked list of + // - If the operation to undo is a regular one (not an undo-operation), + // simply undo it (== restore its parent). + // - If the operation to undo is an undo-operation itself, undo that + // operation to which the previous undo-operation restored the repo. + // - If the operation to restore to is an undo-operation, restore directly + // to the original operation. This avoids creating a linked list of // undo-operations, which subsequently may have to be walked with an // inefficient loop. // diff --git a/cli/src/commands/util/markdown_help.rs b/cli/src/commands/util/markdown_help.rs index a3209de578a..0f0b9f36aca 100644 --- a/cli/src/commands/util/markdown_help.rs +++ b/cli/src/commands/util/markdown_help.rs @@ -27,8 +27,8 @@ pub async fn cmd_util_markdown_help( command: &CommandHelper, _args: &UtilMarkdownHelp, ) -> Result<(), CommandError> { - // If we ever need more flexibility, the code of `clap_markdown` is simple and - // readable. We could reimplement the parts we need without trouble. + // If we ever need more flexibility, the code of `clap_markdown` is simple + // and readable. We could reimplement the parts we need without trouble. let markdown = clap_markdown::help_markdown_command(command.app()).into_bytes(); ui.stdout().write_all(&markdown)?; Ok(()) diff --git a/cli/src/commands/workspace/add.rs b/cli/src/commands/workspace/add.rs index bbd0205086b..1432c0d7195 100644 --- a/cli/src/commands/workspace/add.rs +++ b/cli/src/commands/workspace/add.rs @@ -181,8 +181,9 @@ pub async fn cmd_workspace_add( // If no parent revisions are specified, create a working-copy commit based // on the parent of the current working-copy commit. let parents = if args.revisions.is_empty() { - // Check out parents of the current workspace's working-copy commit, or the - // root if there is no working-copy commit in the current workspace. + // Check out parents of the current workspace's working-copy commit, or + // the root if there is no working-copy commit in the current + // workspace. if let Some(old_wc_commit_id) = tx .base_repo() .view() @@ -214,9 +215,10 @@ pub async fn cmd_workspace_add( let mut description = join_message_paragraphs(&args.message_paragraphs); if !description.is_empty() { // The first trailer would become the first line of the description. - // Also, a commit with no description is treated in a special way in jujutsu: it - // can be discarded as soon as it's no longer the working copy. Adding a - // trailer to an empty description would break that logic. + // Also, a commit with no description is treated in a special way in + // jujutsu: it can be discarded as soon as it's no longer the + // working copy. Adding a trailer to an empty description would + // break that logic. commit_builder.set_description(description); description = add_trailers(ui, &tx, &commit_builder).await?; } diff --git a/cli/src/commit_ref_list.rs b/cli/src/commit_ref_list.rs index 9408f1d8e30..7ce9ec6c885 100644 --- a/cli/src/commit_ref_list.rs +++ b/cli/src/commit_ref_list.rs @@ -348,8 +348,8 @@ mod tests { move || iter.next().unwrap() } - // Helper function to prepare test data, sort and prepare snapshot with relevant - // information. + // Helper function to prepare test data, sort and prepare snapshot with + // relevant information. fn prepare_data_sort_and_snapshot(sort_keys: &[SortKey]) -> String { let mut new_commit_id = commit_id_generator(); let mut new_timestamp = commit_ts_generator(); @@ -449,7 +449,8 @@ mod tests { sort_and_snapshot(&mut bookmark_items, sort_keys, &commits) } - // Helper function to sort refs and prepare snapshot with relevant information. + // Helper function to sort refs and prepare snapshot with relevant + // information. fn sort_and_snapshot( items: &mut [RefListItem], sort_keys: &[SortKey], diff --git a/cli/src/commit_templater.rs b/cli/src/commit_templater.rs index eec1dc5c480..87fd455a6e2 100644 --- a/cli/src/commit_templater.rs +++ b/cli/src/commit_templater.rs @@ -1024,9 +1024,10 @@ impl<'repo> CommitKeywordCache<'repo> { language: &CommitTemplateLanguage<'repo>, span: pest::Span<'_>, ) -> TemplateParseResult<&Rc>> { - // Alternatively, a negated (i.e. visible mutable) set could be computed. - // It's usually smaller than the immutable set. The revset engine can also - // optimize "::" query to use bitset-based implementation. + // Alternatively, a negated (i.e. visible mutable) set could be + // computed. It's usually smaller than the immutable set. The + // revset engine can also optimize "::" query to + // use bitset-based implementation. self.is_immutable_fn.get_or_try_init(|| { let expression = &language.immutable_expression; let revset = evaluate_revset_expression(language, span, expression)?; @@ -1726,8 +1727,8 @@ impl Template for Rc { write!(formatter, "@")?; write!(formatter.labeled("remote"), "{remote}")?; } - // Don't show both conflict and unsynced sigils as conflicted ref wouldn't - // be pushed. + // Don't show both conflict and unsynced sigils as conflicted ref + // wouldn't be pushed. if self.has_conflict() { write!(formatter, "??")?; } else if self.is_local() && !self.synced { @@ -1780,9 +1781,10 @@ impl WorkspaceRef { let workspace_loader = DefaultWorkspaceLoaderFactory.create(base)?; let repo_path = workspace_loader.repo_path().to_owned(); let workspace_store = SimpleWorkspaceStore::load(&repo_path)?; - // Workspaces created before jj 0.38.0 may not have a recorded path. List - // templates should also keep rendering if a recorded path is stale or - // unavailable. Use `jj workspace root --name` for strict path diagnostics. + // Workspaces created before jj 0.38.0 may not have a recorded path. + // List templates should also keep rendering if a recorded path + // is stale or unavailable. Use `jj workspace root --name` for + // strict path diagnostics. let path = workspace_store .get_workspace_path(self.name())? .map(|workspace_path| repo_path.join(workspace_path)) diff --git a/cli/src/complete.rs b/cli/src/complete.rs index 49d347ed739..b125399900a 100644 --- a/cli/src/complete.rs +++ b/cli/src/complete.rs @@ -358,8 +358,8 @@ fn revisions(match_prefix: &str, revset_filter: Option<&str>) -> Vec) -> Vec 1 { candidates.extend(stdout.lines().filter_map(|name| { let symbol = format!("{name}@"); @@ -865,9 +865,9 @@ fn path_completion_candidate_from( let path = slash_path(path); let mut remainder = path.to_str()?.strip_prefix(normalized_prefix)?; - // Trailing slash might have been normalized away in which case we need to strip - // the leading slash in the remainder away, or else the slash would appear - // twice. + // Trailing slash might have been normalized away in which case we need to + // strip the leading slash in the remainder away, or else the slash + // would appear twice. if current_prefix.ends_with(std::path::is_separator) { remainder = remainder.strip_prefix('/').unwrap_or(remainder); } diff --git a/cli/src/config.rs b/cli/src/config.rs index a4d82d964d1..802a855763b 100644 --- a/cli/src/config.rs +++ b/cli/src/config.rs @@ -168,7 +168,8 @@ pub fn resolved_config_values( // Cannot retain inline table formatting because inner values may be // overridden independently. if let Some(table) = item.as_table_like() { - // current table and children may be shadowed by value in upper layer + // current table and children may be shadowed by value in upper + // layer let is_overridden = is_parent_overridden || upper_value_names.contains(&name); for (k, v) in table.iter() { let mut sub_name = name.clone(); @@ -176,7 +177,8 @@ pub fn resolved_config_values( config_stack.push((sub_name, v, is_overridden)); // in reverse order } } else { - // current value may be shadowed by value or table in upper layer + // current value may be shadowed by value or table in upper + // layer let maybe_child = upper_value_names .range(&name..) .next() @@ -388,7 +390,8 @@ impl ConfigEnv { }; let environment = env::vars_os() .filter_map(|(k, v)| { - // Silently ignore non-Unicode environment variables. Don't panic like vars() + // Silently ignore non-Unicode environment variables. Don't + // panic like vars() let k = k.into_string().ok()?; let v = v.into_string().ok()?; Some((k, v)) @@ -750,8 +753,8 @@ fn env_base_layer() -> ConfigLayer { layer.set_value(OP_USERNAME, value).unwrap(); } if !env::var("NO_COLOR").unwrap_or_default().is_empty() { - // "User-level configuration files and per-instance command-line arguments - // should override $NO_COLOR." https://no-color.org/ + // "User-level configuration files and per-instance command-line + // arguments should override $NO_COLOR." https://no-color.org/ layer.set_value("ui.color", "never").unwrap(); } if let Ok(value) = env::var("VISUAL") { @@ -765,8 +768,8 @@ fn env_base_layer() -> ConfigLayer { } pub fn default_config_layers() -> Vec { - // Syntax error in default config isn't a user error. That's why defaults are - // loaded by separate builder. + // Syntax error in default config isn't a user error. That's why defaults + // are loaded by separate builder. let parse = |text: &'static str| ConfigLayer::parse(ConfigSource::Default, text).unwrap(); let mut layers = vec![ parse(include_str!("config/colors.toml")), diff --git a/cli/src/description_util.rs b/cli/src/description_util.rs index 834f5656f28..b814422b3c7 100644 --- a/cli/src/description_util.rs +++ b/cli/src/description_util.rs @@ -332,7 +332,8 @@ pub async fn combine_messages_for_editing( } if let Some(template) = parse_trailers_template(ui, tx)? { - // show the user only trailers that were not in one of the squashed commits + // show the user only trailers that were not in one of the squashed + // commits let old_trailers: Vec<_> = sources .iter() .chain(destination) @@ -362,8 +363,8 @@ pub async fn combine_messages_for_editing( /// Based on the Git CLI behavior. See `opt_parse_m()` and `cleanup_mode` in /// `git/builtin/commit.c`. pub fn join_message_paragraphs(paragraphs: &[String]) -> String { - // Ensure each paragraph ends with a newline, then add another newline between - // paragraphs. + // Ensure each paragraph ends with a newline, then add another newline + // between paragraphs. paragraphs .iter() .map(|p| text_util::complete_newline(p.as_str())) diff --git a/cli/src/diff_util.rs b/cli/src/diff_util.rs index d6d1420daf4..cf257b7c72f 100644 --- a/cli/src/diff_util.rs +++ b/cli/src/diff_util.rs @@ -185,8 +185,9 @@ enum BuiltinFormatKind { impl BuiltinFormatKind { // Alternatively, we could use or vendor one of the crates `strum`, - // `enum-iterator`, or `variant_count` (for a check that the length of the array - // is correct). The latter is very simple and is also a nightly feature. + // `enum-iterator`, or `variant_count` (for a check that the length of the + // array is correct). The latter is very simple and is also a nightly + // feature. const ALL_VARIANTS: &[Self] = &[ Self::Summary, Self::Stat, @@ -2091,8 +2092,8 @@ pub fn show_diff_stats( // rest. Start with the longest path. The code below might shorten it. let mut max_path_width = ui_paths.iter().map(|s| s.width()).max().unwrap_or(0); - // Fit to the available display width, but always assume at least a tiny bit of - // room. + // Fit to the available display width, but always assume at least a tiny bit + // of room. let available_width = max(total_display_width.saturating_sub(" | ".len()), 8); // Measure the widest right side for line diffs and reduce max_path_width if @@ -2130,8 +2131,8 @@ pub fn show_diff_stats( max_path_width = max_path_width.min(available_width.saturating_sub(width)); } - // Now that we've chosen the path width, use the rest of the space for the ++-- - // bar. + // Now that we've chosen the path width, use the rest of the space for the + // ++-- bar. let mut max_bar_width = available_width.saturating_sub(max_path_width + diff_number_width + " ".len()); @@ -2155,12 +2156,14 @@ pub fn show_diff_stats( )?; if let Some((added, removed)) = stat.added_removed { let bar_length = ((added + removed) as f64 * factor) as usize; - // If neither adds nor removes are present, bar length should be zero. - // If only one is present, bar length should be at least 1. - // If both are present, bar length should be at least 2. + // If neither adds nor removes are present, bar length should be + // zero. If only one is present, bar length should be at + // least 1. If both are present, bar length should be at + // least 2. // - // Fractional space after scaling is given to whichever of adds/removes is - // smaller, to show at least one tick for small (but nonzero) counts. + // Fractional space after scaling is given to whichever of + // adds/removes is smaller, to show at least one tick + // for small (but nonzero) counts. let bar_length = bar_length.max(usize::from(added > 0) + usize::from(removed > 0)); let (bar_added, bar_removed) = if added < removed { let len = (added as f64 * factor).ceil() as usize; diff --git a/cli/src/formatter.rs b/cli/src/formatter.rs index fdc8ee4b52c..c0503f4b7a7 100644 --- a/cli/src/formatter.rs +++ b/cli/src/formatter.rs @@ -357,15 +357,17 @@ impl ColorFormatter { if let Some(cached) = self.cached_styles.get(&self.labels) { cached.clone() } else { - // We use the reverse list of matched indices as a measure of how well the rule - // matches the actual labels. For example, for rule "a d" and the actual labels - // "a b c d", we'll get [3,0]. We compare them by Rust's default Vec comparison. + // We use the reverse list of matched indices as a measure of how + // well the rule matches the actual labels. For example, + // for rule "a d" and the actual labels "a b c d", we'll + // get [3,0]. We compare them by Rust's default Vec comparison. // That means "a d" will trump both rule "d" (priority [3]) and rule // "a b c" (priority [2,1,0]). let mut matched_styles = vec![]; for (labels, style) in self.rules.as_ref() { let mut labels_iter = self.labels.iter().enumerate(); - // The indexes in the current label stack that match the required label. + // The indexes in the current label stack that match the + // required label. let mut matched_indices = vec![]; for required_label in labels { for (label_index, label) in &mut labels_iter { @@ -1128,7 +1130,8 @@ mod tests { #[test] fn test_color_formatter_bold_reset() -> TestResult { - // Test that we don't lose other attributes when we reset the bold attribute. + // Test that we don't lose other attributes when we reset the bold + // attribute. let config = config_from_string(indoc! {" [colors] not_bold = { fg = 'red', bg = 'blue', italic = true, underline = true } @@ -1157,7 +1160,8 @@ mod tests { #[test] fn test_color_formatter_dim_reset() -> TestResult { - // Test that we don't lose other attributes when we reset the dim attribute. + // Test that we don't lose other attributes when we reset the dim + // attribute. let config = config_from_string(indoc! {" [colors] not_dim = { fg = 'red', bg = 'blue', italic = true, underline = true } @@ -1301,9 +1305,10 @@ mod tests { #[test] fn test_color_formatter_nested() -> TestResult { - // A color can be associated with a combination of labels. A more specific match - // overrides a less specific match. After the inner label is removed, the outer - // color is used again (we don't reset). + // A color can be associated with a combination of labels. A more + // specific match overrides a less specific match. After the + // inner label is removed, the outer color is used again (we + // don't reset). let config = config_from_string( r#" colors.outer = "blue" @@ -1421,8 +1426,8 @@ mod tests { #[test] fn test_color_formatter_normal_color() -> TestResult { - // The "default" color resets the color. It is possible to reset only the - // background or only the foreground. + // The "default" color resets the color. It is possible to reset only + // the background or only the foreground. let config = config_from_string( r#" colors."outer" = {bg="yellow", fg="blue"} @@ -1524,8 +1529,8 @@ mod tests { #[test] fn test_color_formatter_dropped() -> TestResult { - // Test that the style gets reset if the formatter is dropped without popping - // all labels. + // Test that the style gets reset if the formatter is dropped without + // popping all labels. let config = config_from_string( r#" colors.outer = "green" @@ -1543,8 +1548,9 @@ mod tests { #[test] fn test_color_formatter_debug() -> TestResult { - // Behaves like the color formatter, but surrounds each write with <<...>>, - // adding the active labels before the actual content separated by a ::. + // Behaves like the color formatter, but surrounds each write with + // <<...>>, adding the active labels before the actual content + // separated by a ::. let config = config_from_string( r#" colors.outer = "green" diff --git a/cli/src/git_util.rs b/cli/src/git_util.rs index d209a72d9ce..293c7a01302 100644 --- a/cli/src/git_util.rs +++ b/cli/src/git_util.rs @@ -74,10 +74,11 @@ pub fn is_colocated_git_workspace(workspace: &Workspace) -> Result Result { - // Git appears to turn URL-like source to absolute path if local git directory - // exits, and fails because '$PWD/https' is unsupported protocol. Since it would - // be tedious to copy the exact git (or libgit2) behavior, we simply let gix - // parse the input as URL, rcp-like, or local path. + // Git appears to turn URL-like source to absolute path if local git + // directory exits, and fails because '$PWD/https' is unsupported + // protocol. Since it would be tedious to copy the exact git (or + // libgit2) behavior, we simply let gix parse the input as URL, + // rcp-like, or local path. let mut url = gix::url::parse(source).map_err(cli_error)?; url.canonicalize(cwd).map_err(user_error)?; // As of gix 0.68.0, the canonicalized path uses platform-native directory @@ -85,7 +86,8 @@ pub fn absolute_git_url(cwd: &Path, source: &str) -> Result { if file_mode_change_selected { - // File contents haven't changed, but file mode needs to be updated on the tree. + // File contents haven't changed, but file mode needs to be + // updated on the tree. let value = override_file_executable_bit(select_left(&path).await?, executable); tree_builder.set_or_remove(path, value); } else { @@ -531,7 +532,8 @@ async fn apply_changes( old_description: _, new_description: None, } => { - // File contents emptied out, but file mode is not absent => write empty file. + // File contents emptied out, but file mode is not absent => + // write empty file. let value = write_file(&path, &[], executable).await?; tree_builder.set_or_remove(path, value); } @@ -1016,10 +1018,11 @@ mod tests { create_left_tree: impl FnOnce(&Arc, &RepoPath, bool) -> MergedTree, create_right_tree: impl FnOnce(&Arc, &RepoPath, bool) -> MergedTree, ) { - // In this test, we create 2 trees that consist of only one file under the same - // path. The executable bits are the same. Either of the left tree and the right - // tree can be resolved or have conflicts. Regardless of whether the file is - // resolved or have conflicts, the file has the same executable bit in both + // In this test, we create 2 trees that consist of only one file under + // the same path. The executable bits are the same. Either of + // the left tree and the right tree can be resolved or have + // conflicts. Regardless of whether the file is resolved or have + // conflicts, the file has the same executable bit in both // trees, so we don't expect a file mode section in the diff. let test_repo = TestRepo::init(); @@ -1924,8 +1927,9 @@ mod tests { ] "#); let no_changes_tree = apply_diff(store, &left_tree, &right_tree, &changed_files, &files); - // TODO: we should ensure that `jj diffedit` preserves labels when restoring a - // conflict. It also should work when restoring conflicts of differing arities. + // TODO: we should ensure that `jj diffedit` preserves labels when + // restoring a conflict. It also should work when restoring + // conflicts of differing arities. let left_tree_without_labels = MergedTree::new( left_tree.store().clone(), left_tree.tree_ids().clone(), @@ -2201,7 +2205,8 @@ mod tests { } Transition::SetDirEntry { .. } => { - // Do nothing; this is handled by the reference state machine. + // Do nothing; this is handled by the reference state + // machine. state } } @@ -2296,7 +2301,8 @@ mod tests { } Transition::SetDirEntry { .. } => { - // Do nothing; this is handled by the reference state machine. + // Do nothing; this is handled by the reference state + // machine. state } } @@ -2315,7 +2321,8 @@ mod tests { section.set_checked(*selected); } - // Sanity checks: Does the partial selection make sense on its own? + // Sanity checks: Does the partial selection make sense on its + // own? if let Some(scm_record::Section::FileMode { is_checked, mode }) = file.sections.first() { @@ -2334,7 +2341,8 @@ mod tests { file.set_checked(true); } if !did_file_exist && is_anything_selected { - // File was created, so if any changes are selected, then so must the file + // File was created, so if any changes are selected, + // then so must the file // mode change. file.sections[0].set_checked(true); } @@ -2354,7 +2362,8 @@ mod tests { .skip(1) .any(|dir| state.prev_file_list.contains(dir)) { - // Do not create files which would create directories overwriting files. + // Do not create files which would create directories + // overwriting files. file.set_checked(false); } } @@ -2382,8 +2391,9 @@ mod tests { // If the file has been renamed, it's now in its new position. file.old_path = None; - // Only keep sections which weren't selected previously. For text files, - // transform additions which have already been applied into `Unchanged` hunks. + // Only keep sections which weren't selected previously. For + // text files, transform additions which have + // already been applied into `Unchanged` hunks. file.sections = std::mem::take(&mut file.sections) .into_iter() .flat_map(|sec| { diff --git a/cli/src/merge_tools/diff_working_copies.rs b/cli/src/merge_tools/diff_working_copies.rs index 7b5cb000b85..1741a2c4502 100644 --- a/cli/src/merge_tools/diff_working_copies.rs +++ b/cli/src/merge_tools/diff_working_copies.rs @@ -115,7 +115,8 @@ impl DiffWorkingCopies { pub(crate) fn new_utf8_temp_dir(prefix: &str) -> io::Result { let temp_dir = tempfile::Builder::new().prefix(prefix).tempdir()?; if temp_dir.path().to_str().is_none() { - // Not using .display() as we know the path contains unprintable character + // Not using .display() as we know the path contains unprintable + // character let message = format!("path {:?} is not valid UTF-8", temp_dir.path()); return Err(io::Error::new(io::ErrorKind::InvalidData, message)); } @@ -123,8 +124,8 @@ pub(crate) fn new_utf8_temp_dir(prefix: &str) -> io::Result { } pub(crate) fn set_readonly_recursively(path: &Path) -> Result<(), std::io::Error> { - // Directory permission is unchanged since files under readonly directory cannot - // be removed. + // Directory permission is unchanged since files under readonly directory + // cannot be removed. let metadata = path.symlink_metadata()?; if metadata.is_dir() { for entry in path.read_dir()? { @@ -244,8 +245,8 @@ impl DiffEditWorkingCopies { None => (None, working_copies.right.working_copy_path()), }; let output_instructions_path = output_wc_path.join("JJ-INSTRUCTIONS"); - // In the unlikely event that the file already exists, then the user will simply - // not get any instructions. + // In the unlikely event that the file already exists, then the user + // will simply not get any instructions. if output_instructions_path.exists() { return Ok(None); } @@ -272,8 +273,9 @@ diff editing in mind and be a little inaccurate. right_instructions_file .write_all(instructions.as_bytes()) .map_err(ExternalToolError::SetUpDir)?; - // Note that some diff tools might not show this message and delete the contents - // of the output dir instead. Meld does show this message. + // Note that some diff tools might not show this message and delete + // the contents of the output dir instead. Meld does + // show this message. output_instructions_file .write_all( b"\ diff --git a/cli/src/merge_tools/external.rs b/cli/src/merge_tools/external.rs index 94659152163..4f90c33f5e9 100644 --- a/cli/src/merge_tools/external.rs +++ b/cli/src/merge_tools/external.rs @@ -198,10 +198,10 @@ async fn run_mergetool_external_single_file( let uses_marker_length = find_all_variables(&editor.merge_args).contains(&"marker_length"); - // If the merge tool doesn't get conflict markers pre-populated in the output - // file and doesn't accept "$marker_length", then we should default to accepting - // MIN_CONFLICT_MARKER_LEN since the merge tool can't know about our rules for - // conflict marker length. + // If the merge tool doesn't get conflict markers pre-populated in the + // output file and doesn't accept "$marker_length", then we should + // default to accepting MIN_CONFLICT_MARKER_LEN since the merge tool + // can't know about our rules for conflict marker length. let conflict_marker_len = if editor.merge_tool_edits_conflict_markers || uses_marker_length { choose_materialized_conflict_marker_len(&file.contents) } else { @@ -244,7 +244,8 @@ async fn run_mergetool_external_single_file( let path = temp_dir.path().join(format!("{role}{suffix}")); std::fs::write(&path, contents).map_err(ExternalToolError::SetUpDir)?; if *role != "output" { - // TODO: Should actually ignore the error here, or have a warning. + // TODO: Should actually ignore the error here, or have a + // warning. set_readonly_recursively(&path).map_err(ExternalToolError::SetUpDir)?; } Ok(( @@ -269,7 +270,8 @@ async fn run_mergetool_external_single_file( })?; tracing::info!(%exit_status); - // Check whether the exit status implies that there should be conflict markers + // Check whether the exit status implies that there should be conflict + // markers let exit_status_implies_conflict = exit_status .code() .is_some_and(|code| editor.merge_conflict_exit_codes.contains(&code)); @@ -309,9 +311,9 @@ async fn run_mergetool_external_single_file( }; // If the exit status indicated there should be conflict markers but there - // weren't any, it's likely that the tool generated invalid conflict markers, so - // we need to inform the user. If we didn't treat this as an error, the user - // might think the conflict was resolved successfully. + // weren't any, it's likely that the tool generated invalid conflict + // markers, so we need to inform the user. If we didn't treat this as an + // error, the user might think the conflict was resolved successfully. if exit_status_implies_conflict && new_file_ids.is_resolved() { return Err(ConflictResolveError::ExternalTool( ExternalToolError::InvalidConflictMarkers { exit_status }, @@ -367,8 +369,9 @@ pub async fn run_mergetool_external( return Err(err); } Err(err) => { - // Some conflicts were already resolved, so we should return an error with the - // partially-resolved tree so that the caller can save the resolved files. + // Some conflicts were already resolved, so we should return an + // error with the partially-resolved tree so + // that the caller can save the resolved files. partial_resolution_error = Some(MergeToolPartialResolutionError { source: err, resolved_count: i, @@ -508,8 +511,8 @@ pub fn invoke_external_diff( source, })?; let copy_result = io::copy(&mut child.stdout.take().unwrap(), writer); - // Non-zero exit code isn't an error. For example, the traditional diff command - // will exit with 1 if inputs are different. + // Non-zero exit code isn't an error. For example, the traditional diff + // command will exit with 1 if inputs are different. let exit_status = child.wait().map_err(ExternalToolError::Io)?; tracing::info!(?cmd, ?exit_status, "The external diff generator exited:"); let exit_ok = exit_status diff --git a/cli/src/merge_tools/mod.rs b/cli/src/merge_tools/mod.rs index 17f952105bc..3246f49d680 100644 --- a/cli/src/merge_tools/mod.rs +++ b/cli/src/merge_tools/mod.rs @@ -194,8 +194,8 @@ fn editor_args_from_settings( settings: &UserSettings, key: &'static str, ) -> Result { - // TODO: Make this configuration have a table of possible editors and detect the - // best one here. + // TODO: Make this configuration have a table of possible editors and detect + // the best one here. if let Some(args) = settings.get(key).optional()? { Ok(args) } else { @@ -478,8 +478,8 @@ async fn pick_conflict_side( ) -> Result { let mut tree_builder = MergedTreeBuilder::new(tree.clone()); for merge_tool_file in merge_tool_files { - // We use file IDs here to match the logic for the other external merge tools. - // This ensures that the behavior is consistent. + // We use file IDs here to match the logic for the other external merge + // tools. This ensures that the behavior is consistent. let file = &merge_tool_file.file; let file_id = file.ids.get_add(add_index).unwrap(); let executable = file.executable.expect("should have been resolved"); @@ -757,7 +757,8 @@ mod tests { ) "#); - // List args should never be a merge-tools key, edit_args are filled by default + // List args should never be a merge-tools key, edit_args are filled by + // default insta::assert_debug_snapshot!(get(r#"ui.diff-editor = ["meld"]"#).unwrap(), @r#" External( ExternalMergeTool { diff --git a/cli/src/template_builder.rs b/cli/src/template_builder.rs index 557a730c8e5..18d0efc70f0 100644 --- a/cli/src/template_builder.rs +++ b/cli/src/template_builder.rs @@ -4624,7 +4624,8 @@ mod tests { insta::assert_snapshot!(env.render_ok(r#""Hello World Hello".replace(regex-i:"hello", "hi")"#), @"hi World hi"); insta::assert_snapshot!(env.render_ok(r#""Hello World Hello".replace(regex-i:"hello", "hi", 1)"#), @"hi World Hello"); - // replace with strings that look regex-y ($n patterns are always expanded) + // replace with strings that look regex-y ($n patterns are always + // expanded) insta::assert_snapshot!(env.render_ok(r#"'hello\d+world'.replace('\d+', "X")"#), @"helloXworld"); insta::assert_snapshot!(env.render_ok(r#""(foo)($1)bar".replace("$1", "$2")"#), @"(foo)()bar"); insta::assert_snapshot!(env.render_ok(r#""test(abc)end".replace("(abc)", "X")"#), @"testXend"); @@ -5076,8 +5077,8 @@ mod tests { env.add_color("warning", crossterm::style::Color::DarkYellow); env.add_color("hint", crossterm::style::Color::DarkCyan); - // Empty line shouldn't be indented. Not using insta here because we test - // whitespace existence. + // Empty line shouldn't be indented. Not using insta here because we + // test whitespace existence. assert_eq!(env.render_ok(r#"indent("__", "")"#), ""); assert_eq!(env.render_ok(r#"indent("__", "\n")"#), "\n"); assert_eq!(env.render_ok(r#"indent("__", "a\n\nb")"#), "__a\n\n__b"); diff --git a/cli/src/template_parser.rs b/cli/src/template_parser.rs index 9f920b9d6ab..0b641f0a317 100644 --- a/cli/src/template_parser.rs +++ b/cli/src/template_parser.rs @@ -1486,15 +1486,16 @@ mod tests { with_aliases([("A", "a")]).parse_normalized("|| A"), parse_normalized("|| a"), ); - // No matter if 'A' is a formal parameter. Alias substitution isn't scoped. - // If we don't like this behavior, maybe we can turn off alias substitution - // for lambda parameters. + // No matter if 'A' is a formal parameter. Alias substitution isn't + // scoped. If we don't like this behavior, maybe we can turn off + // alias substitution for lambda parameters. assert_eq!( with_aliases([("A", "a ++ b")]).parse_normalized("|A| A"), parse_normalized("|A| (a ++ b)"), ); - // Infinite recursion, where the top-level error isn't of RecursiveAlias kind. + // Infinite recursion, where the top-level error isn't of RecursiveAlias + // kind. assert_eq!( with_aliases([("A", "A")]).parse("A").unwrap_err().kind, TemplateParseErrorKind::InAliasExpansion("A".to_owned()), @@ -1557,7 +1558,8 @@ mod tests { parse_normalized("|x| a"), ); - // Infinite recursion, where the top-level error isn't of RecursiveAlias kind. + // Infinite recursion, where the top-level error isn't of RecursiveAlias + // kind. assert_eq!( with_aliases([("P:x", "Q:x"), ("Q:x", "R:x"), ("R:x", "P:x")]) .parse("P:a") @@ -1652,7 +1654,8 @@ mod tests { TemplateParseErrorKind::InvalidArguments { .. } ); - // Infinite recursion, where the top-level error isn't of RecursiveAlias kind. + // Infinite recursion, where the top-level error isn't of RecursiveAlias + // kind. assert_eq!( with_aliases([("F(x)", "G(x)"), ("G(x)", "H(x)"), ("H(x)", "F(x)")]) .parse("F(a)") diff --git a/cli/src/text_util.rs b/cli/src/text_util.rs index d66d18c9703..d0497dcc74e 100644 --- a/cli/src/text_util.rs +++ b/cli/src/text_util.rs @@ -256,7 +256,8 @@ pub fn write_truncated_start( }; if data_width > max_width { - // The ellipsis itself may be larger than max_width, so maybe truncate it too. + // The ellipsis itself may be larger than max_width, so maybe truncate + // it too. let (start, ellipsis_width) = truncate_start_pos_bytes(ellipsis_data, max_width); let truncated_start = start + count_start_zero_width_chars_bytes(&ellipsis_data[start..]); truncated_width += ellipsis_width; @@ -300,7 +301,8 @@ pub fn write_truncated_end( replay_truncated(recorded_content, truncated_end)?; if data_width > max_width { - // The ellipsis itself may be larger than max_width, so maybe truncate it too. + // The ellipsis itself may be larger than max_width, so maybe truncate + // it too. let (truncated_end, ellipsis_width) = truncate_end_pos_bytes(ellipsis_data, max_width); truncated_width += ellipsis_width; replay_truncated(recorded_ellipsis, truncated_end)?; @@ -397,8 +399,8 @@ pub fn write_indented( recorded_content.replay_with(formatter, |formatter, range| { for line in data[range].split_inclusive(|&c| c == b'\n') { if new_line && line != b"\n" { - // Prefix inherits the current labels. This is implementation detail - // and may be fixed later. + // Prefix inherits the current labels. This is implementation + // detail and may be fixed later. write_prefix(formatter)?; } formatter.write_all(line)?; @@ -418,7 +420,8 @@ struct ByteFragment<'a> { impl<'a> ByteFragment<'a> { fn new(word: &'a [u8], whitespace_len: usize) -> Self { - // We don't care about the width of non-UTF-8 bytes, but should not panic. + // We don't care about the width of non-UTF-8 bytes, but should not + // panic. let word_width = textwrap::core::display_width(&String::from_utf8_lossy(word)); Self { word, @@ -521,8 +524,9 @@ pub fn write_wrapped( start..start + line.len() }) .peekable(); - // The recorded data ranges are contiguous, and the line ranges are increasing - // sequence (with some holes.) Both ranges should start from data[0]. + // The recorded data ranges are contiguous, and the line ranges are + // increasing sequence (with some holes.) Both ranges should start from + // data[0]. recorded_content.replay_with(formatter, |formatter, data_range| { while let Some(line_range) = line_ranges.peek() { let start = cmp::max(data_range.start, line_range.start); @@ -574,7 +578,8 @@ pub fn write_replaced( // Only continue if replacement begins in the boundaries of the current data range. .next_if(|(_, replacement_range)| replacement_range.start < data_range.end) { - // Write any data before the replacement, followed by the replacement content. + // Write any data before the replacement, followed by the + // replacement content. if position < replacement_range.start { formatter.write_all(&data[position..replacement_range.start])?; } diff --git a/cli/src/time_util.rs b/cli/src/time_util.rs index 0331f458262..88539e19c69 100644 --- a/cli/src/time_util.rs +++ b/cli/src/time_util.rs @@ -13,7 +13,8 @@ pub struct FormattingItems<'a> { impl<'a> FormattingItems<'a> { /// Parses strftime-like format string. pub fn parse(format: &'a str) -> Option { - // If the parsed format contained an error, format().to_string() would panic. + // If the parsed format contained an error, format().to_string() would + // panic. let items = StrftimeItems::new(format) .map(|item| match item { chrono::format::Item::Error => None, diff --git a/cli/src/ui.rs b/cli/src/ui.rs index 871799be343..43e98d4cb27 100644 --- a/cli/src/ui.rs +++ b/cli/src/ui.rs @@ -121,9 +121,10 @@ impl UiOutput { } => { drop(child_stdin); if let Err(err) = child.wait() { - // It's possible (though unlikely) that this write fails, but - // this function gets called so late that there's not much we - // can do about it. + // It's possible (though unlikely) that this write fails, + // but this function gets called so late + // that there's not much we can do about + // it. writeln!( ui.warning_default(), "Failed to wait on pager: {err}", @@ -396,7 +397,8 @@ impl Ui { PagerConfig::External(command_name_and_args) => { UiOutput::new_paged(command_name_and_args) .inspect_err(|err| { - // The pager executable couldn't be found or couldn't be run + // The pager executable couldn't be found or couldn't be + // run writeln!( self.warning_default(), "Failed to spawn pager '{name}': {err}", @@ -718,7 +720,8 @@ impl ProgressOutput { } pub fn term_width(&self) -> Option { - // Terminal can be resized while progress is displayed, so don't cache it. + // Terminal can be resized while progress is displayed, so don't cache + // it. self.term_width.or_else(term_width) } diff --git a/cli/testing/fake-bisector.rs b/cli/testing/fake-bisector.rs index 0e664360321..725d3003124 100644 --- a/cli/testing/fake-bisector.rs +++ b/cli/testing/fake-bisector.rs @@ -50,8 +50,9 @@ fn main() { let mut instructions = edit_script.split('\0').collect_vec(); if let Some(pos) = instructions.iter().position(|&i| i == "next invocation\n") { - // Overwrite the edit script. The next time `fake-bisector` is called, it will - // only see the part after the `next invocation` command. + // Overwrite the edit script. The next time `fake-bisector` is called, + // it will only see the part after the `next invocation` + // command. fs::write(&edit_script_path, instructions[pos + 1..].join("\0")).unwrap(); instructions.truncate(pos); } diff --git a/cli/testing/fake-editor.rs b/cli/testing/fake-editor.rs index e3386a9909e..23147ca6884 100644 --- a/cli/testing/fake-editor.rs +++ b/cli/testing/fake-editor.rs @@ -38,8 +38,8 @@ fn main() { let mut instructions = edit_script.split('\0').collect_vec(); if let Some(pos) = instructions.iter().position(|&i| i == "next invocation\n") { - // Overwrite the edit script. The next time `fake-editor` is called, it will - // only see the part after the `next invocation` command. + // Overwrite the edit script. The next time `fake-editor` is called, it + // will only see the part after the `next invocation` command. fs::write(&edit_script_path, instructions[pos + 1..].join("\0")).unwrap(); instructions.truncate(pos); } diff --git a/cli/tests/common/test_environment.rs b/cli/tests/common/test_environment.rs index 07771e481a9..fef1f04aa6e 100644 --- a/cli/tests/common/test_environment.rs +++ b/cli/tests/common/test_environment.rs @@ -72,8 +72,9 @@ impl Default for TestEnvironment { config_file_number: RefCell::new(0), command_number: RefCell::new(0), }; - // Use absolute timestamps in the operation log to make tests independent of the - // current time. Use non-colocated workspaces by default for simplicity. + // Use absolute timestamps in the operation log to make tests + // independent of the current time. Use non-colocated workspaces + // by default for simplicity. env.add_config( r#" [template-aliases] @@ -138,7 +139,8 @@ impl TestEnvironment { // https://doc.rust-lang.org/stable/std/env/fn.temp_dir.html cmd.env("TMPDIR", &self.tmp_dir); } else { - // Ensure that our tests don't write to the real %USERPROFILE% or %APPDATA%. + // Ensure that our tests don't write to the real %USERPROFILE% or + // %APPDATA%. cmd.env("USERPROFILE", &self.home_dir); cmd.env("APPDATA", self.home_dir.join(".config")); // On Windows, "/tmp" mounted in Git Bash appears to be leaked to @@ -214,8 +216,8 @@ impl TestEnvironment { if self.config_path.is_file() { panic!("add_config not supported when config_path is a file"); } - // Concatenating two valid TOML files does not (generally) result in a valid - // TOML file, so we create a new file every time instead. + // Concatenating two valid TOML files does not (generally) result in a + // valid TOML file, so we create a new file every time instead. let mut config_file_number = self.config_file_number.borrow_mut(); *config_file_number += 1; let config_file_number = *config_file_number; diff --git a/cli/tests/test_abandon_command.rs b/cli/tests/test_abandon_command.rs index 623d12987f1..87e8fb9fd1c 100644 --- a/cli/tests/test_abandon_command.rs +++ b/cli/tests/test_abandon_command.rs @@ -215,8 +215,8 @@ fn test_bug_2600() { let work_dir = test_env.work_dir("repo"); // We will not touch "nottherootcommit". See the - // `test_bug_2600_rootcommit_special_case` for the one case where base being the - // child of the root commit changes the expected behavior. + // `test_bug_2600_rootcommit_special_case` for the one case where base being + // the child of the root commit changes the expected behavior. create_commit(&work_dir, "nottherootcommit", &[]); create_commit(&work_dir, "base", &["nottherootcommit"]); create_commit(&work_dir, "a", &["base"]); @@ -250,8 +250,8 @@ fn test_bug_2600() { Added 0 files, modified 0 files, removed 1 files [EOF] "); - // Commits "a" and "b" should both have "nottherootcommit" as parent, and "b" - // should keep "a" as second parent. + // Commits "a" and "b" should both have "nottherootcommit" as parent, and + // "b" should keep "a" as second parent. insta::assert_snapshot!(get_log_output(&work_dir), @" @ [znk] c ○ [vru] b @@ -277,8 +277,8 @@ fn test_bug_2600() { [EOF] "); // Commit "b" should have "base" as parent. It should not have two parent - // pointers to that commit even though it was a merge commit before we abandoned - // "a". + // pointers to that commit even though it was a merge commit before we + // abandoned "a". insta::assert_snapshot!(get_log_output(&work_dir), @" @ [znk] c ○ [vru] b @@ -339,8 +339,8 @@ fn test_bug_2600() { Added 0 files, modified 0 files, removed 2 files [EOF] "); - // Commit "c" should have "base" as parent. As when we abandoned "a", it should - // not have two parent pointers to the same commit. + // Commit "c" should have "base" as parent. As when we abandoned "a", it + // should not have two parent pointers to the same commit. insta::assert_snapshot!(get_log_output(&work_dir), @" @ [znk] c ○ [zsu] a b base diff --git a/cli/tests/test_absorb_command.rs b/cli/tests/test_absorb_command.rs index 6db43e0cda5..36eac4abb4a 100644 --- a/cli/tests/test_absorb_command.rs +++ b/cli/tests/test_absorb_command.rs @@ -972,13 +972,14 @@ fn test_absorb_interactive() -> TestResult { // Working copy with changes to lines from both ancestors. work_dir.run_jj(["new"]).success(); work_dir.write_file("file1", "1X\n1b\n2Y\n2b\n"); - // Snapshot the changes so they are part of the source commit when we capture - // the op id (otherwise op restore would land on an empty @). + // Snapshot the changes so they are part of the source commit when we + // capture the op id (otherwise op restore would land on an empty @). work_dir.run_jj(["util", "snapshot"]).success(); let setup_opid = work_dir.current_operation_id(); // If we don't make any changes in the diff-editor, all selected changes are - // considered for absorption (and distributed by the usual annotation logic). + // considered for absorption (and distributed by the usual annotation + // logic). std::fs::write(&edit_script, "dump JJ-INSTRUCTIONS instrs")?; let output = work_dir.run_jj(["absorb", "-i"]); insta::assert_snapshot!(output, @" @@ -1009,7 +1010,8 @@ fn test_absorb_interactive() -> TestResult { // Can absorb only some changes in interactive mode (pick hunks that target // only the "1" commit). work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // The right side written here has only the change to the lines from commit 1. + // The right side written here has only the change to the lines from commit + // 1. std::fs::write(&edit_script, "write file1\n1X\n1b\n2a\n2b\n")?; let output = work_dir.run_jj(["absorb", "-i"]); insta::assert_snapshot!(output, @" diff --git a/cli/tests/test_advance_bookmarks.rs b/cli/tests/test_advance_bookmarks.rs index 0e7fabf80f8..ec3c02877a1 100644 --- a/cli/tests/test_advance_bookmarks.rs +++ b/cli/tests/test_advance_bookmarks.rs @@ -67,8 +67,8 @@ fn test_advance_bookmarks_enabled(make_commit: CommitFn) { test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); - // First, test with advance-bookmarks enabled. Start by creating a bookmark on - // the root commit. + // First, test with advance-bookmarks enabled. Start by creating a bookmark + // on the root commit. set_advance_bookmarks(&test_env, true); work_dir .run_jj(["bookmark", "create", "-r", "@-", "test_bookmark"]) @@ -94,7 +94,8 @@ fn test_advance_bookmarks_enabled(make_commit: CommitFn) { "); } - // Now disable advance bookmarks and commit again. The bookmark shouldn't move. + // Now disable advance bookmarks and commit again. The bookmark shouldn't + // move. set_advance_bookmarks(&test_env, false); make_commit(&work_dir, "second"); insta::allow_duplicates! { @@ -140,8 +141,8 @@ fn test_advance_bookmarks_at_minus(make_commit: CommitFn) { "); } - // Create a second bookmark pointing to @. On the next commit, only the first - // bookmark, which points to @-, will advance. + // Create a second bookmark pointing to @. On the next commit, only the + // first bookmark, which points to @-, will advance. work_dir .run_jj(["bookmark", "create", "test_bookmark2", "-r", "@"]) .success(); @@ -241,9 +242,9 @@ fn test_advance_bookmarks_overrides(make_commit: CommitFn) { "); } - // If we create a new bookmark at @- and move test_bookmark there as well. When - // we commit, only "second_bookmark" will advance since "test_bookmark" is - // disabled. + // If we create a new bookmark at @- and move test_bookmark there as well. + // When we commit, only "second_bookmark" will advance since + // "test_bookmark" is disabled. work_dir .run_jj(["bookmark", "create", "second_bookmark", "-r", "@-"]) .success(); @@ -328,7 +329,8 @@ fn test_new_advance_bookmarks_interior() { [EOF] "); - // Create a gap in the commits for us to insert our new commit with --before. + // Create a gap in the commits for us to insert our new commit with + // --before. work_dir.run_jj(["commit", "-m", "first"]).success(); work_dir.run_jj(["commit", "-m", "second"]).success(); work_dir.run_jj(["commit", "-m", "third"]).success(); @@ -372,7 +374,8 @@ fn test_new_advance_bookmarks_before() { [EOF] "); - // Create a gap in the commits for us to insert our new commit with --before. + // Create a gap in the commits for us to insert our new commit with + // --before. work_dir.run_jj(["commit", "-m", "first"]).success(); work_dir.run_jj(["commit", "-m", "second"]).success(); work_dir.run_jj(["commit", "-m", "third"]).success(); diff --git a/cli/tests/test_bookmark_command.rs b/cli/tests/test_bookmark_command.rs index 8543c3d69d3..02781ced5f9 100644 --- a/cli/tests/test_bookmark_command.rs +++ b/cli/tests/test_bookmark_command.rs @@ -1348,7 +1348,8 @@ fn test_bookmark_forget_export() { [EOF] "); // Forgetting a bookmark with --include-remotes deletes local and - // remote-tracking bookmarks including the corresponding git-tracking bookmark. + // remote-tracking bookmarks including the corresponding git-tracking + // bookmark. insta::assert_snapshot!(get_bookmark_output(&work_dir), @""); let output = work_dir.run_jj(["log", "-r=foo", "--no-graph"]); insta::assert_snapshot!(output, @" @@ -1359,9 +1360,9 @@ fn test_bookmark_forget_export() { "); // `jj git export` will delete the bookmark from git. In a colocated - // workspace, this will happen automatically immediately after a `jj bookmark - // forget`. This is demonstrated in `test_git_colocated_bookmark_forget` in - // test_git_colocated.rs + // workspace, this will happen automatically immediately after a `jj + // bookmark forget`. This is demonstrated in + // `test_git_colocated_bookmark_forget` in test_git_colocated.rs let output = work_dir.run_jj(["git", "export"]); insta::assert_snapshot!(output, @""); insta::assert_snapshot!(get_bookmark_output(&work_dir), @""); @@ -1369,8 +1370,8 @@ fn test_bookmark_forget_export() { #[test] fn test_bookmark_forget_fetched_bookmark() { - // Much of this test is borrowed from `test_git_fetch_remote_only_bookmark` in - // test_git_fetch.rs + // Much of this test is borrowed from `test_git_fetch_remote_only_bookmark` + // in test_git_fetch.rs // Set up a git repo with a bookmark and a jj repo that has it as a remote. let test_env = TestEnvironment::default(); @@ -1413,12 +1414,12 @@ fn test_bookmark_forget_fetched_bookmark() { insta::assert_snapshot!(get_bookmark_output(&work_dir), @""); // At this point `jj git export && jj git import` does *not* recreate the - // bookmark. This behavior is important in colocated workspaces, as otherwise a - // forgotten bookmark would be immediately resurrected. + // bookmark. This behavior is important in colocated workspaces, as + // otherwise a forgotten bookmark would be immediately resurrected. // // Technically, this is because `jj bookmark forget` preserved - // the ref in jj view's `git_refs` tracking the local git repo's remote-tracking - // bookmark. + // the ref in jj view's `git_refs` tracking the local git repo's + // remote-tracking bookmark. // TODO: Show that jj git push is also a no-op let output = work_dir.run_jj(["git", "export"]); insta::assert_snapshot!(output, @""); @@ -1515,8 +1516,8 @@ fn test_bookmark_forget_fetched_bookmark() { #[test] fn test_bookmark_forget_deleted_or_nonexistent_bookmark() { - // Much of this test is borrowed from `test_git_fetch_remote_only_bookmark` in - // test_git_fetch.rs + // Much of this test is borrowed from `test_git_fetch_remote_only_bookmark` + // in test_git_fetch.rs // ======== Beginning of test setup ======== // Set up a git repo with a bookmark and a jj repo that has it as a remote. @@ -1722,8 +1723,8 @@ fn test_bookmark_track_untrack() -> TestResult { [EOF] "); - // Untrack existing and locally-deleted bookmarks. Bookmark targets should be - // unchanged + // Untrack existing and locally-deleted bookmarks. Bookmark targets should + // be unchanged work_dir .run_jj(["bookmark", "delete", "feature2"]) .success(); @@ -2593,8 +2594,8 @@ fn test_bookmark_list_filtered() -> TestResult { let query = |args: &[&str]| local_dir.run_jj_with(|cmd| cmd.args(["bookmark", "list"]).args(args)); - // "all()" doesn't include deleted bookmarks since they have no local targets. - // So "all()" is identical to "bookmarks()". + // "all()" doesn't include deleted bookmarks since they have no local + // targets. So "all()" is identical to "bookmarks()". insta::assert_snapshot!(query(&["-rall()"]), @" local-keep: kpqxywon 4b2bc95c (empty) local-keep remote-keep: rlvkpnrz c2f2ee40 (empty) remote-keep diff --git a/cli/tests/test_commit_command.rs b/cli/tests/test_commit_command.rs index dd6a230becd..fefb9fb7ba1 100644 --- a/cli/tests/test_commit_command.rs +++ b/cli/tests/test_commit_command.rs @@ -43,8 +43,8 @@ fn test_commit_with_editor() -> TestResult { test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); - // Check that the text file gets initialized with the current description and - // set a new one + // Check that the text file gets initialized with the current description + // and set a new one work_dir.run_jj(["describe", "-m=initial"]).success(); std::fs::write(&edit_script, ["dump editor0", "write\nmodified"].join("\0"))?; work_dir.run_jj(["commit"]).success(); @@ -608,7 +608,8 @@ fn test_commit_with_editor_without_message() -> TestResult { work_dir.write_file("file1", "foo\n"); - // --editor without -m should behave the same as without --editor (normal flow) + // --editor without -m should behave the same as without --editor (normal + // flow) std::fs::write(&edit_script, "dump editor")?; let output = work_dir.run_jj(["commit", "--editor"]).success(); diff --git a/cli/tests/test_completion.rs b/cli/tests/test_completion.rs index 825de11104c..ca2c2917b8f 100644 --- a/cli/tests/test_completion.rs +++ b/cli/tests/test_completion.rs @@ -1219,8 +1219,8 @@ fn test_revisions() { // Begin testing `jj git push --named` - // The name of a bookmark does not get completed, since we want to create a new - // bookmark + // The name of a bookmark does not get completed, since we want to create a + // new bookmark let output = work_dir.complete_fish(["git", "push", "--named", ""]); insta::assert_snapshot!(output, @""); let output = work_dir.complete_fish(["git", "push", "--named", "a"]); @@ -1470,8 +1470,8 @@ fn test_config_unset() { .run_jj(["config", "set", "--repo", "ui.diff-formatter", ":git"]) .success(); - // Only config options set in TestEnvironment are suggested initially + other - // viable flags + // Only config options set in TestEnvironment are suggested initially + + // other viable flags let output = test_env.complete_fish(["config", "unset", ""]); insta::assert_snapshot!(output.take_stdout_n_lines(5), @r#" template-aliases."format_time_range(time_range)" user: 'time_range.start() ++ " - " ++ time_range.end()' @@ -1536,7 +1536,8 @@ fn test_config_unset() { [EOF] "#); - // If no config source is specified yet, options from all sources are completed + // If no config source is specified yet, options from all sources are + // completed let output = repo_dir.complete_fish(["config", "unset", "ui"]); insta::assert_snapshot!(output, @r#" ui.editor user: "nvim" @@ -1546,7 +1547,8 @@ fn test_config_unset() { [EOF] "#); - // If a config source has already been specified, only its options as completed + // If a config source has already been specified, only its options as + // completed let output = repo_dir.complete_fish(["config", "unset", "--user", "ui"]); insta::assert_snapshot!(output, @r#" ui.editor user: "nvim" @@ -1576,8 +1578,8 @@ fn test_config_unset() { [EOF] "#); - // If a config source has already been specified, the value according to that - // source is listed + // If a config source has already been specified, the value according to + // that source is listed let output = repo_dir.complete_fish(["config", "unset", "--user", "ui.editor"]); insta::assert_snapshot!(output, @r#" ui.editor user: "nvim" @@ -2029,9 +2031,10 @@ fn test_files() { // Given that the path prefix uses the main separator (e.g. `\` on Windows), // check that the completion continues to use the same separator. - // The assertion maps the main separator to some arbitrary fictitious separator - // (`→`) which is not used by real OSes (yet) to check that the main separator - // is preserved on platforms where it differs from `/`. + // The assertion maps the main separator to some arbitrary fictitious + // separator (`→`) which is not used by real OSes (yet) to check that + // the main separator is preserved on platforms where it differs from + // `/`. let output = work_dir.complete_fish([ "diff", "-r", diff --git a/cli/tests/test_concurrent_operations.rs b/cli/tests/test_concurrent_operations.rs index 0ed86cb32a3..66b1515fa32 100644 --- a/cli/tests/test_concurrent_operations.rs +++ b/cli/tests/test_concurrent_operations.rs @@ -337,8 +337,8 @@ fn test_git_head_race_condition() -> TestResult { } // Verify the operation description for importing Git HEAD hasn't changed - // First ensure we're not already on the initial commit (prev/next loop may have - // ended there) + // First ensure we're not already on the initial commit (prev/next loop may + // have ended there) work_dir.run_jj(["new"]).success(); // Use git to checkout the initial commit, then trigger import std::process::Command::new("git") diff --git a/cli/tests/test_config_command.rs b/cli/tests/test_config_command.rs index bebd66a029c..a0d891b9777 100644 --- a/cli/tests/test_config_command.rs +++ b/cli/tests/test_config_command.rs @@ -1348,10 +1348,12 @@ fn test_config_get_yields_values_consistent_with_schema_defaults() -> TestResult let output = test_env.run_jj_in(".", ["config", "get", key]).success(); let output_doc = toml_edit::Document::parse(format!("test={}", output.stdout.normalized())) .unwrap_or_else(|_| { - // Unfortunately for this test, `config get` is "lossy" and does not print - // quoted strings. This means that e.g. `false` and `"false"` are not - // distinguishable. If value couldn't be parsed, it's probably a string, so - // let's parse its Debug string instead. + // Unfortunately for this test, `config get` is "lossy" and does + // not print quoted strings. This means that + // e.g. `false` and `"false"` are not + // distinguishable. If value couldn't be parsed, it's probably a + // string, so let's parse its Debug string + // instead. toml_edit::Document::parse(format!("test={:?}", output.stdout.normalized().trim())) .unwrap() }); diff --git a/cli/tests/test_converge_command.rs b/cli/tests/test_converge_command.rs index 3e2268fefa4..ba7f8f055ca 100644 --- a/cli/tests/test_converge_command.rs +++ b/cli/tests/test_converge_command.rs @@ -91,8 +91,8 @@ fn test_converge_simple() { [EOF] "); - // Run `jj converge` command and check the output. In this case no user input is - // needed. + // Run `jj converge` command and check the output. In this case no user + // input is needed. let output = work_dir.run_jj(["converge"]).success(); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -164,8 +164,8 @@ fn test_converge_two_divergent_changes_in_non_interactive_mode() { .success(); create_commit_with_files(&work_dir, "g", &["e1"], &[("file7", "7")]); - // Test the setup: look at the commit graph (commit B is duplicated and commit E - // is duplicated) + // Test the setup: look at the commit graph (commit B is duplicated and + // commit E is duplicated) insta::assert_snapshot!(get_long_log_output(&work_dir), @r" @ g xznxytkn 46658cae - description: g ○ e1 kmkuslsw/1 15962bae - description: e2 @@ -203,9 +203,9 @@ fn test_converge_two_divergent_changes_in_non_interactive_mode() { [exit status: 1] "); - // Note: in the test environment jj commands run in non-interactive (quiet) mode - // by default, so the following also fails but for a different reason: it - // cannot prompt the user + // Note: in the test environment jj commands run in non-interactive (quiet) + // mode by default, so the following also fails but for a different + // reason: it cannot prompt the user let output = work_dir.run_jj(["converge"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -280,8 +280,8 @@ fn test_converge_two_divergent_changes() { .success(); create_commit_with_files(&work_dir, "g", &["e1"], &[("file7", "7")]); - // Test the setup: look at the commit graph (commit B is duplicated and commit E - // is duplicated) + // Test the setup: look at the commit graph (commit B is duplicated and + // commit E is duplicated) insta::assert_snapshot!(get_long_log_output(&work_dir), @r" @ g xznxytkn 46658cae - description: g ○ e1 kmkuslsw/1 15962bae - description: e2 @@ -341,10 +341,10 @@ fn test_converge_two_divergent_changes() { [EOF] "); - // Run the command again, this time the user chooses the first divergent change. - // This invocation succeeds to automatically converge that change. A hint is - // printed to inform the user that there is still one divergent change - // remaining. + // Run the command again, this time the user chooses the first divergent + // change. This invocation succeeds to automatically converge that + // change. A hint is printed to inform the user that there is still one + // divergent change remaining. let output = work_dir .run_jj_with(|cmd| force_interactive(cmd).args(["converge"]).write_stdin("1\n")) .success(); @@ -502,8 +502,8 @@ fn test_converge_simple_with_revisions_arg() { [EOF] "); - // `-r a::` resolves to {a, b1, b2, c, d}. Now the command "sees" two commits - // with the same change-id and converges them. + // `-r a::` resolves to {a, b1, b2, c, d}. Now the command "sees" two + // commits with the same change-id and converges them. let output = work_dir.run_jj(["converge", "-r", "a::"]).success(); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -583,8 +583,8 @@ fn test_converge_simple_with_revisions_arg_and_two_divergent_changes() { .success(); create_commit_with_files(&work_dir, "g", &["e2"], &[("file7", "7")]); - // Test the setup: look at the commit graph (commit B is duplicated and commit E - // is duplicated) + // Test the setup: look at the commit graph (commit B is duplicated and + // commit E is duplicated) insta::assert_snapshot!(get_long_log_output(&work_dir), @r" @ g nmzmmopx 7e4fac7e - description: g ○ e2 kmkuslsw/0 c8976369 - description: blah blah blah @@ -630,8 +630,8 @@ fn test_converge_simple_with_revisions_arg_and_two_divergent_changes() { [EOF] "); - // `-r a::` does resolve to both divergent changes. In this test we simulate the - // user aborts at the prompt. + // `-r a::` does resolve to both divergent changes. In this test we simulate + // the user aborts at the prompt. let output = work_dir .run_jj_with(|cmd| { force_interactive(cmd) @@ -661,9 +661,9 @@ fn test_converge_simple_with_revisions_arg_and_two_divergent_changes() { [EOF] "); - // `-r b1|e3` resolve to those two commits. Both ARE divergent commits, but in - // the search space there are no other commits with either change-id so the - // command does nothing. + // `-r b1|e3` resolve to those two commits. Both ARE divergent commits, but + // in the search space there are no other commits with either change-id + // so the command does nothing. let output = work_dir .run_jj_with(|cmd| { force_interactive(cmd) @@ -677,8 +677,8 @@ fn test_converge_simple_with_revisions_arg_and_two_divergent_changes() { [EOF] "); - // Specifying `-r b1|b2` resolves to that divergent change and only that one. - // There should not be any prompt. + // Specifying `-r b1|b2` resolves to that divergent change and only that + // one. There should not be any prompt. let output = work_dir .run_jj_with(|cmd| { force_interactive(cmd) @@ -1029,7 +1029,8 @@ fn test_converge_description_changed_inconsistently(invoke_text_editor: bool) -> [EOF] "); - // Verify the description after converge (it should have conflict markers) + // Verify the description after converge (it should have conflict + // markers) let output = work_dir.run_jj(["log", "-T", "description", "-r", "b1", "--no-graph"]); insta::assert_snapshot!(output, @r#" <<<<<<< conflict 1 of 1 @@ -1094,8 +1095,8 @@ fn test_converge_with_inconsistent_parents() { [EOF] "); - // First check behavior in non-interactive mode. The command cannot determine - // which parents to use, so it should fail. + // First check behavior in non-interactive mode. The command cannot + // determine which parents to use, so it should fail. let output = work_dir.run_jj_with(|cmd| force_interactive(cmd).args(["converge", "--no-interactive"])); insta::assert_snapshot!(output, @r" @@ -1213,10 +1214,11 @@ fn test_converge_one_divergent_commit_is_a_descendant_of_another_divergent_commi // Start by setting description to "message 1", then simulate two concurrent // operations, one changing the description to "message 2" and the other - // changing it to "message 3" (--at-op=@- is what allows us to pretend these two - // operations happen concurrently). At this point we have two divergent commits. - // Then we set up bookmarks b2 and b3 to point to the commits. Finally we rebase - // b2 onto b3. This sets the stage for this test's scenario. + // changing it to "message 3" (--at-op=@- is what allows us to pretend these + // two operations happen concurrently). At this point we have two + // divergent commits. Then we set up bookmarks b2 and b3 to point to the + // commits. Finally we rebase b2 onto b3. This sets the stage for this + // test's scenario. work_dir.run_jj(["describe", "-m", "message 1"]).success(); work_dir.run_jj(["describe", "-m", "message 2"]).success(); work_dir @@ -1265,8 +1267,8 @@ fn test_converge_one_divergent_commit_is_a_descendant_of_another_divergent_commi [EOF] "); - // Test the setup: look at the commit graph (commit B is duplicated and commit E - // is duplicated) + // Test the setup: look at the commit graph (commit B is duplicated and + // commit E is duplicated) insta::assert_snapshot!(get_long_log_output(&work_dir), @r" @ b2 qpvuntsm/0 cca75b59 - description: message 2 ○ b3 qpvuntsm/1 4734557e - description: message 3 @@ -1291,9 +1293,10 @@ fn test_converge_one_divergent_commit_is_a_descendant_of_another_divergent_commi [EOF] "); - // Run `jj converge` command and check the output. In this case the user must - // merge the descriptions in a text editor. However, the parents are chosen - // automatically (b2 is ignored because it is a descendant of b3). + // Run `jj converge` command and check the output. In this case the user + // must merge the descriptions in a text editor. However, the parents + // are chosen automatically (b2 is ignored because it is a descendant of + // b3). std::fs::write( &edit_script, ["dump editor0", "write\nmy-merged-description"].join("\0"), @@ -1390,12 +1393,12 @@ fn test_converge_two_divergent_commits_with_unrelated_commit_in_between() -> Tes // Start by setting description to "message 1", then simulate two concurrent // operations, one changing the description to "message 2" and the other - // changing it to "message 3" (--at-op=@- is what allows us to pretend these two - // operations happen concurrently). At this point we have two divergent commits. - // Then we set up bookmarks b2 and b3 to point to the commits. After that we - // create foo as a child of b3, then we rebase b2 onto foo. This sets the - // stage for this test's scenario. We create two other commits (bar and baz) - // to observe how descendants are rebased. + // changing it to "message 3" (--at-op=@- is what allows us to pretend these + // two operations happen concurrently). At this point we have two + // divergent commits. Then we set up bookmarks b2 and b3 to point to the + // commits. After that we create foo as a child of b3, then we rebase b2 + // onto foo. This sets the stage for this test's scenario. We create two + // other commits (bar and baz) to observe how descendants are rebased. work_dir.run_jj(["describe", "-m", "message 1"]).success(); work_dir.run_jj(["describe", "-m", "message 2"]).success(); work_dir @@ -1453,8 +1456,8 @@ fn test_converge_two_divergent_commits_with_unrelated_commit_in_between() -> Tes [EOF] "); - // Test the setup: look at the commit graph (commit B is duplicated and commit E - // is duplicated) + // Test the setup: look at the commit graph (commit B is duplicated and + // commit E is duplicated) insta::assert_snapshot!(get_long_log_output(&work_dir), @r" @ znkkpsqq aac9c864 - description: baz │ ○ yostqsxw 38a29791 - description: bar @@ -1483,9 +1486,10 @@ fn test_converge_two_divergent_commits_with_unrelated_commit_in_between() -> Tes [EOF] "); - // Run `jj converge` command and check the output. In this case the user must - // merge the descriptions in a text editor. However, the parents are chosen - // automatically (b2 is ignored because it is a descendant of b3). + // Run `jj converge` command and check the output. In this case the user + // must merge the descriptions in a text editor. However, the parents + // are chosen automatically (b2 is ignored because it is a descendant of + // b3). std::fs::write( &edit_script, ["dump editor0", "write\nmy-merged-description"].join("\0"), @@ -1554,7 +1558,8 @@ fn test_converge_two_divergent_commits_with_unrelated_commit_in_between() -> Tes "); // Verify the commit graph after converge; notice the commit that was - // "sandwiched" between b2 and b3 (foo) is now a child of the solution commit. + // "sandwiched" between b2 and b3 (foo) is now a child of the solution + // commit. insta::assert_snapshot!(get_long_log_output(&work_dir), @r" @ znkkpsqq 3ea044e0 - description: baz │ ○ yostqsxw a4dd040e - description: bar diff --git a/cli/tests/test_debug_command.rs b/cli/tests/test_debug_command.rs index 37bc1b180b5..5d8fd1e97a3 100644 --- a/cli/tests/test_debug_command.rs +++ b/cli/tests/test_debug_command.rs @@ -344,7 +344,8 @@ fn test_debug_tree() { "# ); - // Can filter by paths when showing non-root tree (matcher applies from root) + // Can filter by paths when showing non-root tree (matcher applies from + // root) let output = work_dir.run_jj([ "debug", "tree", diff --git a/cli/tests/test_describe_command.rs b/cli/tests/test_describe_command.rs index 359a4375fce..cf974081db1 100644 --- a/cli/tests/test_describe_command.rs +++ b/cli/tests/test_describe_command.rs @@ -46,8 +46,8 @@ fn test_describe() -> TestResult { [EOF] "); - // Check that the text file gets initialized with the current description and - // make no changes + // Check that the text file gets initialized with the current description + // and make no changes std::fs::write(&edit_script, "dump editor0")?; let output = work_dir.run_jj(["describe"]); insta::assert_snapshot!(output, @" diff --git a/cli/tests/test_diff_command.rs b/cli/tests/test_diff_command.rs index 95e55cb732b..a1bda872c42 100644 --- a/cli/tests/test_diff_command.rs +++ b/cli/tests/test_diff_command.rs @@ -3174,7 +3174,8 @@ fn test_diff_external_tool() -> TestResult { "); }); - // nonzero exit codes should not print a warning if it's an expected exit code + // nonzero exit codes should not print a warning if it's an expected exit + // code std::fs::write(&edit_script, "fail")?; let output = work_dir.run_jj([ "diff", @@ -3980,8 +3981,8 @@ fn test_diff_stat_binary_and_text() { [EOF] "); - // If the binary file size changed, the right side must be wide enough for that - // text. + // If the binary file size changed, the right side must be wide enough for + // that text. work_dir.write_file("binary_with_elided_long_file_name.png", b"\x0033"); let output = work_dir.run_jj(["diff", "--stat"]); // Rightmost display column ->| @@ -4097,9 +4098,9 @@ fn test_diff_rename_in_merge_commit() { let work_dir = test_env.work_dir("repo"); // A rename in a merge commit is detected once per parent. When the renamed - // source is present in more than one parent, the same copy record is reported - // for each, and those duplicates must not cancel each other out and drop the - // rename. https://github.com/jj-vcs/jj/issues/9752 + // source is present in more than one parent, the same copy record is + // reported for each, and those duplicates must not cancel each other + // out and drop the rename. https://github.com/jj-vcs/jj/issues/9752 work_dir.write_file("a.txt", "aaa\n"); work_dir.run_jj(["describe", "-m", "base"]).success(); work_dir.run_jj(["new", "-m", "first branch"]).success(); diff --git a/cli/tests/test_diffedit_command.rs b/cli/tests/test_diffedit_command.rs index 675c66ef6cf..d505a57e571 100644 --- a/cli/tests/test_diffedit_command.rs +++ b/cli/tests/test_diffedit_command.rs @@ -464,8 +464,9 @@ fn test_diffedit_external_tool_conflict_marker_style() -> TestResult { // Set up diff editor to use "snapshot" conflict markers test_env.add_config(r#"merge-tools.fake-diff-editor.conflict-marker-style = "snapshot""#); - // We want to see whether the diff editor is using the correct conflict markers, - // and reset it to make sure that it parses the conflict markers as well + // We want to see whether the diff editor is using the correct conflict + // markers, and reset it to make sure that it parses the conflict + // markers as well std::fs::write( &edit_script, [ @@ -588,8 +589,8 @@ fn test_diffedit_3pane() -> TestResult { work_dir.run_jj(["debug", "snapshot"]).success(); let setup_opid = work_dir.current_operation_id(); - // 2 configs for a 3-pane setup. In the first, "$right" is passed to what the - // fake diff editor considers the "after" state. + // 2 configs for a 3-pane setup. In the first, "$right" is passed to what + // the fake diff editor considers the "after" state. let config_with_right_as_after = "merge-tools.fake-diff-editor.edit-args=['$left', '$right', '--ignore=$output']"; let config_with_output_as_after = @@ -613,7 +614,8 @@ fn test_diffedit_3pane() -> TestResult { M file2 [EOF] "); - // Nothing happens if we make no changes, `config_with_right_as_after` version + // Nothing happens if we make no changes, `config_with_right_as_after` + // version let output = work_dir.run_jj(["diffedit", "--config", config_with_right_as_after]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -714,7 +716,8 @@ fn test_diffedit_merge() -> TestResult { [EOF] "); - // Remove file1. The conflict remains in the working copy on top of the merge. + // Remove file1. The conflict remains in the working copy on top of the + // merge. std::fs::write( edit_script, "files-before file1\0files-after JJ-INSTRUCTIONS file1 file3\0rm file1", @@ -895,10 +898,10 @@ fn test_diffedit_restore_descendants() -> TestResult { #[test] fn test_diffedit_external_tool_eol_conversion() -> TestResult { - // Create 2 changes: one creates a file with a single LF, another changes the - // file to contain 2 LFs. The diff editor should see the same EOL in both the - // before file and the after file. And when the diff editor adds another EOL to - // update, we should always see 3 LFs in the store. + // Create 2 changes: one creates a file with a single LF, another changes + // the file to contain 2 LFs. The diff editor should see the same EOL in + // both the before file and the after file. And when the diff editor + // adds another EOL to update, we should always see 3 LFs in the store. let mut test_env = TestEnvironment::default(); let edit_script = test_env.set_up_fake_diff_editor(); @@ -965,8 +968,8 @@ fn test_diffedit_external_tool_eol_conversion() -> TestResult { let eol = first_eol; // With the previous diffedit command, file now contains the same content as - // commit 1, i.e., 1 LF. We create another commit 3 with the 2-LF file, so that - // the file shows up in the next diffedit command. + // commit 1, i.e., 1 LF. We create another commit 3 with the 2-LF file, so + // that the file shows up in the next diffedit command. work_dir.write_file(file_path, "\n\n"); work_dir .run_jj(["squash", "--config", eol_conversion_none_config, "-m", "2"]) diff --git a/cli/tests/test_duplicate_command.rs b/cli/tests/test_duplicate_command.rs index 5c86785260d..37bb93287e1 100644 --- a/cli/tests/test_duplicate_command.rs +++ b/cli/tests/test_duplicate_command.rs @@ -511,7 +511,8 @@ fn test_duplicate_insert_after() { [EOF] "); - // Duplicate a single commit after a single commit with no direct relationship. + // Duplicate a single commit after a single commit with no direct + // relationship. let output = work_dir.run_jj(["duplicate", "a1", "--after", "b1"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1141,7 +1142,8 @@ fn test_duplicate_insert_before() { [EOF] "); - // Duplicate a single commit before a single commit with no direct relationship. + // Duplicate a single commit before a single commit with no direct + // relationship. let output = work_dir.run_jj(["duplicate", "a1", "--before", "b2"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1320,8 +1322,8 @@ fn test_duplicate_insert_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Duplicate multiple commits without a direct ancestry relationship before a - // single commit without a direct relationship. + // Duplicate multiple commits without a direct ancestry relationship before + // a single commit without a direct relationship. let output = work_dir.run_jj(["duplicate", "a1", "b1", "--before", "c1"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1353,8 +1355,9 @@ fn test_duplicate_insert_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Duplicate multiple commits without a direct ancestry relationship before a - // single commit which is an ancestor of one of the duplicated commits. + // Duplicate multiple commits without a direct ancestry relationship before + // a single commit which is an ancestor of one of the duplicated + // commits. let output = work_dir.run_jj(["duplicate", "a3", "b1", "--before", "a2"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1387,8 +1390,9 @@ fn test_duplicate_insert_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Duplicate multiple commits without a direct ancestry relationship before a - // single commit which is a descendant of one of the duplicated commits. + // Duplicate multiple commits without a direct ancestry relationship before + // a single commit which is a descendant of one of the duplicated + // commits. let output = work_dir.run_jj(["duplicate", "a1", "b1", "--before", "a3"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1835,8 +1839,8 @@ fn test_duplicate_insert_after_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Duplicate a single commit in between an ancestor commit and a commit with no - // direct relationship. + // Duplicate a single commit in between an ancestor commit and a commit with + // no direct relationship. let output = work_dir.run_jj(["duplicate", "a3", "--before", "a2", "--after", "b2"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1895,8 +1899,8 @@ fn test_duplicate_insert_after_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Duplicate a single commit in between a descendant commit and a commit with no - // direct relationship. + // Duplicate a single commit in between a descendant commit and a commit + // with no direct relationship. let output = work_dir.run_jj(["duplicate", "a1", "--after", "a3", "--before", "b2"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1997,9 +2001,9 @@ fn test_duplicate_insert_after_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Duplicate multiple commits without a direct ancestry relationship between a - // commit which is an ancestor of one of the duplicated commits and a commit - // with no direct relationship. + // Duplicate multiple commits without a direct ancestry relationship between + // a commit which is an ancestor of one of the duplicated commits and a + // commit with no direct relationship. let output = work_dir.run_jj(["duplicate", "a3", "b1", "--after", "a2", "--before", "c2"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2032,8 +2036,8 @@ fn test_duplicate_insert_after_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Duplicate multiple commits without a direct ancestry relationship between a - // commit which is a descendant of one of the duplicated commits and a + // Duplicate multiple commits without a direct ancestry relationship between + // a commit which is a descendant of one of the duplicated commits and a // commit with no direct relationship. let output = work_dir.run_jj(["duplicate", "a1", "b1", "--after", "a3", "--before", "c2"]); insta::assert_snapshot!(output, @r" @@ -2211,8 +2215,8 @@ fn test_duplicate_insert_after_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Duplicate multiple commits with an ancestry relationship between descendant - // commits. + // Duplicate multiple commits with an ancestry relationship between + // descendant commits. let output = work_dir.run_jj(["duplicate", "a3", "a4", "--after", "a1", "--before", "a2"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2277,8 +2281,8 @@ fn test_duplicate_insert_after_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Duplicate multiple commits with an ancestry relationship between an ancestor - // commit and a descendant commit. + // Duplicate multiple commits with an ancestry relationship between an + // ancestor commit and a descendant commit. let output = work_dir.run_jj(["duplicate", "a2", "a3", "--after", "a1", "--before", "a4"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2411,8 +2415,8 @@ fn test_rebase_duplicates() { Added 0 files, modified 0 files, removed 1 files [EOF] "); - // Some of the duplicate commits' timestamps were changed a little to make them - // have distinct commit ids. + // Some of the duplicate commits' timestamps were changed a little to make + // them have distinct commit ids. insta::assert_snapshot!(get_log_output_with_ts(&work_dir), @" @ fa60711d6bd1 c @ 2001-02-03 04:05:18.000 +07:00 │ ○ e320e3d23be0 c @ 2001-02-03 04:05:18.000 +07:00 diff --git a/cli/tests/test_file_chmod_command.rs b/cli/tests/test_file_chmod_command.rs index 34ec5260900..9c03bbdacbb 100644 --- a/cli/tests/test_file_chmod_command.rs +++ b/cli/tests/test_file_chmod_command.rs @@ -309,8 +309,8 @@ fn test_chmod_exec_bit_settings() -> TestResult { let work_dir = test_env.work_dir("repo"); let path = &work_dir.root().join("file"); - // The timestamps in the `jj debug local-working-copy` output change, so we want - // to remove them before asserting the snapshot + // The timestamps in the `jj debug local-working-copy` output change, so we + // want to remove them before asserting the snapshot let timestamp_regex = Regex::new(r"\b\d{10,}\b")?; let redact_timestamp = |output: String| { let output = timestamp_regex.replace_all(&output, ""); diff --git a/cli/tests/test_file_track_untrack_commands.rs b/cli/tests/test_file_track_untrack_commands.rs index 9f8c188626b..7673015cceb 100644 --- a/cli/tests/test_file_track_untrack_commands.rs +++ b/cli/tests/test_file_track_untrack_commands.rs @@ -27,8 +27,8 @@ fn test_track_untrack() { target_dir.write_file("file2", "initial"); target_dir.write_file("file3", "initial"); - // Run a command so all the files get tracked, then add "*.bak" to the ignore - // patterns + // Run a command so all the files get tracked, then add "*.bak" to the + // ignore patterns work_dir.run_jj(["st"]).success(); work_dir.write_file(".gitignore", "*.bak\n"); let files_before = work_dir.run_jj(["file", "list"]).success(); @@ -137,8 +137,8 @@ fn test_track_untrack_sparse() { file1 [EOF] "); - // Trying to manually track a file that's not included in the sparse working has - // no effect. TODO: At least a warning would be useful + // Trying to manually track a file that's not included in the sparse working + // has no effect. TODO: At least a warning would be useful let output = work_dir.run_jj(["file", "track", "file2"]); insta::assert_snapshot!(output, @""); let output = work_dir.run_jj(["file", "list"]); @@ -185,7 +185,8 @@ fn test_auto_track() { [EOF] "); - // CWD-relative paths in `snapshot.auto-track` are evaluated from the repo root + // CWD-relative paths in `snapshot.auto-track` are evaluated from the repo + // root let sub_dir = work_dir.create_dir("sub"); sub_dir.write_file("file1.rs", "initial"); let output = sub_dir.run_jj(["file", "list"]); diff --git a/cli/tests/test_fix_command.rs b/cli/tests/test_fix_command.rs index 15ce32e66ac..6a1c68cd41b 100644 --- a/cli/tests/test_fix_command.rs +++ b/cli/tests/test_fix_command.rs @@ -524,8 +524,8 @@ fn test_relative_paths() { [EOF] "); - // The current directory does not change the interpretation of the config, so - // foo2 is fixed but not dir/foo3. + // The current directory does not change the interpretation of the config, + // so foo2 is fixed but not dir/foo3. sub_dir.run_jj(["fix"]).success(); let output = work_dir.run_jj(["file", "show", "foo1", "-r", "@"]); insta::assert_snapshot!(output, @"Fixed![EOF]"); @@ -817,9 +817,9 @@ fn test_default_revset() { .success(); work_dir.run_jj(["edit", "bar2"]).success(); - // With no args and no revset configuration, we fix `reachable(@, mutable())`, - // which includes bar{1,2,3} and excludes trunk{1,2} (which is immutable) and - // foo (which is mutable but not reachable). + // With no args and no revset configuration, we fix `reachable(@, + // mutable())`, which includes bar{1,2,3} and excludes trunk{1,2} (which + // is immutable) and foo (which is mutable but not reachable). test_env.add_config(r#"revset-aliases."immutable_heads()" = "trunk2""#); let output = work_dir.run_jj(["fix"]); insta::assert_snapshot!(output, @" @@ -936,14 +936,14 @@ fn test_fix_empty_file() { #[test] fn test_fix_large_file() { let mut test_env = TestEnvironment::default(); - // Set to byte mode, so that fake-formatter doesn't read from the stdin all at - // once. + // Set to byte mode, so that fake-formatter doesn't read from the stdin all + // at once. set_up_fake_formatter(&mut test_env, &["--lowercase", "--byte-mode"]); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); - // 512KB should be larger than most default page size, so that the stdin pipe - // will be blocked if fake-formatter doesn't read, and the stdout pipe will - // be blocked if jj doesn't read. + // 512KB should be larger than most default page size, so that the stdin + // pipe will be blocked if fake-formatter doesn't read, and the stdout + // pipe will be blocked if jj doesn't read. let mut large_contents = b"A".repeat(0x800_000); large_contents.push(b'\n'); work_dir.write_file("file", &large_contents); @@ -1037,15 +1037,16 @@ fn test_fix_cyclic() { #[test] fn test_deduplication() { - // Append all fixed content to a log file. Note that fix tools are always run - // from the workspace root, so this will always write to $root/$path-fixlog. + // Append all fixed content to a log file. Note that fix tools are always + // run from the workspace root, so this will always write to + // $root/$path-fixlog. let mut test_env = TestEnvironment::default(); set_up_fake_formatter(&mut test_env, &["--uppercase", "--tee", "$path-fixlog"]); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); - // There are at least two interesting cases: the content is repeated immediately - // in the child commit, or later in another descendant. + // There are at least two interesting cases: the content is repeated + // immediately in the child commit, or later in another descendant. work_dir.write_file("file", "foo\n"); work_dir .run_jj(["bookmark", "create", "-r@", "a"]) @@ -1096,9 +1097,10 @@ fn test_deduplication() { [EOF] "); - // Each new content string only appears once in the log, because all the other - // inputs (like file name) were identical, and so the results were reused. We - // sort the log because the order of execution inside `jj fix` is undefined. + // Each new content string only appears once in the log, because all the + // other inputs (like file name) were identical, and so the results were + // reused. We sort the log because the order of execution inside `jj + // fix` is undefined. insta::assert_snapshot!(sorted_lines(work_dir.root().join("file-fixlog")), @" BAR FOO @@ -1117,8 +1119,9 @@ fn sorted_lines(path: PathBuf) -> String { #[test] fn test_executed_but_nothing_changed() { - // Show that the tool ran by causing a side effect with --tee, and test that we - // do the right thing when the tool's output is exactly equal to its input. + // Show that the tool ran by causing a side effect with --tee, and test that + // we do the right thing when the tool's output is exactly equal to its + // input. let mut test_env = TestEnvironment::default(); set_up_fake_formatter(&mut test_env, &["--tee", "$path-copy"]); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); @@ -1190,8 +1193,8 @@ fn test_stderr_success() { let work_dir = test_env.work_dir("repo"); work_dir.write_file("file", "old content"); - // TODO: Associate the stderr lines with the relevant tool/file/commit instead - // of passing it through directly. + // TODO: Associate the stderr lines with the relevant tool/file/commit + // instead of passing it through directly. let output = work_dir.run_jj(["fix", "-s", "@"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1242,9 +1245,9 @@ fn test_missing_command() { command = ['this_executable_shouldnt_exist'] patterns = ['all()'] "}); - // TODO: We should display a warning about invalid tool configurations. When we - // support multiple tools, we should also keep going to see if any of the other - // executions succeed. + // TODO: We should display a warning about invalid tool configurations. When + // we support multiple tools, we should also keep going to see if any of + // the other executions succeed. let output = work_dir.run_jj(["fix", "-s", "@"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1309,8 +1312,8 @@ fn test_fix_executable() -> TestResult { #[test] fn test_fix_trivial_merge_commit() { - // All the changes are attributable to a parent, so none are fixed (in the same - // way that none would be shown in `jj diff -r @`). + // All the changes are attributable to a parent, so none are fixed (in the + // same way that none would be shown in `jj diff -r @`). let mut test_env = TestEnvironment::default(); set_up_fake_formatter(&mut test_env, &["--uppercase"]); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); @@ -1345,8 +1348,8 @@ fn test_fix_trivial_merge_commit() { #[test] fn test_fix_adding_merge_commit() { - // None of the changes are attributable to a parent, so they are all fixed (in - // the same way that they would be shown in `jj diff -r @`). + // None of the changes are attributable to a parent, so they are all fixed + // (in the same way that they would be shown in `jj diff -r @`). let mut test_env = TestEnvironment::default(); set_up_fake_formatter(&mut test_env, &["--uppercase"]); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); @@ -1405,8 +1408,8 @@ fn test_fix_both_sides_of_conflict() { .success(); work_dir.run_jj(["new", "a", "b"]).success(); - // The conflicts are not different from the merged parent, so they would not be - // fixed if we didn't fix the parents also. + // The conflicts are not different from the merged parent, so they would not + // be fixed if we didn't fix the parents also. let output = work_dir.run_jj(["fix", "-s", "a", "-s", "b"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1444,8 +1447,8 @@ fn test_fix_both_sides_of_conflict() { #[test] fn test_fix_resolve_conflict() { - // If both sides of the conflict look the same after being fixed, the conflict - // will be resolved. + // If both sides of the conflict look the same after being fixed, the + // conflict will be resolved. let mut test_env = TestEnvironment::default(); set_up_fake_formatter(&mut test_env, &["--uppercase"]); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); @@ -1461,8 +1464,8 @@ fn test_fix_resolve_conflict() { .success(); work_dir.run_jj(["new", "a", "b"]).success(); - // The conflicts are not different from the merged parent, so they would not be - // fixed if we didn't fix the parents also. + // The conflicts are not different from the merged parent, so they would not + // be fixed if we didn't fix the parents also. let output = work_dir.run_jj(["fix", "-s", "a", "-s", "b"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1494,8 +1497,8 @@ fn test_all_files() { // File B: in patterns, NOT changed in child // File C: NOT in patterns, NOT changed in child // File D: NOT in patterns, changed in child - // Some files will be in subdirectories to make sure we're covering that aspect - // of matching. + // Some files will be in subdirectories to make sure we're covering that + // aspect of matching. test_env.add_config(format!( r###" [fix.tools.tool] @@ -1517,10 +1520,11 @@ fn test_all_files() { work_dir.write_file("ddd", "child ddd\n"); work_dir.run_jj(["describe", "-m", "child"]).success(); - // Specifying files means exactly those files will be fixed in each revision, - // although some like file C won't have any tools configured to make changes to - // them. Specified but unfixed files are silently skipped, whether they lack - // configuration, are ignored, don't exist, aren't normal files, etc. + // Specifying files means exactly those files will be fixed in each + // revision, although some like file C won't have any tools configured + // to make changes to them. Specified but unfixed files are silently + // skipped, whether they lack configuration, are ignored, don't exist, + // aren't normal files, etc. let output = work_dir.run_jj([ "fix", "--include-unchanged-files", @@ -1793,8 +1797,8 @@ fn test_fix_with_run_tool_if_zero_line_ranges() { .run_jj(["bookmark", "create", "-r@", "c1"]) .success(); - // Create a new commit doing a deletion of a line in foo and bar (which should - // produce empty line ranges). + // Create a new commit doing a deletion of a line in foo and bar (which + // should produce empty line ranges). work_dir.run_jj(["new"]).success(); work_dir.write_file("foo", "Foo1\nFoo3\n"); work_dir.write_file("bar", "Bar1\nBar3\n"); @@ -1855,8 +1859,8 @@ fn test_fix_with_run_tool_if_zero_line_ranges() { [EOF] "); - // Create a new commit doing a deletion of a line in qux. This commit's parent - // is c1. + // Create a new commit doing a deletion of a line in qux. This commit's + // parent is c1. work_dir.run_jj(["new", "-r", "c1"]).success(); work_dir.write_file("qux", "Qux1\nQux3\n"); work_dir @@ -1864,10 +1868,11 @@ fn test_fix_with_run_tool_if_zero_line_ranges() { .success(); // Run `jj fix` on the third commit. This command should pass, but the - // fake-formatter should fail to format qux because `--split-even-length-lines` - // requires line-ranges to be passed into the fake formatter and qux should - // not have any line ranges passed due to run-tool-if-zero-line-ranges. - // This should result in no changes to qux. + // fake-formatter should fail to format qux because + // `--split-even-length-lines` requires line-ranges to be passed into + // the fake formatter and qux should not have any line ranges passed due + // to run-tool-if-zero-line-ranges. This should result in no changes to + // qux. let output = work_dir.run_jj(["fix", "-s", "c3"]).success(); let output = output.normalize_stderr_with(|s| { s.replace(formatter_path.to_str().unwrap(), "fake-formatter") @@ -2056,8 +2061,8 @@ fn test_fix_with_line_ranges_multiple_formatters() { [EOF] "); - // Check that split lines was applied first and then upper was only applied to - // the second half. + // Check that split lines was applied first and then upper was only applied + // to the second half. let output = work_dir.run_jj(["file", "show", "foo", "-r", "c2"]); insta::assert_snapshot!(output, @r" ab @@ -2151,8 +2156,8 @@ fn test_fix_with_line_ranges_and_include_unchanged_files_all_lines() { [EOF] "); - // Check that the formatter was applied to the second commit and all lines were - // affected. + // Check that the formatter was applied to the second commit and all lines + // were affected. let output = work_dir.run_jj(["file", "show", "changed.txt", "-r", "c2"]); insta::assert_snapshot!(output, @" FOO1 diff --git a/cli/tests/test_gerrit_upload.rs b/cli/tests/test_gerrit_upload.rs index 6706e56bfa3..37592927e30 100644 --- a/cli/tests/test_gerrit_upload.rs +++ b/cli/tests/test_gerrit_upload.rs @@ -365,8 +365,8 @@ fn test_gerrit_upload_local_implicit_change_ids() { [EOF] "); - // There's no particular reason to run this with jj util exec, it's just that - // the infra makes it easier to run this way. + // There's no particular reason to run this with jj util exec, it's just + // that the infra makes it easier to run this way. let output = remote_dir.run_jj(["util", "exec", "--", "git", "log", "refs/for/main"]); insta::assert_snapshot!(output, @" commit 68b986d2eb820643b767ae219fb48128dcc2fc03 @@ -463,8 +463,8 @@ review-url = "https://gerrit.example.com/" [EOF] "); - // There's no particular reason to run this with jj util exec, it's just that - // the infra makes it easier to run this way. + // There's no particular reason to run this with jj util exec, it's just + // that the infra makes it easier to run this way. let output = remote_dir.run_jj(["util", "exec", "--", "git", "log", "refs/for/main"]); insta::assert_snapshot!(output, @r" commit b2731737e530be944c12679a86dacca2a3d3c6ad @@ -574,8 +574,8 @@ fn test_gerrit_upload_local_explicit_change_ids() { [EOF] "); - // There's no particular reason to run this with jj util exec, it's just that - // the infra makes it easier to run this way. + // There's no particular reason to run this with jj util exec, it's just + // that the infra makes it easier to run this way. let output = remote_dir.run_jj(["util", "exec", "--", "git", "log", "refs/for/main"]); insta::assert_snapshot!(output, @" commit b4124fc9d4694eecb4d9938cf4874cd13f1252b6 @@ -669,8 +669,8 @@ fn test_gerrit_upload_local_mixed_change_ids() { [EOF] "); - // There's no particular reason to run this with jj util exec, it's just that - // the infra makes it easier to run this way. + // There's no particular reason to run this with jj util exec, it's just + // that the infra makes it easier to run this way. let output = remote_dir.run_jj(["util", "exec", "--", "git", "log", "refs/for/main"]); insta::assert_snapshot!(output, @" commit 015df2b1d38bdc71ae7ef24c2889100e39d34ef8 diff --git a/cli/tests/test_git_colocated.rs b/cli/tests/test_git_colocated.rs index 4bde2e178a6..2cf26a5d2d3 100644 --- a/cli/tests/test_git_colocated.rs +++ b/cli/tests/test_git_colocated.rs @@ -65,8 +65,8 @@ fn test_git_colocated() -> TestResult { [EOF] "); - // Modify the working copy. The working-copy commit should changed, but the Git - // HEAD commit should not + // Modify the working copy. The working-copy commit should changed, but the + // Git HEAD commit should not work_dir.write_file("file", "modified"); insta::assert_snapshot!(get_log_output(&work_dir), @" @ 9dfe8c7005c8dff6078ecdfd953c6bfddc633c90 @@ -121,8 +121,8 @@ fn test_git_colocated_intent_to_add() -> TestResult { work_dir.run_jj(["status"]).success(); insta::assert_snapshot!(get_index_state(work_dir.root()), @"Unconflicted Mode(FILE) e69de29bb2d1 ctime=0:0 mtime=0:0 size=0 flags=20004000 file1.txt"); - // Previously, this would fail due to the empty blob not being written to the - // store when marking files as intent-to-add. + // Previously, this would fail due to the empty blob not being written to + // the store when marking files as intent-to-add. work_dir.run_jj(["util", "gc"]).success(); // Another new file should be marked as intent-to-add @@ -136,7 +136,8 @@ fn test_git_colocated_intent_to_add() -> TestResult { let op_id_new_file = work_dir.current_operation_id(); - // After creating a new commit, it should not longer be marked as intent-to-add + // After creating a new commit, it should not longer be marked as + // intent-to-add work_dir.run_jj(["new"]).success(); work_dir.write_file("file2.txt", "contents"); work_dir.run_jj(["status"]).success(); @@ -509,8 +510,8 @@ fn test_git_colocated_export_bookmarks_on_snapshot() -> TestResult { [EOF] "); - // The bookmark gets updated when we modify the working copy, and it should get - // exported to Git without requiring any other changes + // The bookmark gets updated when we modify the working copy, and it should + // get exported to Git without requiring any other changes work_dir.write_file("file", "modified"); insta::assert_snapshot!(get_log_output(&work_dir), @" @ 00fc09f48ccf5c8b025a0f93b0ec3b0e4294a598 foo @@ -598,8 +599,8 @@ fn test_git_colocated_bookmarks() -> TestResult { [EOF] "); - // Create a bookmark in jj. It should be exported to Git even though it points - // to the working-copy commit. + // Create a bookmark in jj. It should be exported to Git even though it + // points to the working-copy commit. work_dir .run_jj(["bookmark", "create", "-r@", "master"]) .success(); @@ -942,8 +943,8 @@ fn test_git_colocated_fetch_deleted_or_moved_bookmark() -> TestResult { Updated 1 rewritten commits. [EOF] "); - // "original C" and "B_to_delete" are abandoned, as the corresponding bookmarks - // were deleted or moved on the remote (#864) + // "original C" and "B_to_delete" are abandoned, as the corresponding + // bookmarks were deleted or moved on the remote (#864) insta::assert_snapshot!(get_log_output(&clone_dir), @" @ 0060713e4c7c46c4ce0d69a43ac16451582eda79 │ ○ fb297975e4ef98dc057f65b761aed2cdb0386598 C_to_move moved C @@ -1040,8 +1041,8 @@ fn test_git_colocated_external_checkout() -> TestResult { // Check out another bookmark by external command git_check_out_ref("refs/heads/master")?; - // The old working-copy commit gets abandoned, but the whole bookmark should not - // be abandoned. (#1042) + // The old working-copy commit gets abandoned, but the whole bookmark should + // not be abandoned. (#1042) insta::assert_snapshot!(get_log_output(&work_dir), @" @ 7ceeaaae54c8ac99ad34eeed7fe1e896f535be99 ○ 8777db25171cace71ad014598663d5ffc4fae6b1 master A @@ -1347,9 +1348,10 @@ fn test_git_colocated_update_index_preserves_timestamps() -> TestResult { Unconflicted Mode(FILE) d5f7fc3f74f7 ctime=0:0 mtime=0:0 size=0 flags=0 file4.txt "); - // Update index with stats for all files. We may want to do this automatically - // in the future after we update the index in `git::reset_head` (#3786), but for - // now, we at least want to preserve existing stat information when possible. + // Update index with stats for all files. We may want to do this + // automatically in the future after we update the index in + // `git::reset_head` (#3786), but for now, we at least want to preserve + // existing stat information when possible. update_git_index(work_dir.root()); insta::assert_snapshot!(get_index_state(work_dir.root()), @" @@ -1358,8 +1360,8 @@ fn test_git_colocated_update_index_preserves_timestamps() -> TestResult { Unconflicted Mode(FILE) d5f7fc3f74f7 ctime=[nonzero] mtime=[nonzero] size=6 flags=0 file4.txt "); - // Edit parent commit, causing the changes to be removed from the index without - // touching the working copy + // Edit parent commit, causing the changes to be removed from the index + // without touching the working copy work_dir.run_jj(["edit", "commit2"]).success(); insta::assert_snapshot!(get_log_output(&work_dir), @" @@ -1563,8 +1565,9 @@ fn test_git_colocated_update_index_rebase_conflict() -> TestResult { [EOF] "); - // Index should contain files from parent commit, so there should be no conflict - // in conflict.txt yet. The stat for base.txt should not change. + // Index should contain files from parent commit, so there should be no + // conflict in conflict.txt yet. The stat for base.txt should not + // change. insta::assert_snapshot!(get_index_state(work_dir.root()), @" Unconflicted Mode(FILE) df967b96a579 ctime=[nonzero] mtime=[nonzero] size=5 flags=0 base.txt Unconflicted Mode(FILE) c376d892e8b1 ctime=0:0 mtime=0:0 size=0 flags=0 conflict.txt @@ -1583,8 +1586,8 @@ fn test_git_colocated_update_index_rebase_conflict() -> TestResult { [EOF] "); - // Now the working copy commit's parent is conflicted, so the index should have - // a conflict with correct blob IDs. + // Now the working copy commit's parent is conflicted, so the index should + // have a conflict with correct blob IDs. insta::assert_snapshot!(get_index_state(work_dir.root()), @" Unconflicted Mode(FILE) df967b96a579 ctime=[nonzero] mtime=[nonzero] size=5 flags=0 base.txt Base Mode(FILE) df967b96a579 ctime=0:0 mtime=0:0 size=0 flags=1000 conflict.txt @@ -1666,8 +1669,8 @@ fn test_git_colocated_update_index_3_sided_conflict() -> TestResult { [EOF] "); - // We can't add conflicts with more than 2 sides to the index, so we add a dummy - // conflict instead. The stat for base.txt should not change. + // We can't add conflicts with more than 2 sides to the index, so we add a + // dummy conflict instead. The stat for base.txt should not change. insta::assert_snapshot!(get_index_state(work_dir.root()), @" Ours Mode(FILE) eb8299123d2a ctime=0:0 mtime=0:0 size=0 flags=2000 .jj-do-not-resolve-this-conflict Unconflicted Mode(FILE) df967b96a579 ctime=[nonzero] mtime=[nonzero] size=5 flags=0 base.txt diff --git a/cli/tests/test_git_fetch.rs b/cli/tests/test_git_fetch.rs index 6bff397a447..c6db3d6dc4f 100644 --- a/cli/tests/test_git_fetch.rs +++ b/cli/tests/test_git_fetch.rs @@ -917,7 +917,8 @@ fn test_git_fetch_all() { let source_dir = test_env.work_dir("source"); git::init(source_dir.root()); - // Clone an empty repo. The target repo is a normal `jj` repo, *not* colocated + // Clone an empty repo. The target repo is a normal `jj` repo, *not* + // colocated let output = test_env.run_jj_in(".", ["git", "clone", "source", "target"]); insta::assert_snapshot!(output, @r#" ------- stderr ------- @@ -995,7 +996,8 @@ fn test_git_fetch_all() { ◆ 000000000000 "" [EOF] "#); - // Change a bookmark in the source repo as well, so that it becomes conflicted. + // Change a bookmark in the source repo as well, so that it becomes + // conflicted. target_dir .run_jj(["describe", "b", "-m=new_descr_for_b_to_create_conflict"]) .success(); @@ -1075,7 +1077,8 @@ fn test_git_fetch_some_of_many_bookmarks() { let source_dir = test_env.work_dir("source"); git::init(source_dir.root()); - // Clone an empty repo. The target repo is a normal `jj` repo, *not* colocated + // Clone an empty repo. The target repo is a normal `jj` repo, *not* + // colocated let output = test_env.run_jj_in(".", ["git", "clone", "source", "target"]); insta::assert_snapshot!(output, @r#" ------- stderr ------- @@ -1196,7 +1199,8 @@ fn test_git_fetch_some_of_many_bookmarks() { ◆ 000000000000 "" [EOF] "#); - // Change a bookmark in the source repo as well, so that it becomes conflicted. + // Change a bookmark in the source repo as well, so that it becomes + // conflicted. target_dir .run_jj(["describe", "b", "-m=new_descr_for_b_to_create_conflict"]) .success(); @@ -1238,7 +1242,8 @@ fn test_git_fetch_some_of_many_bookmarks() { [EOF] "#); - // We left a2 where it was before, let's see how `jj bookmark list` sees this. + // We left a2 where it was before, let's see how `jj bookmark list` sees + // this. insta::assert_snapshot!(get_bookmark_output(&target_dir), @" a1: mzvwutvl bc7e74c2 a1 @origin: mzvwutvl bc7e74c2 a1 @@ -1251,8 +1256,8 @@ fn test_git_fetch_some_of_many_bookmarks() { @origin (behind by 1 commits): yostqsxw/0 2b30dbc9 (divergent) b [EOF] "); - // Now, let's fetch a2 and double-check that fetching a1 and b again doesn't do - // anything. + // Now, let's fetch a2 and double-check that fetching a1 and b again doesn't + // do anything. let output = target_dir.run_jj(["git", "fetch", "--branch", "b", "--branch", "a*"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1338,8 +1343,8 @@ fn test_git_fetch_bookmarks_some_missing() { [EOF] "); - // multiple existing bookmark, explicit remotes, each bookmark is only in one - // remote. + // multiple existing bookmark, explicit remotes, each bookmark is only in + // one remote. let output = work_dir.run_jj([ "git", "fetch", "--branch", "rem1", "--branch", "rem2", "--branch", "rem3", "--remote", "rem1", "--remote", "rem2", "--remote", "rem3", @@ -1448,7 +1453,8 @@ fn test_git_fetch_undo() { let source_dir = test_env.work_dir("source"); git::init(source_dir.root()); - // Clone an empty repo. The target repo is a normal `jj` repo, *not* colocated + // Clone an empty repo. The target repo is a normal `jj` repo, *not* + // colocated let output = test_env.run_jj_in(".", ["git", "clone", "source", "target"]); insta::assert_snapshot!(output, @r#" ------- stderr ------- @@ -1532,7 +1538,8 @@ fn test_fetch_undo_what() { let source_dir = test_env.work_dir("source"); git::init(source_dir.root()); - // Clone an empty repo. The target repo is a normal `jj` repo, *not* colocated + // Clone an empty repo. The target repo is a normal `jj` repo, *not* + // colocated let output = test_env.run_jj_in(".", ["git", "clone", "source", "target"]); insta::assert_snapshot!(output, @r#" ------- stderr ------- @@ -1607,8 +1614,8 @@ fn test_fetch_undo_what() { @origin (not created yet) [EOF] "); - // Restoring just the remote-tracking state will not affect `newbookmark`, but - // will eliminate `b@origin`. + // Restoring just the remote-tracking state will not affect `newbookmark`, + // but will eliminate `b@origin`. let output = work_dir.run_jj([ "op", "restore", @@ -1736,7 +1743,8 @@ fn test_git_fetch_removed_bookmark() { let source_dir = test_env.work_dir("source"); git::init(source_dir.root()); - // Clone an empty repo. The target repo is a normal `jj` repo, *not* colocated + // Clone an empty repo. The target repo is a normal `jj` repo, *not* + // colocated let output = test_env.run_jj_in(".", ["git", "clone", "source", "target"]); insta::assert_snapshot!(output, @r#" ------- stderr ------- @@ -1807,7 +1815,8 @@ fn test_git_fetch_removed_bookmark() { [EOF] "#); - // Fetch bookmarks a2 from origin, and check that it has been removed locally + // Fetch bookmarks a2 from origin, and check that it has been removed + // locally let output = target_dir.run_jj(["git", "fetch", "--branch", "a2"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1835,7 +1844,8 @@ fn test_git_fetch_removed_parent_bookmark() { let source_dir = test_env.work_dir("source"); git::init(source_dir.root()); - // Clone an empty repo. The target repo is a normal `jj` repo, *not* colocated + // Clone an empty repo. The target repo is a normal `jj` repo, *not* + // colocated let output = test_env.run_jj_in(".", ["git", "clone", "source", "target"]); insta::assert_snapshot!(output, @r#" ------- stderr ------- @@ -1886,9 +1896,9 @@ fn test_git_fetch_removed_parent_bookmark() { .run_jj(["bookmark", "forget", "--include-remotes", "*"]) .success(); - // Fetch bookmarks master, trunk1 and a1 from origin and check that only those - // bookmarks have been removed and that others were not rebased because of - // abandoned commits. + // Fetch bookmarks master, trunk1 and a1 from origin and check that only + // those bookmarks have been removed and that others were not rebased + // because of abandoned commits. let output = target_dir.run_jj([ "git", "fetch", "--branch", "master", "--branch", "trunk1", "--branch", "a1", ]); diff --git a/cli/tests/test_git_import_export.rs b/cli/tests/test_git_import_export.rs index 1b679a23be1..a42d772bf5f 100644 --- a/cli/tests/test_git_import_export.rs +++ b/cli/tests/test_git_import_export.rs @@ -144,8 +144,9 @@ fn test_git_export_undo() -> TestResult { [EOF] "); - // Exported refs won't be removed by undoing the export, but the git-tracking - // bookmark is. This is the same as remote-tracking bookmarks. + // Exported refs won't be removed by undoing the export, but the + // git-tracking bookmark is. This is the same as remote-tracking + // bookmarks. let output = work_dir.run_jj(["undo"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -299,9 +300,9 @@ fn test_git_import_move_export_with_default_undo() -> TestResult { [EOF] "); - // "git import" can be undone with the default `restore` behavior, as shown in - // the previous test. However, "git export" can't: the bookmarks in the git - // repo stay where they were. + // "git import" can be undone with the default `restore` behavior, as shown + // in the previous test. However, "git export" can't: the bookmarks in + // the git repo stay where they were. let output = work_dir.run_jj(["op", "restore", &base_operation_id]); insta::assert_snapshot!(output, @" ------- stderr ------- diff --git a/cli/tests/test_git_init.rs b/cli/tests/test_git_init.rs index dec33d43c65..2b4da9a327a 100644 --- a/cli/tests/test_git_init.rs +++ b/cli/tests/test_git_init.rs @@ -281,7 +281,8 @@ fn test_git_init_external_import_trunk(bare: bool) -> TestResult { // Explicitly enable git.colocate (which is also the default) test_env.add_config("git.colocate = true"); - // Add remote bookmark "trunk" for remote "origin", and set it as "origin/HEAD" + // Add remote bookmark "trunk" for remote "origin", and set it as + // "origin/HEAD" let oid = git_repo.find_reference("refs/heads/my-bookmark")?.id(); git_repo.reference( @@ -320,7 +321,8 @@ fn test_git_init_external_import_trunk(bare: bool) -> TestResult { "#); } - // "trunk()" alias should be set to remote "origin"'s default bookmark "trunk" + // "trunk()" alias should be set to remote "origin"'s default bookmark + // "trunk" let work_dir = test_env.work_dir("repo"); let output = work_dir.run_jj(["config", "list", "--repo", "revset-aliases.\"trunk()\""]); insta::allow_duplicates! { @@ -912,7 +914,8 @@ fn test_git_init_external_but_git_dir_exists() { [EOF] "#); - // The local ".git" repository is unrelated, so no commits should be imported + // The local ".git" repository is unrelated, so no commits should be + // imported insta::assert_snapshot!(get_log_output(&work_dir), @" @ e8849ae12c70 ◆ 000000000000 @@ -1114,8 +1117,8 @@ fn test_git_init_colocated_via_flag_git_dir_not_exists() { .run_jj(["bookmark", "create", "-r@", "main", "master"]) .success(); - // If .git/HEAD pointed to the default bookmark, new working-copy commit would - // be created on top. + // If .git/HEAD pointed to the default bookmark, new working-copy commit + // would be created on top. insta::assert_snapshot!(get_log_output(&work_dir), @" @ e8849ae12c70 main master ◆ 000000000000 @@ -1299,7 +1302,8 @@ fn test_git_init_colocate_gitlink_not_worktree() -> TestResult { let test_env = TestEnvironment::default(); test_env.add_config("git.colocate = true"); - // Create a bare git repo at a path containing "worktrees" as a directory name + // Create a bare git repo at a path containing "worktrees" as a directory + // name let git_repo_path = test_env.env_root().join("worktrees").join("my-repo.git"); std::fs::create_dir_all(&git_repo_path)?; init_git_repo(&git_repo_path, true); diff --git a/cli/tests/test_git_push.rs b/cli/tests/test_git_push.rs index 35de0bee209..1447d6fe8a2 100644 --- a/cli/tests/test_git_push.rs +++ b/cli/tests/test_git_push.rs @@ -220,8 +220,8 @@ fn test_git_push_current_bookmark() { "--allow-backwards", ]) .success(); - // This behavior is a strangeness of our definition of the default push revset. - // We could consider changing it. + // This behavior is a strangeness of our definition of the default push + // revset. We could consider changing it. let output = work_dir.run_jj(["git", "push"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -363,12 +363,13 @@ fn test_git_push_other_remote_has_bookmark() { Nothing changed. [EOF] "); - // The bookmark was moved on the "other" remote as well (since it's actually the - // same remote), but `jj` is not aware of that since it thinks this is a - // different remote. So, the push should fail. + // The bookmark was moved on the "other" remote as well (since it's actually + // the same remote), but `jj` is not aware of that since it thinks this + // is a different remote. So, the push should fail. // - // But it succeeds! That's because the bookmark is created at the same location - // as it is on the remote. This would also work for a descendant. + // But it succeeds! That's because the bookmark is created at the same + // location as it is on the remote. This would also work for a + // descendant. // // TODO: Saner test? work_dir @@ -613,8 +614,8 @@ fn test_git_push_unexpectedly_deleted() { [EOF] "); - // git does not allow to push a deleted bookmark if we expect it to exist even - // though it was already deleted + // git does not allow to push a deleted bookmark if we expect it to exist + // even though it was already deleted let output = work_dir.run_jj(["git", "push", "-bbookmark1"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -704,8 +705,8 @@ fn test_git_push_locally_created_and_rewritten() { [EOF] "); - // Rewrite it and push again, which would fail if the pushed bookmark weren't - // set to "tracking" + // Rewrite it and push again, which would fail if the pushed bookmark + // weren't set to "tracking" work_dir.run_jj(["describe", "-mlocal 2"]).success(); insta::assert_snapshot!(get_bookmark_output(&work_dir), @" bookmark1: qpvuntsm 9b2e76de (empty) description 1 @@ -1001,7 +1002,8 @@ fn test_git_push_changes() { [EOF] "); - // specifying the same bookmark with --change/--bookmark doesn't break things + // specifying the same bookmark with --change/--bookmark doesn't break + // things work_dir.write_file("file", "modified4"); let output = work_dir.run_jj(["git", "push", "-c=@", "-b=push-yostqsxwqrlt"]); insta::assert_snapshot!(output, @" @@ -1130,8 +1132,8 @@ fn test_git_push_changes_with_name() { bookmark: b1 [add to 5f4f9a466c96] [EOF] "); - // Spaces before the = sign are treated like part of the bookmark name and such - // bookmarks cannot be pushed. + // Spaces before the = sign are treated like part of the bookmark name and + // such bookmarks cannot be pushed. let output = work_dir.run_jj(["git", "push", "--named", "b1 = @"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1230,8 +1232,8 @@ fn test_git_push_changes_with_name() { fn test_git_push_changes_with_name_deleted_tracked() { let test_env = TestEnvironment::default(); set_up(&test_env); - // Unset immutable_heads so that untracking branches does not move the working - // copy + // Unset immutable_heads so that untracking branches does not move the + // working copy test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#); let work_dir = test_env.work_dir("local"); // Create a second empty remote `another_remote` @@ -1276,8 +1278,8 @@ fn test_git_push_changes_with_name_deleted_tracked() { [EOF] "); - // Can't push `b1` with --named to the same or another remote if it's deleted - // locally and still tracked on `origin` + // Can't push `b1` with --named to the same or another remote if it's + // deleted locally and still tracked on `origin` let output = work_dir.run_jj(["git", "push", "--named", "b1=@", "--remote=another_remote"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1295,8 +1297,8 @@ fn test_git_push_changes_with_name_deleted_tracked() { [exit status: 1] "); - // OK to push to a different remote once the bookmark is no longer tracked on - // `origin` + // OK to push to a different remote once the bookmark is no longer tracked + // on `origin` work_dir .run_jj(["bookmark", "untrack", "b1", "--remote=origin"]) .success(); @@ -1330,8 +1332,8 @@ fn test_git_push_changes_with_name_untracked_or_forgotten() { let test_env = TestEnvironment::default(); set_up(&test_env); let work_dir = test_env.work_dir("local"); - // Unset immutable_heads so that untracking branches does not move the working - // copy + // Unset immutable_heads so that untracking branches does not move the + // working copy test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#); work_dir.run_jj(["describe", "-m", "parent"]).success(); work_dir.run_jj(["new", "-m", "pushed_to_remote"]).success(); @@ -1402,8 +1404,8 @@ fn test_git_push_changes_with_name_untracked_or_forgotten() { [EOF] "); - // Make sure push still errors if we try to push a bookmark with the same name - // to a different location. + // Make sure push still errors if we try to push a bookmark with the same + // name to a different location. let output = work_dir.run_jj(["git", "push", "--named", "b1=@-"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1436,9 +1438,9 @@ fn test_git_push_changes_with_name_untracked_or_forgotten() { [EOF] [exit status: 1] "); - // In this case, pushing the bookmark to the same location where it already is - // succeeds. TODO: This seems pretty safe, but perhaps it should still show - // an error or some sort of warning? + // In this case, pushing the bookmark to the same location where it already + // is succeeds. TODO: This seems pretty safe, but perhaps it should + // still show an error or some sort of warning? let output = work_dir.run_jj(["git", "push", "--named", "b1=@"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -2422,18 +2424,20 @@ fn test_git_push_tracked_vs_all() { "); // All bookmarks are still untracked. - // - --all tries to push bookmark1, but fails because a bookmark with the same + // - --all tries to push bookmark1, but fails because a bookmark with the + // same // name exist on the remote. - // - --all succeeds in pushing bookmark3, since there is no bookmark of the same + // - --all succeeds in pushing bookmark3, since there is no bookmark of the + // same // name on the remote. // - It does not try to push bookmark2. // - // TODO: Not trying to push bookmark2 could be considered correct, or perhaps - // we want to consider this as a deletion of the bookmark that failed because - // the bookmark was untracked. In the latter case, an error message should be - // printed. Some considerations: - // - Whatever we do should be consistent with what `jj bookmark list` does; it - // currently does *not* list bookmarks like bookmark2 as "about to be + // TODO: Not trying to push bookmark2 could be considered correct, or + // perhaps we want to consider this as a deletion of the bookmark that + // failed because the bookmark was untracked. In the latter case, an + // error message should be printed. Some considerations: + // - Whatever we do should be consistent with what `jj bookmark list` does; + // it currently does *not* list bookmarks like bookmark2 as "about to be // deleted", as can be seen above. // - We could consider showing some hint on `jj bookmark untrack bookmark2 // --remote=origin` instead of showing an error here. @@ -2850,14 +2854,14 @@ fn test_git_push_rejected_by_remote() -> TestResult { // push bookmark let output = work_dir.run_jj(["git", "push"]); - // The git remote sideband adds a dummy suffix of 8 spaces to attempt to clear - // any leftover data. This is done to help with cases where the line is - // rewritten. + // The git remote sideband adds a dummy suffix of 8 spaces to attempt to + // clear any leftover data. This is done to help with cases where the + // line is rewritten. // // However, a common option in a lot of editors removes trailing whitespace. - // This means that anyone with that option that opens this file would make the - // following snapshot fail. Using the insta filter here normalizes the - // output. + // This means that anyone with that option that opens this file would make + // the following snapshot fail. Using the insta filter here normalizes + // the output. let mut settings = insta::Settings::clone_current(); settings.add_filter(r"\s*\n", "\n"); settings.bind(|| { diff --git a/cli/tests/test_git_remotes.rs b/cli/tests/test_git_remotes.rs index f3c4bba6968..64bfda66f7f 100644 --- a/cli/tests/test_git_remotes.rs +++ b/cli/tests/test_git_remotes.rs @@ -590,7 +590,8 @@ fn test_git_remote_rename() { #[test] fn test_git_remote_rename_updates_trunk() { - // Verify trunk() resolves correctly after renaming the remote it references. + // Verify trunk() resolves correctly after renaming the remote it + // references. let test_env = TestEnvironment::default(); let remote_repo = git::init(test_env.env_root().join("remote")); diff --git a/cli/tests/test_gitignores.rs b/cli/tests/test_gitignores.rs index 213e1feebe6..67a83a7d842 100644 --- a/cli/tests/test_gitignores.rs +++ b/cli/tests/test_gitignores.rs @@ -32,7 +32,8 @@ fn test_gitignores() -> TestResult { let mut file = std::fs::OpenOptions::new() .append(true) .open(work_dir.root().join(".git").join("config"))?; - // Put the file in "~/my-ignores" so we also test that "~" expands to "$HOME" + // Put the file in "~/my-ignores" so we also test that "~" expands to + // "$HOME" file.write_all(b"[core]\nexcludesFile=~/my-ignores\n")?; drop(file); std::fs::write( @@ -47,8 +48,8 @@ fn test_gitignores() -> TestResult { file.write_all(b"!file2\n!file3")?; drop(file); - // Say in .gitignore (in the working copy) that we actually do not want file2 - // (again) + // Say in .gitignore (in the working copy) that we actually do not want + // file2 (again) work_dir.write_file(".gitignore", "file2"); // Writes some files to the working copy diff --git a/cli/tests/test_global_opts.rs b/cli/tests/test_global_opts.rs index b63439c0aa1..1c3b0d715d8 100644 --- a/cli/tests/test_global_opts.rs +++ b/cli/tests/test_global_opts.rs @@ -244,9 +244,9 @@ fn test_no_integrate_operation() { let working_copy_output = test_env.run_jj_in(&repo_path, &["debug", "working-copy"]); // Modify the working copy and run a mutating operation. With - // --no-integrate-operation, the working copy gets snapshotted and the operation - // gets created, but there's no new operation in the operation log, and the - // working copy state is not updated. + // --no-integrate-operation, the working copy gets snapshotted and the + // operation gets created, but there's no new operation in the operation + // log, and the working copy state is not updated. std::fs::write(repo_path.join("file2"), "initial").unwrap(); let output = test_env.run_jj_in(&repo_path, &["squash", "--no-integrate-operation"]); insta::assert_snapshot!(output.stdout, @""); @@ -313,9 +313,9 @@ fn test_no_integrate_operation_colocated() { let working_copy_output = test_env.run_jj_in(&repo_path, &["debug", "working-copy"]); // Modify the working copy and run a mutating operation. With - // --no-integrate-operation, the working copy gets snapshotted and the operation - // gets created, but there's no new operation in the operation log, and the - // working copy state is not updated. + // --no-integrate-operation, the working copy gets snapshotted and the + // operation gets created, but there's no new operation in the operation + // log, and the working copy state is not updated. std::fs::write(repo_path.join("file2"), "initial").unwrap(); let output = test_env.run_jj_in(&repo_path, &["squash", "--no-integrate-operation"]); insta::assert_snapshot!(output.stdout, @""); @@ -423,7 +423,8 @@ fn test_resolve_workspace_directory() { [EOF] "); - // "../../..".ancestors() contains "../..", but it should never be looked up. + // "../../..".ancestors() contains "../..", but it should never be looked + // up. let output = sub_dir.run_jj(["status", "-R", "../../.."]); insta::assert_snapshot!(output, @r#" ------- stderr ------- @@ -677,7 +678,8 @@ fn test_color_config() { [EOF] "); - // Test that NO_COLOR does NOT override the request for color in the config file + // Test that NO_COLOR does NOT override the request for color in the config + // file test_env.add_env_var("NO_COLOR", "1"); let work_dir = test_env.work_dir("repo"); let output = work_dir.run_jj(["log", "-T", "commit_id"]); @@ -1307,7 +1309,8 @@ fn test_default_config() -> TestResult { #[test] fn test_no_user_configured() { - // Test that the user is reminded if they haven't configured their name or email + // Test that the user is reminded if they haven't configured their name or + // email let test_env = TestEnvironment::default(); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); diff --git a/cli/tests/test_help_command.rs b/cli/tests/test_help_command.rs index dca2ff448a9..25d888af31c 100644 --- a/cli/tests/test_help_command.rs +++ b/cli/tests/test_help_command.rs @@ -112,7 +112,8 @@ fn test_help() { fn test_help_keyword() { let test_env = TestEnvironment::default(); - // It should show help for a certain keyword if the `--keyword` flag is present + // It should show help for a certain keyword if the `--keyword` flag is + // present let help_cmd = test_env .run_jj_in(".", ["help", "--keyword", "revsets"]) .success(); diff --git a/cli/tests/test_identical_commits.rs b/cli/tests/test_identical_commits.rs index a577db0ae89..c91b656751f 100644 --- a/cli/tests/test_identical_commits.rs +++ b/cli/tests/test_identical_commits.rs @@ -122,8 +122,8 @@ fn test_identical_commits_by_convergent_rewrite() { [EOF] [exit status: 255] "); - // TODO: The "test3" commit should have either "test1" or "test2" as predecessor - // (or both?) + // TODO: The "test3" commit should have either "test1" or "test2" as + // predecessor (or both?) insta::assert_snapshot!(work_dir.run_jj(["evolog"]), @" @ oxmtprsl/1 test.user@example.com 2001-01-01 11:00:00 c5abd225 (divergent) (empty) test2 @@ -158,8 +158,8 @@ fn test_identical_commits_by_convergent_rewrite_one_operation() { ◆ 000000000000 [EOF] "); - // TODO: The "test3" commit should have either "test1" or "test2" as predecessor - // (or both?) + // TODO: The "test3" commit should have either "test1" or "test2" as + // predecessor (or both?) insta::assert_snapshot!(work_dir.run_jj(["evolog"]), @" @ oxmtprsl/0 test.user@example.com 2001-01-01 11:00:00 c5abd225 (divergent) (empty) test2 diff --git a/cli/tests/test_immutable_commits.rs b/cli/tests/test_immutable_commits.rs index a516f77b8d7..10660f6defc 100644 --- a/cli/tests/test_immutable_commits.rs +++ b/cli/tests/test_immutable_commits.rs @@ -69,7 +69,8 @@ fn test_rewrite_immutable_generic() { [EOF] [exit status: 1] "#); - // Cannot rewrite the root commit even with an empty set of immutable commits + // Cannot rewrite the root commit even with an empty set of immutable + // commits test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#); let output = work_dir.run_jj(["edit", "root()"]); insta::assert_snapshot!(output, @" @@ -331,8 +332,8 @@ fn test_rewrite_immutable_commands() { work_dir .run_jj(["new", "visible_heads()", "-m=merge"]) .success(); - // Create another file to make sure the merge commit isn't empty (to satisfy `jj - // split`) and still has a conflict (to satisfy `jj resolve`). + // Create another file to make sure the merge commit isn't empty (to satisfy + // `jj split`) and still has a conflict (to satisfy `jj resolve`). work_dir.write_file("file2", "merged"); work_dir .run_jj(["bookmark", "create", "-r@", "main"]) diff --git a/cli/tests/test_interdiff_command.rs b/cli/tests/test_interdiff_command.rs index f4170c7d8eb..d8a24e3b06e 100644 --- a/cli/tests/test_interdiff_command.rs +++ b/cli/tests/test_interdiff_command.rs @@ -144,7 +144,8 @@ fn test_interdiff_paths() { [EOF] "); - // Running interdiff on commits with deleted files should not show a warning. + // Running interdiff on commits with deleted files should not show a + // warning. work_dir.run_jj(["edit", "right"]).success(); work_dir.remove_file("file1"); work_dir.run_jj(["new"]).success(); diff --git a/cli/tests/test_log_command.rs b/cli/tests/test_log_command.rs index 8a7708e8ec8..f8bf69b7523 100644 --- a/cli/tests/test_log_command.rs +++ b/cli/tests/test_log_command.rs @@ -288,7 +288,8 @@ fn test_log_with_or_without_diff() { [EOF] "); - // `-p` enables default "color-words" diff output, so `--color-words` is noop + // `-p` enables default "color-words" diff output, so `--color-words` is + // noop let output = work_dir.run_jj(["log", "-T", "description", "-p", "--color-words"]); insta::assert_snapshot!(output, @" @ a new commit @@ -1173,8 +1174,8 @@ fn test_log_warn_path_might_be_revset() { [EOF] "#); - // warn when checking `jj log .` in a subdirectory because this folder hasn't - // been added to the working copy, yet. + // warn when checking `jj log .` in a subdirectory because this folder + // hasn't been added to the working copy, yet. let sub_dir = work_dir.create_dir_all("dir"); let output = sub_dir.run_jj(["log", "."]); insta::assert_snapshot!(output, @" @@ -1279,7 +1280,8 @@ fn test_multiple_revsets() { .success(); } - // Default revset should be overridden if one or more -r options are specified. + // Default revset should be overridden if one or more -r options are + // specified. test_env.add_config(r#"revsets.log = "root()""#); insta::assert_snapshot!( @@ -1309,7 +1311,8 @@ fn test_multiple_revsets() { #[test] fn test_graph_template_color() { - // Test that color codes from a multi-line template don't span the graph lines. + // Test that color codes from a multi-line template don't span the graph + // lines. let test_env = TestEnvironment::default(); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); @@ -1689,8 +1692,8 @@ fn test_elided() { [EOF] "); - // Elide some commits from each side of the merge. It's unclear that a revision - // was skipped on the left side. + // Elide some commits from each side of the merge. It's unclear that a + // revision was skipped on the left side. test_env.add_config("ui.log-synthetic-elided-nodes = false"); insta::assert_snapshot!(get_log("@ | @- | subject(initial)"), @" @ merge @@ -1705,8 +1708,8 @@ fn test_elided() { [EOF] "); - // Elide shared commits. It's unclear that a revision was skipped on the right - // side (#1252). + // Elide shared commits. It's unclear that a revision was skipped on the + // right side (#1252). insta::assert_snapshot!(get_log("@-- | root()"), @" ○ side bookmark 1 ╷ diff --git a/cli/tests/test_metaedit_command.rs b/cli/tests/test_metaedit_command.rs index 95f863ba70f..6c787d295ec 100644 --- a/cli/tests/test_metaedit_command.rs +++ b/cli/tests/test_metaedit_command.rs @@ -352,7 +352,8 @@ fn test_metaedit() { [EOF] "); - // When resetting the description has no effect, the commits are not rewritten. + // When resetting the description has no effect, the commits are not + // rewritten. work_dir.run_jj(["op", "restore", &setup_opid]).success(); let output = work_dir.run_jj(["metaedit", "--message", "", "kkmpptxzrspx"]); insta::assert_snapshot!(output, @" diff --git a/cli/tests/test_new_command.rs b/cli/tests/test_new_command.rs index 75bb6acfaa6..73fc0de3e84 100644 --- a/cli/tests/test_new_command.rs +++ b/cli/tests/test_new_command.rs @@ -34,7 +34,8 @@ fn test_new() { [EOF] "); - // Start a new change off of a specific commit (the root commit in this case). + // Start a new change off of a specific commit (the root commit in this + // case). work_dir .run_jj(["new", "-m", "off of root", "root()"]) .success(); diff --git a/cli/tests/test_next_prev_commands.rs b/cli/tests/test_next_prev_commands.rs index f96543c5170..ca1bcf85f07 100644 --- a/cli/tests/test_next_prev_commands.rs +++ b/cli/tests/test_next_prev_commands.rs @@ -829,8 +829,8 @@ fn test_prev_conflict_editing() { #[test] fn test_next_conflict() { - // There is a conflict in the third commit, so after next it should be the new - // parent. + // There is a conflict in the third commit, so after next it should be the + // new parent. let test_env = TestEnvironment::default(); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); @@ -901,7 +901,8 @@ fn test_next_conflict_editing() { #[test] fn test_next_conflict_head() { - // When editing a head with conflicts, `jj next --conflict [--edit]` errors out. + // When editing a head with conflicts, `jj next --conflict [--edit]` errors + // out. let test_env = TestEnvironment::default(); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); diff --git a/cli/tests/test_op_integrate_command.rs b/cli/tests/test_op_integrate_command.rs index 59309af297c..d0aae90dead 100644 --- a/cli/tests/test_op_integrate_command.rs +++ b/cli/tests/test_op_integrate_command.rs @@ -54,8 +54,8 @@ fn test_integrate_sibling_operation() -> TestResult { heads_dir.join(&unintegrated_id), heads_dir.join(&base_op_id), )?; - // We use --ignore-working-copy to prevent the automatic reloading of the repo - // at the unintegrated operation that's mentioned in + // We use --ignore-working-copy to prevent the automatic reloading of the + // repo at the unintegrated operation that's mentioned in // `.jj/working_copy/checkout`. let output = work_dir.run_jj(["new", "-m=second", "--ignore-working-copy"]); insta::assert_snapshot!(output, @""); @@ -118,8 +118,8 @@ fn test_integrate_rebase_descendants() -> TestResult { heads_dir.join(&base_op_id), )?; - // We use --ignore-working-copy to prevent the automatic reloading of the repo - // at the unintegrated operation that's mentioned in + // We use --ignore-working-copy to prevent the automatic reloading of the + // repo at the unintegrated operation that's mentioned in // `.jj/working_copy/checkout`. let output = work_dir.run_jj(["describe", "-m=parent", "--ignore-working-copy"]); insta::assert_snapshot!(output, @r" @@ -200,8 +200,8 @@ fn test_integrate_concurrent_operations() -> TestResult { heads_dir.join(&base_op_id), )?; - // We use --ignore-working-copy to prevent the automatic reloading of the repo - // at the unintegrated operation that's mentioned in + // We use --ignore-working-copy to prevent the automatic reloading of the + // repo at the unintegrated operation that's mentioned in // `.jj/working_copy/checkout`. let output = work_dir.run_jj(["describe", "-m=right", "--ignore-working-copy"]); insta::assert_snapshot!(output, @""); diff --git a/cli/tests/test_op_revert_command.rs b/cli/tests/test_op_revert_command.rs index 6203943020c..03b7229b71a 100644 --- a/cli/tests/test_op_revert_command.rs +++ b/cli/tests/test_op_revert_command.rs @@ -55,8 +55,9 @@ fn test_revert_merge_operation() { #[test] fn test_revert_rewrite_with_child() { - // Test that if we revert an operation that rewrote some commit, any descendants - // after that will be rebased on top of the un-rewritten commit. + // Test that if we revert an operation that rewrote some commit, any + // descendants after that will be rebased on top of the un-rewritten + // commit. let test_env = TestEnvironment::default(); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); @@ -73,8 +74,8 @@ fn test_revert_rewrite_with_child() { "); work_dir.run_jj(["op", "revert", "@-"]).success(); - // Since we undid the description-change, the child commit should now be on top - // of the initial commit + // Since we undid the description-change, the child commit should now be on + // top of the initial commit let output = work_dir.run_jj(["log", "-T", "description"]); insta::assert_snapshot!(output, @" @ child @@ -225,9 +226,9 @@ fn test_git_push_revert_with_import() { [EOF] "); - // PROBLEM: inserting this import changes the outcome compared to previous test - // TODO: decide if this is the better behavior, and whether import of - // remote-tracking bookmarks should happen on every operation. + // PROBLEM: inserting this import changes the outcome compared to previous + // test TODO: decide if this is the better behavior, and whether import + // of remote-tracking bookmarks should happen on every operation. work_dir.run_jj(["git", "import"]).success(); // | jj refs | jj's | git // | | git | repo @@ -243,8 +244,8 @@ fn test_git_push_revert_with_import() { test_env.advance_test_rng_seed_to_multiple_of(100_000); work_dir.run_jj(["describe", "-m", "CC"]).success(); work_dir.run_jj(["git", "fetch"]).success(); - // There is not a conflict. This seems like a good outcome; reverting `git push` - // was essentially a no-op. + // There is not a conflict. This seems like a good outcome; reverting `git + // push` was essentially a no-op. insta::assert_snapshot!(get_bookmark_output(&work_dir), @" main: qpvuntsm 1e742089 (empty) CC @origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 d9a9f6a0 (hidden) (empty) BB @@ -326,8 +327,8 @@ fn test_git_push_revert_colocated() { test_env.advance_test_rng_seed_to_multiple_of(100_000); work_dir.run_jj(["describe", "-m", "CC"]).success(); work_dir.run_jj(["git", "fetch"]).success(); - // We have the same conflict as `test_git_push_revert`. TODO: why did we get the - // same result in a seemingly different way? + // We have the same conflict as `test_git_push_revert`. TODO: why did we get + // the same result in a seemingly different way? insta::assert_snapshot!(get_bookmark_output(&work_dir), @" main (conflicted): - qpvuntsm/2 3a44d6c5 (hidden) (empty) AA @@ -374,7 +375,8 @@ fn test_git_push_revert_repo_only() { let pre_push_opid = work_dir.current_operation_id(); work_dir.run_jj(["git", "push"]).success(); - // Revert the push, but keep both the git_refs and the remote-tracking bookmarks + // Revert the push, but keep both the git_refs and the remote-tracking + // bookmarks work_dir .run_jj(["op", "restore", "--what=repo", &pre_push_opid]) .success(); @@ -386,7 +388,8 @@ fn test_git_push_revert_repo_only() { test_env.advance_test_rng_seed_to_multiple_of(100_000); work_dir.run_jj(["describe", "-m", "CC"]).success(); work_dir.run_jj(["git", "fetch"]).success(); - // This currently gives an identical result to `test_git_push_revert_import`. + // This currently gives an identical result to + // `test_git_push_revert_import`. insta::assert_snapshot!(get_bookmark_output(&work_dir), @" main: qpvuntsm 1e742089 (empty) CC @origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 d9a9f6a0 (hidden) (empty) BB diff --git a/cli/tests/test_operations.rs b/cli/tests/test_operations.rs index 8048c256db1..6bf8793af53 100644 --- a/cli/tests/test_operations.rs +++ b/cli/tests/test_operations.rs @@ -1436,7 +1436,8 @@ fn test_op_diff() { let first_parent_id = op_log_lines[3].split(' ').nth(3).unwrap(); let second_parent_id = op_log_lines[6].split(' ').nth(3).unwrap(); - // Diff between the first parent of the merge operation and the merge operation. + // Diff between the first parent of the merge operation and the merge + // operation. let output = work_dir.run_jj(["op", "diff", "--from", first_parent_id, "--to", op_id]); insta::assert_snapshot!(output, @" From operation: 68d99f04e273 (2001-02-03 08:05:19) point bookmark bookmark-1 to commit e8849ae12c709f2321908879bc724fdb2ab8a781 @@ -3301,7 +3302,8 @@ fn test_op_immutable_revisions() { [EOF] "); - // 4. Case where exactly one immutable revision is elided (singular "revision") + // 4. Case where exactly one immutable revision is elided (singular + // "revision") work_dir .run_jj(["new", "root()", "-m", "single-1"]) .success(); @@ -3594,8 +3596,8 @@ commit_summary = 'commit_id.short() ++ " " ++ description.first_line()' [EOF] "); - // 7. Test op show for op_create with the flag: should show all changes and NO - // WARNING. + // 7. Test op show for op_create with the flag: should show all changes and + // NO WARNING. insta::assert_snapshot!(work_dir.run_jj(["op", "show", &op_create, "--show-changes-in", "all()"]), @" e57fae0b2f31 test-username@host.example.com default@ 2001-02-03 04:05:09.000 +07:00 - 2001-02-03 04:05:09.000 +07:00 create bookmark bookmark_x pointing to commit 2308e5a241f7a47f186b0686ffb17aa613a727d7 diff --git a/cli/tests/test_rebase_command.rs b/cli/tests/test_rebase_command.rs index 2015f2ab0fa..492d6e847c4 100644 --- a/cli/tests/test_rebase_command.rs +++ b/cli/tests/test_rebase_command.rs @@ -354,8 +354,8 @@ fn test_rebase_single_revision() { "); let setup_opid = work_dir.current_operation_id(); - // Descendants of the rebased commit "c" should be rebased onto parents. First - // we test with a non-merge commit. + // Descendants of the rebased commit "c" should be rebased onto parents. + // First we test with a non-merge commit. let output = work_dir.run_jj(["rebase", "-r", "c", "-o", "b"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -380,8 +380,8 @@ fn test_rebase_single_revision() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Now, let's try moving the merge commit. After, both parents of "d" ("b" and - // "c") should become parents of "e". + // Now, let's try moving the merge commit. After, both parents of "d" ("b" + // and "c") should become parents of "e". let output = work_dir.run_jj(["rebase", "-r", "d", "-o", "a"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -520,9 +520,9 @@ fn test_rebase_multiple_revisions() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Test with two related non-merge commits. Since "b" is a parent of "c", when - // rebasing commits "b" and "c", their ancestry relationship should be - // preserved. + // Test with two related non-merge commits. Since "b" is a parent of "c", + // when rebasing commits "b" and "c", their ancestry relationship should + // be preserved. let output = work_dir.run_jj(["rebase", "-r", "b", "-r", "c", "-o", "e"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -552,11 +552,11 @@ fn test_rebase_multiple_revisions() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Test with a subgraph containing a merge commit. Since the merge commit "f" - // was extracted, its descendants which are not part of the subgraph will - // inherit its descendants which are not in the subtree ("c" and "d"). - // "f" will retain its parent "c" since "c" is outside the target set, and not - // a descendant of any new children. + // Test with a subgraph containing a merge commit. Since the merge commit + // "f" was extracted, its descendants which are not part of the subgraph + // will inherit its descendants which are not in the subtree ("c" and + // "d"). "f" will retain its parent "c" since "c" is outside the target + // set, and not a descendant of any new children. let output = work_dir.run_jj(["rebase", "-r", "e::g", "-o", "a"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -591,8 +591,8 @@ fn test_rebase_multiple_revisions() { // Test with commits in a disconnected subgraph. The subgraph has the // relationship d->e->f->g->h, but only "d", "f" and "h" are in the set of // rebased commits. "d" should be a new parent of "f", and "f" should be a - // new parent of "h". "f" will retain its parent "c" since "c" is outside the - // target set, and not a descendant of any new children. + // new parent of "h". "f" will retain its parent "c" since "c" is outside + // the target set, and not a descendant of any new children. let output = work_dir.run_jj(["rebase", "-r", "d", "-r", "f", "-r", "h", "-o", "b"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -884,8 +884,8 @@ fn test_rebase_with_descendants() { [EOF] "); - // `d` was a descendant of `b`, and both are moved to be direct descendants of - // `a`. `c` remains a descendant of `b`. + // `d` was a descendant of `b`, and both are moved to be direct descendants + // of `a`. `c` remains a descendant of `b`. let output = work_dir.run_jj(["rebase", "-s=b", "-s=d", "-d=a"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1065,8 +1065,8 @@ fn test_rebase_with_child_and_descendant_bug_2600() { [EOF] "); - // The commits in roots(base..c), i.e. commit "a" should be rebased onto "base", - // which is a no-op + // The commits in roots(base..c), i.e. commit "a" should be rebased onto + // "base", which is a no-op let output = work_dir.run_jj(["rebase", "-b", "c", "-o", "base"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1243,8 +1243,9 @@ fn test_rebase_with_child_and_descendant_bug_2600() { Added 0 files, modified 0 files, removed 1 files [EOF] "); - // In this case, it is unclear whether the user would always prefer unsimplified - // ancestry (whether `b` should also be a direct child of the root commit). + // In this case, it is unclear whether the user would always prefer + // unsimplified ancestry (whether `b` should also be a direct child of + // the root commit). insta::assert_snapshot!(get_log_output(&work_dir), @" @ c: b ○ b: base @@ -1308,8 +1309,8 @@ fn test_rebase_with_child_and_descendant_bug_2600() { [EOF] "); - // In this test, the commit with weird ancestry is not rebased (neither directly - // nor indirectly). + // In this test, the commit with weird ancestry is not rebased (neither + // directly nor indirectly). work_dir.run_jj(["op", "restore", &setup_opid]).success(); let output = work_dir.run_jj(["rebase", "-r", "c", "-o", "a"]); insta::assert_snapshot!(output, @r" @@ -1417,8 +1418,9 @@ fn test_rebase_after() { [EOF] "); - // Rebase a commit after another commit. "c" has parents "b2" and "b4", so its - // children "d" and "e" should be rebased onto "b2" and "b4" respectively. + // Rebase a commit after another commit. "c" has parents "b2" and "b4", so + // its children "d" and "e" should be rebased onto "b2" and "b4" + // respectively. let output = work_dir.run_jj(["rebase", "-r", "c", "--after", "e"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1534,8 +1536,8 @@ fn test_rebase_after() { work_dir.run_jj(["op", "restore", &setup_opid]).success(); // Rebase a commit after a commit with multiple children. - // "c" has two children "d" and "e", so the rebased commit "f" will inherit the - // two children. + // "c" has two children "d" and "e", so the rebased commit "f" will inherit + // the two children. let output = work_dir.run_jj(["rebase", "-r", "f", "--after", "c"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1624,8 +1626,8 @@ fn test_rebase_after() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Rebase a subgraph with merge commit and two parents, which should preserve - // the merge. + // Rebase a subgraph with merge commit and two parents, which should + // preserve the merge. let output = work_dir.run_jj(["rebase", "-r", "b2", "-r", "b4", "-r", "c", "--after", "f"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1685,9 +1687,9 @@ fn test_rebase_after() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Rebase a subgraph before the parents of one of the commits in the subgraph. - // "c" had parents "b2" and "b4", but no longer has "b4" as a parent since - // "b4" would be a descendant of "c" after the rebase. + // Rebase a subgraph before the parents of one of the commits in the + // subgraph. "c" had parents "b2" and "b4", but no longer has "b4" as a + // parent since "b4" would be a descendant of "c" after the rebase. let output = work_dir.run_jj(["rebase", "-r", "b2::d", "--after", "root()"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1745,7 +1747,8 @@ fn test_rebase_after() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // `rebase -s` of commit "c" and its descendants after itself should be a no-op. + // `rebase -s` of commit "c" and its descendants after itself should be a + // no-op. let output = work_dir.run_jj(["rebase", "-s", "c", "--after", "c"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1935,8 +1938,9 @@ fn test_rebase_before() { [exit status: 1] "); - // Rebase a commit before another commit. "c" has parents "b2" and "b4", so its - // children "d" and "e" should be rebased onto "b2" and "b4" respectively. + // Rebase a commit before another commit. "c" has parents "b2" and "b4", so + // its children "d" and "e" should be rebased onto "b2" and "b4" + // respectively. let output = work_dir.run_jj(["rebase", "-r", "c", "--before", "a"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2051,9 +2055,9 @@ fn test_rebase_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Rebase a commit before a merge commit. "c" has two parents "b2" and "b4", so - // the rebased commit "f" will have the two commits "b2" and "b4" as its - // parents. + // Rebase a commit before a merge commit. "c" has two parents "b2" and "b4", + // so the rebased commit "f" will have the two commits "b2" and "b4" as + // its parents. let output = work_dir.run_jj(["rebase", "-r", "f", "--before", "c"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2111,8 +2115,8 @@ fn test_rebase_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Rebase a commit before two commits in separate bookmarks to create a merge - // commit. + // Rebase a commit before two commits in separate bookmarks to create a + // merge commit. let output = work_dir.run_jj(["rebase", "-r", "f", "--before", "b2", "--before", "b4"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2144,8 +2148,8 @@ fn test_rebase_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Rebase two unrelated commits "b2" and "b4" before a single commit "a". This - // creates a merge commit "a" with the two parents "b2" and "b4". + // Rebase two unrelated commits "b2" and "b4" before a single commit "a". + // This creates a merge commit "a" with the two parents "b2" and "b4". let output = work_dir.run_jj(["rebase", "-r", "b2", "-r", "b4", "--before", "a"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2234,9 +2238,9 @@ fn test_rebase_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Rebase a subgraph before the parents of one of the commits in the subgraph. - // "c" had parents "b2" and "b4", but no longer has "b4" as a parent since - // "b4" would be a descendant of "c" after the rebase. + // Rebase a subgraph before the parents of one of the commits in the + // subgraph. "c" had parents "b2" and "b4", but no longer has "b4" as a + // parent since "b4" would be a descendant of "c" after the rebase. let output = work_dir.run_jj(["rebase", "-r", "b2::d", "--before", "a"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2264,9 +2268,9 @@ fn test_rebase_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Rebase a subgraph before the parents of one of the commits in the subgraph. - // "c" had parents "b2" and "b4", but no longer has "b4" as a parent since - // "b4" would be a descendant of "c" after the rebase. + // Rebase a subgraph before the parents of one of the commits in the + // subgraph. "c" had parents "b2" and "b4", but no longer has "b4" as a + // parent since "b4" would be a descendant of "c" after the rebase. let output = work_dir.run_jj(["rebase", "-r", "b2::d", "--before", "a"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2352,9 +2356,9 @@ fn test_rebase_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // `rebase -b` of commit "b3" before "b2" moves its descendants which are not - // already descendants of its parent "b1" (just "b3" and "b4") in between "b1" - // and its child "b2". + // `rebase -b` of commit "b3" before "b2" moves its descendants which are + // not already descendants of its parent "b1" (just "b3" and "b4") in + // between "b1" and its child "b2". let output = work_dir.run_jj(["rebase", "-b", "b3", "--before", "b1"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2461,8 +2465,8 @@ fn test_rebase_after_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Rebase a commit after another commit and before that commit's descendant to - // create a new merge commit. + // Rebase a commit after another commit and before that commit's descendant + // to create a new merge commit. let output = work_dir.run_jj(["rebase", "-r", "d", "--after", "a", "--before", "f"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2495,10 +2499,10 @@ fn test_rebase_after_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // "c" has parents "b1" and "b2", so when it is rebased, its children "d" and - // "e" should have "b1" and "b2" as parents as well. "c" is then inserted in - // between "d" and "e", making "e" a merge commit with 3 parents "b1", "b2", - // and "c". + // "c" has parents "b1" and "b2", so when it is rebased, its children "d" + // and "e" should have "b1" and "b2" as parents as well. "c" is then + // inserted in between "d" and "e", making "e" a merge commit with 3 + // parents "b1", "b2", and "c". let output = work_dir.run_jj(["rebase", "-r", "c", "--after", "d", "--before", "e"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -2529,10 +2533,10 @@ fn test_rebase_after_before() { "); work_dir.run_jj(["op", "restore", &setup_opid]).success(); - // Rebase multiple commits and preserve their ancestry. Apart from the heads of - // the target commits ("d" and "e"), "f" also has commits "b1" and "b2" as - // parents since its parents "d" and "e" were in the target set and were - // replaced by their closest ancestors outside the target set. + // Rebase multiple commits and preserve their ancestry. Apart from the heads + // of the target commits ("d" and "e"), "f" also has commits "b1" and + // "b2" as parents since its parents "d" and "e" were in the target set + // and were replaced by their closest ancestors outside the target set. let output = work_dir.run_jj([ "rebase", "-r", "c", "-r", "d", "-r", "e", "--after", "a", "--before", "f", ]); @@ -2683,8 +2687,8 @@ fn test_rebase_skip_emptied() { [EOF] "); - // The parent commit became empty and was dropped, but the already empty commits - // were kept + // The parent commit became empty and was dropped, but the already empty + // commits were kept insta::assert_snapshot!(work_dir.run_jj(["log", "-T", "description"]), @" @ also already empty ○ already empty @@ -2723,8 +2727,8 @@ fn test_rebase_skip_emptied() { [EOF] "); - // Rebasing a single commit which becomes empty abandons that commit, whilst its - // already empty descendants were kept + // Rebasing a single commit which becomes empty abandons that commit, whilst + // its already empty descendants were kept insta::assert_snapshot!(work_dir.run_jj(["log", "-T", "description"]), @" @ also already empty ○ already empty diff --git a/cli/tests/test_resolve_command.rs b/cli/tests/test_resolve_command.rs index 53e3f7b7e54..afe513b4e71 100644 --- a/cli/tests/test_resolve_command.rs +++ b/cli/tests/test_resolve_command.rs @@ -191,7 +191,8 @@ fn test_resolution() -> TestResult { "#); // Check that if merge tool leaves conflict markers in output file and - // `merge-tool-edits-conflict-markers=true`, these markers are properly parsed. + // `merge-tool-edits-conflict-markers=true`, these markers are properly + // parsed. work_dir.run_jj(["op", "restore", &setup_opid]).success(); insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @""); std::fs::write( @@ -334,8 +335,8 @@ fn test_resolution() -> TestResult { [exit status: 2] "); - // Check that merge tool can override conflict marker style setting, and that - // the merge tool can output Git-style conflict markers + // Check that merge tool can override conflict marker style setting, and + // that the merge tool can output Git-style conflict markers work_dir.run_jj(["op", "restore", &setup_opid]).success(); insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @""); std::fs::write( @@ -484,7 +485,8 @@ fn test_resolution() -> TestResult { "); // Check that an error is reported if a merge tool indicated it would leave - // conflict markers, but the output file didn't contain valid conflict markers. + // conflict markers, but the output file didn't contain valid conflict + // markers. work_dir.run_jj(["op", "restore", &setup_opid]).success(); insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @""); std::fs::write( @@ -623,8 +625,8 @@ fn check_resolve_produces_input_file( std::fs::write(editor_script, format!("expect\n{expected_content}")).unwrap(); let merge_arg_config = format!(r#"merge-tools.fake-editor.merge-args=["${role}"]"#); - // This error means that fake-editor exited successfully but did not modify the - // output file. + // This error means that fake-editor exited successfully but did not modify + // the output file. let output = work_dir.run_jj(["resolve", "--config", &merge_arg_config, filename]); insta::allow_duplicates! { insta::assert_snapshot!( @@ -762,8 +764,8 @@ fn test_simplify_conflict_sides() -> TestResult { test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); - // Creates a 4-sided conflict, with fileA and fileB having different conflicts: - // fileA: A - B + C - B + B - B + B + // Creates a 4-sided conflict, with fileA and fileB having different + // conflicts: fileA: A - B + C - B + B - B + B // fileB: A - A + A - A + B - C + D create_commit_with_files( &work_dir, @@ -812,7 +814,8 @@ fn test_simplify_conflict_sides() -> TestResult { >>>>>>> conflict 1 of 1 ends "#); - // Conflict should be simplified before being handled by external merge tool. + // Conflict should be simplified before being handled by external merge + // tool. check_resolve_produces_input_file(&mut test_env, "repo", "fileA", "base", "base\n"); check_resolve_produces_input_file(&mut test_env, "repo", "fileA", "left", "1\n"); check_resolve_produces_input_file(&mut test_env, "repo", "fileA", "right", "2\n"); @@ -820,8 +823,8 @@ fn test_simplify_conflict_sides() -> TestResult { check_resolve_produces_input_file(&mut test_env, "repo", "fileB", "left", "1\n"); check_resolve_produces_input_file(&mut test_env, "repo", "fileB", "right", "2\n"); - // Check that simplified conflicts are still parsed as conflicts after editing - // when `merge-tool-edits-conflict-markers=true`. + // Check that simplified conflicts are still parsed as conflicts after + // editing when `merge-tool-edits-conflict-markers=true`. let editor_script = test_env.set_up_fake_editor(); std::fs::write( editor_script, @@ -1029,8 +1032,8 @@ fn test_resolve_conflicts_with_executable() -> TestResult { test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); - // Create a conflict in "file1" where all 3 terms are executables, and create a - // conflict in "file2" where one side set the executable bit. + // Create a conflict in "file1" where all 3 terms are executables, and + // create a conflict in "file2" where one side set the executable bit. create_commit_with_files( &work_dir, "base", @@ -1081,7 +1084,8 @@ fn test_resolve_conflicts_with_executable() -> TestResult { ); let setup_opid = work_dir.current_operation_id(); - // Test resolving the conflict in "file1", which should produce an executable + // Test resolving the conflict in "file1", which should produce an + // executable std::fs::write(&editor_script, b"write\nresolution1\n")?; let output = work_dir.run_jj(["resolve", "file1"]); insta::assert_snapshot!(output, @" @@ -1125,7 +1129,8 @@ fn test_resolve_conflicts_with_executable() -> TestResult { [EOF] "); - // Test resolving the conflict in "file2", which should produce an executable + // Test resolving the conflict in "file2", which should produce an + // executable work_dir.run_jj(["op", "restore", &setup_opid]).success(); std::fs::write(&editor_script, b"write\nresolution2\n")?; let output = work_dir.run_jj(["resolve", "file2"]); @@ -1747,8 +1752,8 @@ fn test_resolve_long_conflict_markers() -> TestResult { [EOF] "); - // If the merge tool accepts the marker length as an argument, then the conflict - // markers should be at least as long as "$marker_length" + // If the merge tool accepts the marker length as an argument, then the + // conflict markers should be at least as long as "$marker_length" work_dir.run_jj(["op", "restore", &setup_opid]).success(); std::fs::write( &editor_script, @@ -2074,7 +2079,8 @@ fn test_multiple_conflicts_with_error() -> TestResult { ); let setup_opid = work_dir.current_operation_id(); - // Test resolving one conflict, then exiting without resolving the second one + // Test resolving one conflict, then exiting without resolving the second + // one std::fs::write( &editor_script, ["write\nresolution1\n", "next invocation\n"].join("\0"), diff --git a/cli/tests/test_restore_command.rs b/cli/tests/test_restore_command.rs index 65a6f31d275..eeefd187022 100644 --- a/cli/tests/test_restore_command.rs +++ b/cli/tests/test_restore_command.rs @@ -323,8 +323,8 @@ fn test_restore_restore_descendants() { [EOF] "); - // Check that "a", "b", and "ab" have their expected content by diffing them. - // "ab" must have kept its content. + // Check that "a", "b", and "ab" have their expected content by diffing + // them. "ab" must have kept its content. insta::assert_snapshot!(work_dir.run_jj(["diff", "--from=a", "--to=ab", "--git"]), @" diff --git a/file b/file index 7898192261..81bf396956 100644 diff --git a/cli/tests/test_run_command.rs b/cli/tests/test_run_command.rs index 2cb2a48bb28..820a1b1901e 100644 --- a/cli/tests/test_run_command.rs +++ b/cli/tests/test_run_command.rs @@ -48,8 +48,8 @@ fn test_run_simple() { ◆ zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz [EOF] "); - // `--tee touched.txt` creates a file in each working copy, so every commit's - // tree gets rewritten. + // `--tee touched.txt` creates a file in each working copy, so every + // commit's tree gets rewritten. let stdout = work_dir .run_jj(&[ "run", @@ -636,8 +636,9 @@ fn test_run_stops_after_first_failure() { work_dir.write_file("c.txt", "c"); work_dir.run_jj(&["commit", "-m", "C"]).success(); - // The counter lives outside every ephemeral working copy, so all invocations - // append to the same file and its byte length is the execution count. + // The counter lives outside every ephemeral working copy, so all + // invocations append to the same file and its byte length is the + // execution count. let counter = test_env.env_root().join("run-count.txt"); let counter_arg = counter.to_str().unwrap(); @@ -1615,7 +1616,8 @@ fn test_run_ignore_changes_does_not_rewrite() { let log_before = get_log_output(&work_dir); // --tee touched.txt writes a new file in each working copy. Without - // --ignore-changes this would amend the commits; with it nothing is rewritten. + // --ignore-changes this would amend the commits; with it nothing is + // rewritten. let output = work_dir .run_jj(&[ "run", @@ -1653,9 +1655,9 @@ fn test_run_ignore_changes_does_not_rewrite() { #[test] fn test_run_ignore_changes_does_not_leak_between_invocations() { // Mirrors test_run_pool_no_file_leak_between_invocations but run 1 uses - // --ignore-changes. The pool slot's tree_state is still updated by the snapshot - // during run 1, so run 2 correctly removes artifact.txt from the slot - // before checking out commit1. + // --ignore-changes. The pool slot's tree_state is still updated by the + // snapshot during run 1, so run 2 correctly removes artifact.txt from + // the slot before checking out commit1. let test_env = TestEnvironment::default(); test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); @@ -1664,9 +1666,10 @@ fn test_run_ignore_changes_does_not_leak_between_invocations() { work_dir.run_jj(&["commit", "-m", "commit1"]).success(); work_dir.run_jj(&["commit", "-m", "commit2"]).success(); - // Run 1 (--ignore-changes): writes artifact.txt in the pool slot for commit2 - // but does not amend any commit. The slot's tree_state must record - // artifact.txt so run 2 can remove it when checking out a different tree. + // Run 1 (--ignore-changes): writes artifact.txt in the pool slot for + // commit2 but does not amend any commit. The slot's tree_state must + // record artifact.txt so run 2 can remove it when checking out a + // different tree. let touch_cmd: &[&str] = if cfg!(windows) { &[ "run", @@ -1830,8 +1833,9 @@ fn test_run_passthrough() { " ); - // --passthrough passes the child's stdout/stderr directly through. The output - // appears in `jj run`'s own stdout/stderr (captured by the test harness). + // --passthrough passes the child's stdout/stderr directly through. The + // output appears in `jj run`'s own stdout/stderr (captured by the test + // harness). let jj_args: &[&str] = if cfg!(windows) { &[ "run", @@ -1936,9 +1940,9 @@ fn test_run_on_conflicted_commit() { [EOF] "); - // `jj run` over the conflicted commit used to panic. `--tee` writes a file in - // its working copy so the commit is actually rewritten, proving the conflict - // survives the rewrite instead of crashing. + // `jj run` over the conflicted commit used to panic. `--tee` writes a file + // in its working copy so the commit is actually rewritten, proving the + // conflict survives the rewrite instead of crashing. let output = work_dir.run_jj(&[ "run", "-r", diff --git a/cli/tests/test_split_command.rs b/cli/tests/test_split_command.rs index 9c9fd8c9a2e..37bd0c1b3a7 100644 --- a/cli/tests/test_split_command.rs +++ b/cli/tests/test_split_command.rs @@ -112,8 +112,8 @@ fn test_split_by_paths() -> TestResult { [EOF] "); - // The author dates of the new commits should be inherited from the commit being - // split. The committer dates should be newer. + // The author dates of the new commits should be inherited from the commit + // being split. The committer dates should be newer. insta::assert_snapshot!(get_recorded_dates(&work_dir, "@"), @" Author date: 2001-02-03 04:05:08.000 +07:00 Committer date: 2001-02-03 04:05:10.000 +07:00[EOF] @@ -617,7 +617,8 @@ fn test_split_parallel_with_descendants() -> TestResult { work_dir .run_jj(["commit", "-m", "Add file1 & file2"]) .success(); - // Second commit. This will be the child of the sibling commits after the split. + // Second commit. This will be the child of the sibling commits after the + // split. work_dir.write_file("file3", "baz\n"); work_dir.run_jj(["commit", "-m", "Add file3"]).success(); // Third commit. @@ -773,7 +774,8 @@ fn test_split_parallel_with_conflict() -> TestResult { [EOF] "); - // Create a conflict by splitting two consecutive lines into parallel commits. + // Create a conflict by splitting two consecutive lines into parallel + // commits. std::fs::write( diff_editor, ["write file\nline 1\nline 2.1\nline 3\n"].join("\0"), @@ -824,8 +826,8 @@ fn test_split_parallel_with_conflict() -> TestResult { line 3 "); - // The old commit shouldn't be conflicted, since it matches the selection from - // the editor. + // The old commit shouldn't be conflicted, since it matches the selection + // from the editor. insta::assert_snapshot!(work_dir.run_jj(["file", "show", "-r=@+-~@", "file"]), @" line 1 line 2.1 @@ -992,8 +994,8 @@ fn test_split_interactive_with_paths() -> TestResult { .join("\0"); std::fs::write(diff_editor, diff_script)?; - // Select file1 and file2 by args, then select file1 interactively via the diff - // script. + // Select file1 and file2 by args, then select file1 interactively via the + // diff script. let output = work_dir.run_jj(["split", "-i", "file1", "file2"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1060,8 +1062,9 @@ fn test_split_with_multiple_workspaces_same_working_copy() -> TestResult { secondary_dir .run_jj(["edit", "-r", "subject(first-commit)"]) .success(); - // Check the working-copy commit in each workspace in the log output. The "@" - // node in the graph indicates the current workspace's working-copy commit. + // Check the working-copy commit in each workspace in the log output. The + // "@" node in the graph indicates the current workspace's working-copy + // commit. insta::assert_snapshot!(get_workspace_log_output(&main_dir), @" @ qpvuntsmwlqt default@ second@ first-commit ◆ zzzzzzzzzzzz @@ -1117,8 +1120,9 @@ fn test_split_with_multiple_workspaces_different_working_copy() -> TestResult { main_dir .run_jj(["workspace", "add", "--name", "second", "../secondary"]) .success(); - // Check the working-copy commit in each workspace in the log output. The "@" - // node in the graph indicates the current workspace's working-copy commit. + // Check the working-copy commit in each workspace in the log output. The + // "@" node in the graph indicates the current workspace's working-copy + // commit. insta::assert_snapshot!(get_workspace_log_output(&main_dir), @" @ qpvuntsmwlqt default@ first-commit │ ○ pmmvwywvzvvn second@ @@ -1712,7 +1716,8 @@ fn test_split_with_editor_and_message_args() -> TestResult { ]) .success(); - // Verify editor was opened for the first commit with message from command line + // Verify editor was opened for the first commit with message from command + // line insta::assert_snapshot!( std::fs::read_to_string(test_env.env_root().join("editor1"))?, @r#" JJ: Enter a description for the selected changes. @@ -1725,7 +1730,8 @@ fn test_split_with_editor_and_message_args() -> TestResult { JJ: Lines starting with "JJ:" (like this one) will be removed. "#); - // Verify editor was opened for the second commit with the original description + // Verify editor was opened for the second commit with the original + // description insta::assert_snapshot!( std::fs::read_to_string(test_env.env_root().join("editor2"))?, @r#" JJ: Enter a description for the remaining changes. @@ -1799,7 +1805,8 @@ fn test_split_with_editor_and_empty_message() -> TestResult { JJ: JJ: Lines starting with "JJ:" (like this one) will be removed. "#); - // Verify editor was opened for the second commit with the original description + // Verify editor was opened for the second commit with the original + // description insta::assert_snapshot!( std::fs::read_to_string(test_env.env_root().join("editor2"))?, @r#" JJ: Enter a description for the remaining changes. @@ -1835,7 +1842,8 @@ fn test_split_with_editor_without_message() -> TestResult { .run_jj(["describe", "-m", "original description"]) .success(); - // --editor without -m should behave the same as without --editor (normal flow) + // --editor without -m should behave the same as without --editor (normal + // flow) std::fs::write( &edit_script, [ diff --git a/cli/tests/test_squash_command.rs b/cli/tests/test_squash_command.rs index 63bbcb72e26..605130f9697 100644 --- a/cli/tests/test_squash_command.rs +++ b/cli/tests/test_squash_command.rs @@ -98,8 +98,8 @@ fn test_squash() { [EOF] "); - // Cannot squash a merge commit (because it's unclear which parent it should go - // into) + // Cannot squash a merge commit (because it's unclear which parent it should + // go into) work_dir.run_jj(["op", "restore", &setup_opid]).success(); work_dir.run_jj(["edit", "b"]).success(); work_dir.run_jj(["new"]).success(); @@ -195,8 +195,8 @@ fn test_squash_partial() -> TestResult { let start_op_id = work_dir.current_operation_id(); - // If we don't make any changes in the diff-editor, the whole change is moved - // into the parent + // If we don't make any changes in the diff-editor, the whole change is + // moved into the parent std::fs::write(&edit_script, "dump JJ-INSTRUCTIONS instrs")?; let output = work_dir.run_jj(["squash", "-r", "b", "-i"]); insta::assert_snapshot!(output, @r" @@ -323,7 +323,8 @@ fn test_squash_partial() -> TestResult { [EOF] "); - // We get a warning if we pass a positional argument that looks like a revset + // We get a warning if we pass a positional argument that looks like a + // revset work_dir.run_jj(["op", "restore", &start_op_id]).success(); let output = work_dir.run_jj(["squash", "b"]); insta::assert_snapshot!(output, @r#" @@ -512,8 +513,8 @@ fn test_squash_from_to() { // |/ // A // - // When moving changes between e.g. C and F, we should not get unrelated changes - // from B and D. + // When moving changes between e.g. C and F, we should not get unrelated + // changes from B and D. work_dir .run_jj(["bookmark", "create", "-r@", "a"]) .success(); @@ -621,8 +622,9 @@ fn test_squash_from_to() { ◆ 000000000000 (empty) [EOF] "); - // The change from the source has been applied (the file contents were already - // "f", as is typically the case when moving changes from an ancestor) + // The change from the source has been applied (the file contents were + // already "f", as is typically the case when moving changes from an + // ancestor) let output = work_dir.run_jj(["file", "show", "file2"]); insta::assert_snapshot!(output, @" f @@ -735,7 +737,8 @@ fn test_squash_from_to_partial() -> TestResult { "); let setup_opid = work_dir.current_operation_id(); - // If we don't make any changes in the diff-editor, the whole change is moved + // If we don't make any changes in the diff-editor, the whole change is + // moved let output = work_dir.run_jj(["squash", "-i", "--from", "c"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -849,7 +852,8 @@ fn test_squash_from_to_partial() -> TestResult { [EOF] "); - // Can squash only part of the change from a descendant in non-interactive mode + // Can squash only part of the change from a descendant in non-interactive + // mode work_dir.run_jj(["op", "restore", &setup_opid]).success(); // Clear the script so we know it won't be used std::fs::write(&edit_script, "")?; @@ -1203,7 +1207,8 @@ fn test_squash_from_multiple_partial() { f [EOF] "); - // The selected changes from the sources have been applied to the destination + // The selected changes from the sources have been applied to the + // destination let output = work_dir.run_jj(["file", "show", "-r=e", "file1"]); insta::assert_snapshot!(output, @" f @@ -1342,8 +1347,8 @@ fn test_squash_description() -> TestResult { [EOF] "); - // If the destination description is non-empty and the source's description is - // empty, the resulting description is from the destination + // If the destination description is non-empty and the source's description + // is empty, the resulting description is from the destination work_dir.run_jj(["op", "restore", &setup_opid1]).success(); work_dir .run_jj(["describe", "@-", "-m", "destination"]) @@ -1363,7 +1368,8 @@ fn test_squash_description() -> TestResult { [EOF] "); - // If both descriptions were non-empty, we get asked for a combined description + // If both descriptions were non-empty, we get asked for a combined + // description work_dir.run_jj(["op", "restore", &setup_opid2]).success(); work_dir.run_jj(["describe", "-m", "source"]).success(); let setup_opid3 = work_dir.current_operation_id(); @@ -1393,8 +1399,8 @@ fn test_squash_description() -> TestResult { JJ: Lines starting with "JJ:" (like this one) will be removed. "#); - // An explicit description on the command-line overrides prevents launching an - // editor + // An explicit description on the command-line overrides prevents launching + // an editor work_dir.run_jj(["op", "restore", &setup_opid3]).success(); work_dir.run_jj(["squash", "-m", "custom"]).success(); insta::assert_snapshot!(get_description(&work_dir, "@-"), @" @@ -1421,8 +1427,8 @@ fn test_squash_description() -> TestResult { [EOF] "); - // If the source's *content* doesn't become empty, then the source remains and - // both descriptions are unchanged + // If the source's *content* doesn't become empty, then the source remains + // and both descriptions are unchanged work_dir.run_jj(["op", "restore", &setup_opid3]).success(); work_dir.run_jj(["squash", "file1"]).success(); insta::assert_snapshot!(get_description(&work_dir, "@-"), @" @@ -1504,9 +1510,9 @@ fn test_squash_description() -> TestResult { JJ: Lines starting with "JJ:" (like this one) will be removed. "#); - // If the destination description is non-empty and the source's description is - // empty, the resulting description is from the destination, with additional - // trailers if defined in the commit_trailers template + // If the destination description is non-empty and the source's description + // is empty, the resulting description is from the destination, with + // additional trailers if defined in the commit_trailers template work_dir.run_jj(["op", "restore", &setup_opid3]).success(); work_dir.run_jj(["describe", "-m", ""]).success(); insta::assert_snapshot!(get_log_output_with_description(&work_dir), @" @@ -2455,8 +2461,8 @@ fn test_squash_with_editor_combine_messages() -> TestResult { work_dir.run_jj(["new", "-m", "source"]).success(); work_dir.write_file("file1", "b\n"); - // Both source and destination have descriptions, so editor will open to combine - // them; the --editor was superfluous. + // Both source and destination have descriptions, so editor will open to + // combine them; the --editor was superfluous. std::fs::write( &edit_script, ["dump editor", "write\nfinal description from editor"].join("\0"), diff --git a/cli/tests/test_status_command.rs b/cli/tests/test_status_command.rs index 32960068d89..82f92161c7b 100644 --- a/cli/tests/test_status_command.rs +++ b/cli/tests/test_status_command.rs @@ -56,8 +56,8 @@ fn test_status_merge() { work_dir.write_file("file", "right"); work_dir.run_jj(["new", "left", "@"]).success(); - // The output should mention each parent, and the diff should be empty (compared - // to the auto-merged parents) + // The output should mention each parent, and the diff should be empty + // (compared to the auto-merged parents) let output = work_dir.run_jj(["status"]); insta::assert_snapshot!(output, @" The working copy has no changes. @@ -109,7 +109,8 @@ fn test_status_filtered() { [EOF] "); - // The diff summary should preserve ANSI color codes instead of sanitizing them. + // The diff summary should preserve ANSI color codes instead of sanitizing + // them. let output = work_dir.run_jj(["status", "file_1", "--color=always"]); insta::assert_snapshot!(output, @" Working copy changes: @@ -283,8 +284,8 @@ fn test_status_display_relevant_working_commit_conflict_hints() { work_dir .run_jj(["new", "--message", "boom", "(@-)+"]) .success(); - // Adding more descendants to ensure we correctly find the root ancestors with - // conflicts, not just the parents. + // Adding more descendants to ensure we correctly find the root ancestors + // with conflicts, not just the parents. work_dir.run_jj(["new", "--message", "boom-cont"]).success(); work_dir .run_jj(["new", "--message", "boom-cont-2"]) @@ -454,8 +455,8 @@ fn test_status_display_relevant_working_commit_conflict_hints() { [EOF] "); - // Step back to all the way to `root()+` so that wc has no conflict, even though - // there is a conflict later in the tree. So that we can confirm + // Step back to all the way to `root()+` so that wc has no conflict, even + // though there is a conflict later in the tree. So that we can confirm // our hinting logic doesn't get confused. work_dir.run_jj(["edit", "root()+"]).success(); let output = work_dir.run_jj(["log", "-r", "::"]); @@ -499,8 +500,8 @@ fn test_status_simplify_conflict_sides() { test_env.run_jj_in(".", ["git", "init", "repo"]).success(); let work_dir = test_env.work_dir("repo"); - // Creates a 4-sided conflict, with fileA and fileB having different conflicts: - // fileA: A - B + C - B + B - B + B + // Creates a 4-sided conflict, with fileA and fileB having different + // conflicts: fileA: A - B + C - B + B - B + B // fileB: A - A + A - A + B - C + D create_commit_with_files( &work_dir, diff --git a/cli/tests/test_util_command.rs b/cli/tests/test_util_command.rs index 7f4e5bdfb48..6421184f919 100644 --- a/cli/tests/test_util_command.rs +++ b/cli/tests/test_util_command.rs @@ -126,7 +126,8 @@ fn test_shell_completions() { #[track_caller] fn test(shell: &str) { let test_env = TestEnvironment::default(); - // Use the local backend because GitBackend::gc() depends on the git CLI. + // Use the local backend because GitBackend::gc() depends on the git + // CLI. let output = test_env .run_jj_in(".", ["util", "completion", shell]) .success(); diff --git a/cli/tests/test_working_copy.rs b/cli/tests/test_working_copy.rs index 2020822aa08..b34c77c0f12 100644 --- a/cli/tests/test_working_copy.rs +++ b/cli/tests/test_working_copy.rs @@ -406,8 +406,8 @@ fn test_conflict_marker_length_stored_in_working_copy() -> TestResult { >>>>>>>>>>> conflict 1 of 1 ends "#); - // The timestamps in the `jj debug local-working-copy` output change, so we want - // to remove them before asserting the snapshot + // The timestamps in the `jj debug local-working-copy` output change, so we + // want to remove them before asserting the snapshot let timestamp_regex = Regex::new(r"\b\d{10,}\b")?; let redact_output = |output: String| { let output = timestamp_regex.replace_all(&output, ""); @@ -541,8 +541,8 @@ fn test_submodule_ignored() { .success(); let work_dir = test_env.work_dir("repo"); - // There's no particular reason to run this with jj util exec, it's just that - // the infra makes it easier to run this way. + // There's no particular reason to run this with jj util exec, it's just + // that the infra makes it easier to run this way. let output = work_dir.run_jj([ "util", "exec", @@ -590,8 +590,8 @@ fn test_submodule_ignored() { // Switch to a historical commit before the submodule was checked in. work_dir.run_jj(["prev"]).success(); - // jj new (or equivalently prev) should always leave you with an empty working - // copy. + // jj new (or equivalently prev) should always leave you with an empty + // working copy. let output = work_dir.run_jj(["diff", "--summary"]); insta::assert_snapshot!(output, @""); } diff --git a/cli/tests/test_workspaces.rs b/cli/tests/test_workspaces.rs index be7256dea40..f8c47f84fd1 100644 --- a/cli/tests/test_workspaces.rs +++ b/cli/tests/test_workspaces.rs @@ -73,8 +73,9 @@ fn test_workspaces_add_second_and_third_workspace() { [EOF] "#); - // Can see the working-copy commit in each workspace in the log output. The "@" - // node in the graph indicates the current workspace's working-copy commit. + // Can see the working-copy commit in each workspace in the log output. The + // "@" node in the graph indicates the current workspace's working-copy + // commit. insta::assert_snapshot!(get_log_output(&main_dir), @r#" @ 504e3d8c1bcd default@ │ ○ bcc858e1d93f second@ @@ -270,7 +271,8 @@ fn test_workspaces_add_second_workspace_on_merge() { .run_jj(["workspace", "add", "--name", "second", "../secondary"]) .success(); - // The new workspace's working-copy commit shares all parents with the old one. + // The new workspace's working-copy commit shares all parents with the old + // one. insta::assert_snapshot!(get_log_output(&main_dir), @r#" @ 46ed31b61ce9 default@ "merge" ├─╮ @@ -436,8 +438,9 @@ fn test_workspaces_add_workspace_at_revision() { [EOF] "#); - // Can see the working-copy commit in each workspace in the log output. The "@" - // node in the graph indicates the current workspace's working-copy commit. + // Can see the working-copy commit in each workspace in the log output. The + // "@" node in the graph indicates the current workspace's working-copy + // commit. insta::assert_snapshot!(get_log_output(&main_dir), @r#" @ 5ac9178da8b2 default@ ○ a47d8a593529 "second" @@ -715,8 +718,8 @@ fn test_workspaces_conflicting_edits() { // Make changes in both working copies main_dir.write_file("file", "changed in main\n"); secondary_dir.write_file("file", "changed in second\n"); - // Squash the changes from the main workspace into the initial commit (before - // running any command in the secondary workspace + // Squash the changes from the main workspace into the initial commit + // (before running any command in the secondary workspace let output = main_dir.run_jj(["squash"]); insta::assert_snapshot!(output, @r" ------- stderr ------- @@ -1024,9 +1027,10 @@ fn test_workspaces_updated_by_other_with_changes_in_working_copy_automatic() { [EOF] "); - // We get divergence between the newly described commit and the commit created - // by snapshotting (the reconciliation happened to point secondary@ to the child - // of the squashed commit rather than the snapshot commit). + // We get divergence between the newly described commit and the commit + // created by snapshotting (the reconciliation happened to point + // secondary@ to the child of the squashed commit rather than the + // snapshot commit). insta::assert_snapshot!(get_log_output(&secondary_dir), @r#" @ c38323e3e6f3 secondary@ (divergent) "modified" @@ -1077,8 +1081,8 @@ fn test_workspaces_current_op_discarded_by_other(automatic: bool) { secondary_dir.remove_file("deleted"); secondary_dir.write_file("added", "secondary\n"); - // Create an op by abandoning the parent commit. Importantly, that commit also - // changes the target tree in the secondary workspace. + // Create an op by abandoning the parent commit. Importantly, that commit + // also changes the target tree in the secondary workspace. main_dir.run_jj(["abandon", "@-"]).success(); let output = main_dir.run_jj([ @@ -1305,8 +1309,8 @@ fn test_workspaces_update_stale_snapshot() { // Record new operation in one workspace. main_dir.run_jj(["new"]).success(); - // Snapshot the other working copy, which unfortunately results in concurrent - // operations, but should be resolved cleanly. + // Snapshot the other working copy, which unfortunately results in + // concurrent operations, but should be resolved cleanly. secondary_dir.write_file("file", "changed in second\n"); let output = secondary_dir.run_jj(["workspace", "update-stale"]); insta::assert_snapshot!(output, @r" @@ -1406,9 +1410,9 @@ fn test_colocated_workspace_update_stale() { [exit status: 1] "); - // Before the fix, this would fail with the same "working copy is stale" error - // because the colocated repo reload logic would reload to HEAD before - // snapshotting, breaking the recovery. + // Before the fix, this would fail with the same "working copy is stale" + // error because the colocated repo reload logic would reload to HEAD + // before snapshotting, breaking the recovery. let output = main_dir.run_jj(["workspace", "update-stale"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1476,8 +1480,8 @@ fn test_workspaces_forget() { [EOF] "); - // After forgetting the default, secondary root is still recorded, default no - // longer exists + // After forgetting the default, secondary root is still recorded, default + // no longer exists let output = main_dir.run_jj(["workspace", "root", "--name", "secondary"]); insta::assert_snapshot!(output, @" $TEST_ENV/secondary @@ -1492,9 +1496,9 @@ fn test_workspaces_forget() { "); // The old working copy doesn't get an "@" in the log output - // TODO: It seems useful to still have the "secondary@" marker here even though - // there's only one workspace. We should show it when the command is not run - // from that workspace. + // TODO: It seems useful to still have the "secondary@" marker here even + // though there's only one workspace. We should show it when the command + // is not run from that workspace. insta::assert_snapshot!(get_log_output(&main_dir), @" ○ 31da14559558 ○ 006bd1130b84 @@ -1523,7 +1527,8 @@ fn test_workspaces_forget() { // Add a third workspace... main_dir.run_jj(["workspace", "add", "../third"]).success(); - // ... and then forget it, a non-existent one, and the secondary workspace too + // ... and then forget it, a non-existent one, and the secondary workspace + // too let output = main_dir.run_jj(["workspace", "forget", "secondary", "nonexistent", "third"]); insta::assert_snapshot!(output, @" ------- stderr ------- @@ -1603,7 +1608,8 @@ fn test_workspaces_forget_multi_transaction() { [EOF] "); - // the op log should have the multiple valid workspaces forgotten in a single tx + // the op log should have the multiple valid workspaces forgotten in a + // single tx let output = main_dir.run_jj(["op", "log", "--limit", "1"]); insta::assert_snapshot!(output, @" @ da3075edb24f test-username@host.example.com default@ 2001-02-03 04:05:12.000 +07:00 - 2001-02-03 04:05:12.000 +07:00 @@ -1641,7 +1647,8 @@ fn test_workspaces_forget_abandon_commits() { let fourth_dir = test_env.work_dir("fourth"); fourth_dir.run_jj(["edit", "second@"]).success(); - // there should be four workspaces, three of which are at the same empty commit + // there should be four workspaces, three of which are at the same empty + // commit let output = main_dir.run_jj(["workspace", "list"]); insta::assert_snapshot!(output.normalize_backslash(), @" default: . qpvuntsm 006bd113 (no description set) @@ -1670,8 +1677,8 @@ fn test_workspaces_forget_abandon_commits() { [EOF] "); - // delete the second workspace (should not abandon commit since other workspaces - // still have commit checked out) + // delete the second workspace (should not abandon commit since other + // workspaces still have commit checked out) main_dir.run_jj(["workspace", "forget", "second"]).success(); insta::assert_snapshot!(get_log_output(&main_dir), @" ○ 94f41578a9e1 fourth@ third@ diff --git a/core/proc-macros/src/content_hash.rs b/core/proc-macros/src/content_hash.rs index 2123d143661..68798b5e2c5 100644 --- a/core/proc-macros/src/content_hash.rs +++ b/core/proc-macros/src/content_hash.rs @@ -114,7 +114,8 @@ fn enum_bindings_with_type<'a>(fields: impl IntoIterator) -> V .into_iter() .enumerate() .map(|(i, f)| { - // If the field is named, use the name, otherwise generate a placeholder name. + // If the field is named, use the name, otherwise generate a + // placeholder name. ( f.ty.clone(), f.ident.clone().unwrap_or(format_ident!("field_{}", i)), diff --git a/core/src/dag_walk.rs b/core/src/dag_walk.rs index ccdfebc5f3b..083e910e7c8 100644 --- a/core/src/dag_walk.rs +++ b/core/src/dag_walk.rs @@ -213,9 +213,9 @@ where NI: IntoIterator>, { let mut heads: HashSet = start.into_iter().try_collect()?; - // Do a BFS until we have only one item left in the frontier. That frontier must - // have originated from one of the heads, and since there can't be cycles, - // it won't be able to eliminate any other heads. + // Do a BFS until we have only one item left in the frontier. That frontier + // must have originated from one of the heads, and since there can't be + // cycles, it won't be able to eliminate any other heads. let mut frontier: Vec = heads.iter().cloned().collect(); let mut visited: HashSet = heads.iter().map(&id_fn).collect(); let mut root_reached = false; diff --git a/core/src/dag_walk_async.rs b/core/src/dag_walk_async.rs index 670e4a7652c..b27d9a82ca5 100644 --- a/core/src/dag_walk_async.rs +++ b/core/src/dag_walk_async.rs @@ -490,9 +490,9 @@ where NI: IntoIterator, { let mut heads: HashSet = start.into_iter().collect(); - // Do a BFS until we have only one item left in the frontier. That frontier must - // have originated from one of the heads, and since there can't be cycles, - // it won't be able to eliminate any other heads. + // Do a BFS until we have only one item left in the frontier. That frontier + // must have originated from one of the heads, and since there can't be + // cycles, it won't be able to eliminate any other heads. let mut frontier: Vec = heads.iter().cloned().collect(); let mut visited: HashSet = heads.iter().map(&id_fn).collect(); let mut root_reached = false; @@ -917,8 +917,8 @@ mod tests { .unwrap(); assert_eq!(common, vec!['E', 'D', 'C', 'B', 'a']); - // The root node 'a' is visited before 'C'. If the graph were split there, - // the branch 'C->B->a' would be orphaned. + // The root node 'a' is visited before 'C'. If the graph were split + // there, the branch 'C->B->a' would be orphaned. let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('E')], id_fn, neighbors_fn, cycle_fn) .try_collect() .block_on() @@ -1052,8 +1052,8 @@ mod tests { .unwrap(); assert_eq!(common, vec!['G', 'F', 'E', 'D', 'c', 'B', 'A']); - // Iterator can be lazy for linear chunks. The node 'c' is visited before 'D', - // but it will be processed lazily. + // Iterator can be lazy for linear chunks. The node 'c' is visited + // before 'D', but it will be processed lazily. let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied()); let mut inner_iter = TopoOrderReverseLazyInner::empty(); inner_iter.extend([Ok('G')]); @@ -1388,9 +1388,9 @@ mod tests { #[test] fn test_closest_common_nodes_tricky() { - // Test this case where A is the shortest distance away, but we still want the - // result to be B because A is an ancestor of B. In other words, we want - // to minimize the longest distance. + // Test this case where A is the shortest distance away, but we still + // want the result to be B because A is an ancestor of B. In + // other words, we want to minimize the longest distance. // // E H // |\ /| @@ -1420,9 +1420,9 @@ mod tests { #[test] fn test_closest_common_nodes_tricky_ancestor() { - // Find the clostest common ancestor between B and F. It should be B because - // it's even an ancestor of F, but we used to find A because the path to it - // from F is shorter (via E). + // Find the clostest common ancestor between B and F. It should be B + // because it's even an ancestor of F, but we used to find A + // because the path to it from F is shorter (via E). // // F // |\ @@ -1451,8 +1451,8 @@ mod tests { #[test] fn test_closest_common_nodes_tricky_ancestor_with_bad_heuristic() { - // Find the clostest common ancestor between D and A. It should be D because - // it's even an ancestor of A. + // Find the clostest common ancestor between D and A. It should be D + // because it's even an ancestor of A. // // A // |\ @@ -1505,9 +1505,10 @@ mod tests { #[test] fn test_closest_common_nodes_many_paths() { - // One side has very many possible paths due to repeated forking and merging. We - // must not walk the exponential number of paths between A and MN when finding - // common ancestors between MN and B. + // One side has very many possible paths due to repeated forking and + // merging. We must not walk the exponential number of paths + // between A and MN when finding common ancestors between MN and + // B. // // MN // |\ @@ -1559,8 +1560,8 @@ mod tests { #[test] fn test_closest_common_nodes_simple_with_bad_heuristic() { - // We still find the right common ancestor between C and A when given a bad - // heuristic. + // We still find the right common ancestor between C and A when given a + // bad heuristic. // // C A // |/ @@ -1583,8 +1584,8 @@ mod tests { #[test] fn test_closest_common_nodes_ancestor_with_bad_heuristic() { - // We still find the right common ancestor between A and B when given a bad - // heuristic. + // We still find the right common ancestor between A and B when given a + // bad heuristic. // // A // | diff --git a/core/src/diff.rs b/core/src/diff.rs index dc72fbd8b6d..efc0741d2b2 100644 --- a/core/src/diff.rs +++ b/core/src/diff.rs @@ -391,8 +391,9 @@ fn find_lcs(input: &[usize]) -> Vec<(usize, usize)> { if len > global_longest { global_longest = len; global_longest_right_pos = right_pos; - // If this is the longest chain globally so far, we cannot find a - // longer one by using a previous value, so break early. + // If this is the longest chain globally so far, we + // cannot find a longer one by + // using a previous value, so break early. break; } } @@ -473,13 +474,14 @@ fn collect_unchanged_words_lcs( let left_histogram = Histogram::calculate(left, comp, max_occurrences); let left_count_to_entries = left_histogram.build_count_to_entries(); if *left_count_to_entries.keys().next().unwrap() > max_occurrences { - // If there are very many occurrences of all words, then we just give up. + // If there are very many occurrences of all words, then we just give + // up. return; } let right_histogram = Histogram::calculate(right, comp, max_occurrences); - // Look for words with few occurrences in `left` (could equally well have picked - // `right`?). If any of them also occur in `right`, then we add the words to - // the LCS. + // Look for words with few occurrences in `left` (could equally well have + // picked `right`?). If any of them also occur in `right`, then we add + // the words to the LCS. let Some(uncommon_shared_word_positions) = left_count_to_entries.values().find_map(|left_entries| { let mut both_positions = left_entries @@ -669,7 +671,8 @@ impl<'input> ContentDiff<'input> { // found ranges with the ranges in the diff. [first_other_source, tail_other_sources @ ..] => { let mut unchanged_regions = Vec::new(); - // Add an empty range at the start to make life easier for hunks(). + // Add an empty range at the start to make life easier for + // hunks(). unchanged_regions.push(UnchangedRange { base: 0..0, others: smallvec![0..0; other_inputs.len()], @@ -721,7 +724,8 @@ impl<'input> ContentDiff<'input> { }, )); } - // Add an empty range at the end to make life easier for hunks(). + // Add an empty range at the end to make life easier for + // hunks(). unchanged_regions.push(UnchangedRange { base: base_input.len()..base_input.len(), others: other_inputs @@ -809,10 +813,10 @@ impl<'input> ContentDiff<'input> { let mut new_unchanged_ranges = vec![self.unchanged_regions[0].clone()]; for window in self.unchanged_regions.windows(2) { let [previous, current]: &[_; 2] = window.try_into().unwrap(); - // For the changed region between the previous region and the current one, - // create a new Diff instance. Then adjust the start positions and - // offsets to be valid in the context of the larger Diff instance - // (`self`). + // For the changed region between the previous region and the + // current one, create a new Diff instance. Then adjust + // the start positions and offsets to be valid in the + // context of the larger Diff instance (`self`). let refined_diff = ContentDiff::for_tokenizer( self.hunk_between(previous, current), &tokenizer, @@ -1027,7 +1031,8 @@ mod tests { use super::*; // Extracted to a function because type inference is ambiguous due to - // `impl PartialEq for std::ops::Range` + // `impl PartialEq for + // std::ops::Range` fn no_ranges() -> Vec> { vec![] } @@ -1220,8 +1225,8 @@ mod tests { #[test] fn test_unchanged_ranges_non_unique_removed() { - // We used to consider the first two "a" in the first input to match the two - // "a"s in the second input. We no longer do. + // We used to consider the first two "a" in the first input to match the + // two "a"s in the second input. We no longer do. assert_eq!( unchanged_ranges( (b"a a a a", &[0..1, 2..3, 4..5, 6..7]), @@ -1254,8 +1259,8 @@ mod tests { #[test] fn test_unchanged_ranges_non_unique_added() { - // We used to consider the first two "a" in the first input to match the two - // "a"s in the second input. We no longer do. + // We used to consider the first two "a" in the first input to match the + // two "a"s in the second input. We no longer do. assert_eq!( unchanged_ranges( (b"a b a c", &[0..1, 2..3, 4..5, 6..7]), @@ -1595,11 +1600,13 @@ mod tests { #[test] fn test_diff_real_case_write_fmt() { - // This is from src/ui.rs in commit f44d246e3f88 in this repo. It highlights the - // need for recursion into the range at the end: after splitting at "Arguments" - // and "formatter", the region at the end has the unique words "write_fmt" - // and "fmt", but we forgot to recurse into that region, so we ended up - // saying that "write_fmt(fmt).unwrap()" was replaced by b"write_fmt(fmt)". + // This is from src/ui.rs in commit f44d246e3f88 in this repo. It + // highlights the need for recursion into the range at the end: + // after splitting at "Arguments" and "formatter", the region at + // the end has the unique words "write_fmt" and "fmt", but we + // forgot to recurse into that region, so we ended up + // saying that "write_fmt(fmt).unwrap()" was replaced by + // b"write_fmt(fmt)". #[rustfmt::skip] assert_eq!( diff([ diff --git a/core/src/file_util.rs b/core/src/file_util.rs index 44813292c4f..41dd1f33131 100644 --- a/core/src/file_util.rs +++ b/core/src/file_util.rs @@ -344,7 +344,8 @@ mod platform { /// Whether changing executable bits is permitted on the filesystem of this /// directory, and whether attempting to flip one has an observable effect. pub fn check_executable_bit_support(path: impl AsRef) -> io::Result { - // Get current permissions and try to flip just the user's executable bit. + // Get current permissions and try to flip just the user's executable + // bit. let temp_file = tempfile::tempfile_in(path)?; let old_mode = temp_file.metadata()?.permissions().mode(); let new_mode = old_mode ^ 0o100; @@ -443,9 +444,10 @@ mod platform { // same way it does (read access, plus `FILE_FLAG_BACKUP_SEMANTICS` so a // directory can be opened too), but add `FILE_FLAG_OPEN_REPARSE_POINT` // so the handle refers to the symlink itself instead of its target. - // This matches the Unix implementation, which uses `symlink_metadata()`. - // The reparse-point flag is ignored for paths that aren't reparse - // points, so regular files and hard links are unaffected. + // This matches the Unix implementation, which uses + // `symlink_metadata()`. The reparse-point flag is ignored for + // paths that aren't reparse points, so regular files and hard + // links are unaffected. const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; let file = OpenOptions::new() @@ -767,8 +769,8 @@ mod tests { FileIdentity::from_symlink_path(&symlink_path)? ); // symlink should be different from the target directory. The - // `File::open()` follow-through is not checked here because File::open() - // can't open a directory on Windows. + // `File::open()` follow-through is not checked here because + // File::open() can't open a directory on Windows. assert_ne!( FileIdentity::from_symlink_path(&dir_path)?, FileIdentity::from_symlink_path(&symlink_path)? diff --git a/core/src/graph.rs b/core/src/graph.rs index 03d778ea575..34fb4b1ea78 100644 --- a/core/src/graph.rs +++ b/core/src/graph.rs @@ -247,7 +247,8 @@ where .blocked_ids .iter() .map(|id| { - // Borrow from self.nodes so self.blocked_ids can be mutated later + // Borrow from self.nodes so self.blocked_ids can be mutated + // later let (id, _) = self.nodes.get_key_value(id).unwrap(); id }) @@ -266,10 +267,11 @@ where .expect("blocking head should exist"); let new_head_id = self.new_head_ids.remove(index).unwrap(); - // Unmark ancestors of the selected head so they won't contribute to future - // new-head resolution within the newly-unblocked sub graph. The sub graph - // can have many fork points, and the corresponding heads should be picked in - // the fork-point order, not in the head appearance order. + // Unmark ancestors of the selected head so they won't contribute to + // future new-head resolution within the newly-unblocked sub + // graph. The sub graph can have many fork points, and the + // corresponding heads should be picked in the fork-point order, + // not in the head appearance order. to_visit.push(&new_head_id); visited.remove(&new_head_id); while let Some(id) = to_visit.pop() { @@ -561,8 +563,8 @@ mod tests { ├─╯ A "); - // D-A is found earlier than B-A, but B is emitted first because it belongs to - // the emitting branch. + // D-A is found earlier than B-A, but B is emitted first because it + // belongs to the emitting branch. insta::assert_snapshot!(format_graph(topo_grouped(graph.iter().cloned())), @" E direct(B) │ @@ -980,8 +982,8 @@ mod tests { │ ~ "); - // K-E,J is resolved without queuing new heads. Then, G::H, F::I, B::C, and - // A::D. + // K-E,J is resolved without queuing new heads. Then, G::H, F::I, B::C, + // and A::D. insta::assert_snapshot!(format_graph(topo_grouped(graph.iter().cloned())), @" K direct(E), direct(J) ├─╮ @@ -1046,8 +1048,8 @@ mod tests { │ ~ "); - // K-I,J is resolved without queuing new heads. Then, D::F, B::H, C::E, and - // A::G. + // K-I,J is resolved without queuing new heads. Then, D::F, B::H, C::E, + // and A::G. insta::assert_snapshot!(format_graph(topo_grouped(graph.iter().cloned())), @" K direct(I), direct(J) ├─╮ @@ -1902,9 +1904,9 @@ mod tests { A "); - // A is queued once by C-A because B isn't populated at this point. Since - // B is the second parent, B-A is processed next and A is queued again. So - // one of them in the queue has to be ignored. + // A is queued once by C-A because B isn't populated at this point. + // Since B is the second parent, B-A is processed next and A is + // queued again. So one of them in the queue has to be ignored. let mut iter = topo_grouped(graph.iter().cloned()); assert_eq!(iter.next().unwrap()?.0, 'C'); assert_eq!(iter.next().unwrap()?.0, 'B'); @@ -1915,8 +1917,8 @@ mod tests { #[test] fn test_topo_grouped_duplicated_edges() -> TestResult { - // The graph shouldn't have duplicated parent->child edges, but topo-grouped - // iterator can handle it anyway. + // The graph shouldn't have duplicated parent->child edges, but + // topo-grouped iterator can handle it anyway. let graph = [('B', vec![direct('A'), direct('A')]), ('A', vec![])].map(Ok); insta::assert_snapshot!(format_graph(graph.iter().cloned()), @" B direct(A), direct(A) diff --git a/core/src/matchers.rs b/core/src/matchers.rs index a23ccb56ee7..90e3444cb8b 100644 --- a/core/src/matchers.rs +++ b/core/src/matchers.rs @@ -761,8 +761,8 @@ mod tests { m.visit(RepoPath::root()), Visit::sets(hashset! {repo_path_component_buf("foo")}, hashset! {}) ); - // Inside parent directory "foo/", both subdirectory "bar" and file "bar" may - // match + // Inside parent directory "foo/", both subdirectory "bar" and file + // "bar" may match assert_eq!( m.visit(repo_path("foo")), Visit::sets( @@ -770,12 +770,13 @@ mod tests { hashset! {repo_path_component_buf("bar")} ) ); - // Inside a directory that matches the prefix, everything matches recursively + // Inside a directory that matches the prefix, everything matches + // recursively assert_eq!(m.visit(repo_path("foo/bar")), Visit::AllRecursively); // Same thing in subdirectories of the prefix assert_eq!(m.visit(repo_path("foo/bar/baz")), Visit::AllRecursively); - // Nothing in directories that are siblings of the prefix can match, so don't - // visit + // Nothing in directories that are siblings of the prefix can match, so + // don't visit assert_eq!(m.visit(repo_path("bar")), Visit::Nothing); } @@ -796,7 +797,8 @@ mod tests { hashset! {repo_path_component_buf("foo")} ) ); - // Inside a directory that matches the prefix, everything matches recursively + // Inside a directory that matches the prefix, everything matches + // recursively assert_eq!(m.visit(repo_path("foo")), Visit::AllRecursively); // Same thing in subdirectories of the prefix assert_eq!(m.visit(repo_path("foo/bar/baz")), Visit::AllRecursively); diff --git a/core/src/merge.rs b/core/src/merge.rs index 0716d3124c0..f58e5be93d5 100644 --- a/core/src/merge.rs +++ b/core/src/merge.rs @@ -146,9 +146,9 @@ where }; } - // Number of occurrences of each value, with positive indexes counted as +1 and - // negative as -1, thereby letting positive and negative terms with the same - // value (i.e. key in the map) cancel each other. + // Number of occurrences of each value, with positive indexes counted as +1 + // and negative as -1, thereby letting positive and negative terms with + // the same value (i.e. key in the map) cancel each other. let mut counts: HashMap<&T, i32> = HashMap::new(); for (value, n) in zip(values, [1, -1].into_iter().cycle()) { counts.entry(value).and_modify(|e| *e += n).or_insert(n); @@ -158,7 +158,8 @@ where // canceled out. counts.retain(|_, count| *count != 0); if counts.len() == 1 { - // If there is a single value with a count of 1 left, then that is the result. + // If there is a single value with a count of 1 left, then that is the + // result. let (value, count) = counts.into_iter().next().unwrap(); assert_eq!(count, 1); Some(value) @@ -196,8 +197,8 @@ impl ContentHash for Merge { impl Debug for Merge { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { - // Format like an enum with two variants to make it less verbose in the common - // case of a resolved state. + // Format like an enum with two variants to make it less verbose in the + // common case of a resolved state. if let Some(value) = self.as_resolved() { f.debug_tuple("Resolved").field(value).finish() } else { @@ -381,8 +382,8 @@ impl Merge { if let Some((remove_index, _)) = remove_indices .find(|&(_, original_remove_index)| &self.values[*original_remove_index] == add) { - // Align the current "add" value to the `remove_index/2`-th diff, then - // delete the diff pair. + // Align the current "add" value to the `remove_index/2`-th + // diff, then delete the diff pair. simplified_to_original_indices.swap(remove_index + 1, add_index); simplified_to_original_indices.drain(remove_index..remove_index + 2); } else { @@ -696,8 +697,8 @@ impl Merge> { let mut outer_values = self.values.into_iter(); let mut result = outer_values.next().unwrap(); while let Some(mut remove) = outer_values.next() { - // Add removes reversed, and with the first element moved last, so we preserve - // the diffs + // Add removes reversed, and with the first element moved last, so + // we preserve the diffs remove.values.rotate_left(1); for i in 0..remove.values.len() / 2 { remove.values.swap(i * 2, i * 2 + 1); @@ -1118,8 +1119,8 @@ mod tests { ); assert_eq!(c(&[0, 0, 3, 1, 3, 2, 4]).simplify(), c(&[3, 1, 3, 2, 4])); - // Check that the `3`s are replaced correctly and that `4` ends up in the - // correct position. + // Check that the `3`s are replaced correctly and that `4` ends up in + // the correct position. assert_eq!( c(&[0, 0, 3, 1, 3, 2, 4]).update_from_simplified(c(&[10, 1, 11, 2, 4])), c(&[0, 0, 10, 1, 11, 2, 4]) diff --git a/core/src/repo_path.rs b/core/src/repo_path.rs index 9aa43d5bd5b..7a8983d00a3 100644 --- a/core/src/repo_path.rs +++ b/core/src/repo_path.rs @@ -479,8 +479,8 @@ impl RepoPath { for (self_comp, _other_comp) in common_components { if prefix_len > 0 { // + 1 for all paths to take their separators into account. - // We skip the first one since there are ComponentCount - 1 separators in a - // path. + // We skip the first one since there are ComponentCount - 1 + // separators in a path. prefix_len += 1; } diff --git a/core/src/str_util.rs b/core/src/str_util.rs index 4cc69786b00..d22967e463f 100644 --- a/core/src/str_util.rs +++ b/core/src/str_util.rs @@ -56,8 +56,9 @@ impl GlobPattern { /// Converts this glob pattern to a bytes regex. pub fn to_regex(&self) -> regex::bytes::Regex { - // Based on new_regex() in globset. We don't use GlobMatcher::is_match(path) - // because the input string shouldn't be normalized as path. + // Based on new_regex() in globset. We don't use + // GlobMatcher::is_match(path) because the input string + // shouldn't be normalized as path. regex::bytes::RegexBuilder::new(self.glob.regex()) .dot_matches_new_line(true) .build() @@ -202,9 +203,9 @@ impl StringPattern { /// /// This can be used to optimize map lookup by exact key. pub fn as_exact(&self) -> Option<&str> { - // TODO: Handle trivial case‐insensitive patterns here? It might make people - // expect they can use case‐insensitive patterns in contexts where they - // generally can’t. + // TODO: Handle trivial case‐insensitive patterns here? It might make + // people expect they can use case‐insensitive patterns in + // contexts where they generally can’t. match self { Self::Exact(literal) => Some(literal), _ => None, @@ -228,9 +229,9 @@ impl StringPattern { /// Converts this pattern to a glob string. Returns `None` if the pattern /// can't be represented as a glob. pub fn to_glob(&self) -> Option> { - // TODO: Handle trivial case‐insensitive patterns here? It might make people - // expect they can use case‐insensitive patterns in contexts where they - // generally can’t. + // TODO: Handle trivial case‐insensitive patterns here? It might make + // people expect they can use case‐insensitive patterns in + // contexts where they generally can’t. match self { Self::Exact(literal) => Some(globset::escape(literal).into()), Self::Substring(needle) => { @@ -257,13 +258,15 @@ impl StringPattern { // manner where relevant. That said, regex patterns are unicode-aware by // default, so we already have some inconsistencies. // - // Care will need to be taken regarding normalization and the choice of an - // appropriate case‐insensitive comparison scheme (`toNFKC_Casefold`?) to ensure - // that it is compatible with the standard case‐insensitivity of haystack - // components (like internationalized domain names in email addresses). The - // availability of normalization and case folding schemes in database backends - // will also need to be considered. A locale‐specific case folding - // scheme would likely not be appropriate for Jujutsu. + // Care will need to be taken regarding normalization and the choice of + // an appropriate case‐insensitive comparison scheme + // (`toNFKC_Casefold`?) to ensure that it is compatible with the + // standard case‐insensitivity of haystack components (like + // internationalized domain names in email addresses). The + // availability of normalization and case folding schemes in database + // backends will also need to be considered. A locale‐specific + // case folding scheme would likely not be appropriate for + // Jujutsu. // // For some discussion of this topic, see: // @@ -511,8 +514,8 @@ impl StringMatcher { /// Iterates over matching lines in `text`. pub fn match_lines<'a>(&self, text: &'a [u8]) -> impl Iterator { - // The pattern is matched line by line so that it can be anchored to line - // start/end. For example, exact:"" will match blank lines. + // The pattern is matched line by line so that it can be anchored to + // line start/end. For example, exact:"" will match blank lines. text.split_inclusive(|b| *b == b'\n').filter(|line| { let line = line.strip_suffix(b"\n").unwrap_or(line); self.is_match_bytes(line) diff --git a/lib/src/bisect.rs b/lib/src/bisect.rs index 8273927f271..5bf8f674f12 100644 --- a/lib/src/bisect.rs +++ b/lib/src/bisect.rs @@ -162,9 +162,9 @@ impl<'repo> Bisector<'repo> { /// Mark a commit as causing an abort pub fn mark_abort(&mut self, id: CommitId) { // TODO: Right now, we only use this state for triggering an abort. - // A potential improvement would be to make the CLI print out the revset with - // the current status of each change, making it possible for a user - // to restart an aborted bisect in progress. + // A potential improvement would be to make the CLI print out the revset + // with the current status of each change, making it possible + // for a user to restart an aborted bisect in progress. assert!(!self.good_commits.contains(&id)); assert!(!self.bad_commits.contains(&id)); assert!(!self.skipped_commits.contains(&id)); @@ -222,8 +222,8 @@ impl<'repo> Bisector<'repo> { if self.aborted { return Ok(NextStep::Done(BisectionResult::Abort)); } - // Intersect the input range with the current bad range and then bisect it to - // find the next commit to evaluate. + // Intersect the input range with the current bad range and then bisect + // it to find the next commit to evaluate. // Skipped revisions are simply subtracted from the set. // TODO: Handle long ranges of skipped revisions better let to_evaluate_expr = self.candidates().bisect().latest(1); diff --git a/lib/src/commit_builder.rs b/lib/src/commit_builder.rs index b8c51227b9f..3dba597e9fe 100644 --- a/lib/src/commit_builder.rs +++ b/lib/src/commit_builder.rs @@ -233,8 +233,8 @@ impl DetachedCommitBuilder { let mut commit = backend::Commit::clone(predecessor.store_commit()); commit.predecessors = vec![]; commit.committer = settings.signature(); - // If the user had not configured a name and email before but now they have, - // update the author fields with the new information. + // If the user had not configured a name and email before but now they + // have, update the author fields with the new information. if commit.author.name.is_empty() { commit.author.name.clone_from(&commit.committer.name); } diff --git a/lib/src/config_resolver.rs b/lib/src/config_resolver.rs index 22200a3f586..4fe6b7f0210 100644 --- a/lib/src/config_resolver.rs +++ b/lib/src/config_resolver.rs @@ -1343,8 +1343,8 @@ mod tests { assert_eq!(resolved_config.layers().len(), 1); insta::assert_snapshot!(resolved_config.layers()[0].data, @"a = 'a #0'"); - // MY_ENV=yes matches first scope, OR scope, key-exists scope, and second - // layer (but not nested scope or absent-exists scope) + // MY_ENV=yes matches first scope, OR scope, key-exists scope, and + // second layer (but not nested scope or absent-exists scope) let environment = HashMap::from([("MY_ENV".into(), "yes".into())]); let context = ConfigResolutionContext { home_dir: Some(Path::new("/home/dir")), diff --git a/lib/src/conflicts.rs b/lib/src/conflicts.rs index d58a375f804..f03eaff5bc5 100644 --- a/lib/src/conflicts.rs +++ b/lib/src/conflicts.rs @@ -522,9 +522,10 @@ fn materialize_conflict_hunks( conflict_index += 1; let conflict_info = format!("conflict {conflict_index} of {num_conflicts}"); - // If any side doesn't have the ending EOL, we remove the ending EOL from the - // conflict end marker line and "spread" the ending EOL to every side as a - // separator, so that contents without an ending EOL won't be concatenated with + // If any side doesn't have the ending EOL, we remove the ending EOL + // from the conflict end marker line and "spread" the + // ending EOL to every side as a separator, so that + // contents without an ending EOL won't be concatenated with // the conflict markers. let all_sides_have_ending_eol = hunk .iter() @@ -582,8 +583,8 @@ fn build_hunk_sides(hunk: Merge, labels: &ConflictLabels) -> Merge Mer removes.last_mut().unwrap().extend_from_slice(rest); adds.last_mut().unwrap().extend_from_slice(rest); } else if line == b"\n" || line == b"\r\n" { - // Some editors strip trailing whitespace, so " \n" might become "\n". It would - // be unfortunate if this prevented the conflict from being parsed, so we add - // the empty line to the "remove" and "add" as if there was a space in front + // Some editors strip trailing whitespace, so " \n" might + // become "\n". It would be unfortunate + // if this prevented the conflict from being parsed, so we + // add the empty line to the "remove" + // and "add" as if there was a space in front removes.last_mut().unwrap().extend_from_slice(line); adds.last_mut().unwrap().extend_from_slice(line); } else { @@ -1104,8 +1114,8 @@ pub async fn update_from_content( } } - // Now write the new files contents we found by parsing the file with conflict - // markers. + // Now write the new files contents we found by parsing the file with + // conflict markers. let new_file_ids: Vec> = try_join_all(zip(&contents, &simplified_file_ids).map( async |(content, file_id)| -> BackendResult> { if file_id.is_some() || !content.is_empty() { @@ -1359,7 +1369,8 @@ mod tests { style: ConflictMarkerStyle, eol: &str, ) { - // Add a leading EOL to suggest the correct EOL to use for materialization. + // Add a leading EOL to suggest the correct EOL to use for + // materialization. let base = format!("\n{base}{base_ending_eol}").replace('\n', eol); let side1 = format!("\n{side1}{side1_ending_eol}").replace('\n', eol); let side2 = format!("\n{side2}{side2_ending_eol}").replace('\n', eol); @@ -1377,7 +1388,8 @@ mod tests { .into(), ) .unwrap(); - // We expect the materialized conflict to keep the original EOL, LF or CRLF. + // We expect the materialized conflict to keep the original EOL, LF or + // CRLF. for line in actual_contents.as_bytes().lines_with_terminator() { let line = line.as_bstr(); if !line.ends_with(b"\n") { @@ -1425,9 +1437,9 @@ mod tests { "right\r\n", ]); "crlf")] fn test_materialize_conflict_trailing_cr(merge: Merge<&str>) { - // A side ending with a CR but no ending EOL must survive the round trip. - // The only EOL parsing may strip is the separator the materialization - // added, not one the content already carried. + // A side ending with a CR but no ending EOL must survive the round + // trip. The only EOL parsing may strip is the separator the + // materialization added, not one the content already carried. let options = ConflictMaterializeOptions { marker_style: ConflictMarkerStyle::Git, marker_len: None, diff --git a/lib/src/converge.rs b/lib/src/converge.rs index 723fce854bb..785018ae8f8 100644 --- a/lib/src/converge.rs +++ b/lib/src/converge.rs @@ -274,9 +274,9 @@ impl TruncatedEvolutionGraph { walk_predecessors(&repo, divergent_commit_ids.as_slice()).boxed_local(), ); - // These are the commits in the graph that have no predecessors. Typically - // there is exactly one entry in initial_nodes (the first commit for the - // change-id). + // These are the commits in the graph that have no predecessors. + // Typically there is exactly one entry in initial_nodes (the + // first commit for the change-id). let mut initial_nodes = vec![]; for node in evolution_nodes { @@ -288,13 +288,16 @@ impl TruncatedEvolutionGraph { } to_visit.remove(commit_id); if !seen.insert(commit_id.clone()) { - // TODO: think about this some more. Can 2 different operations result in the - // same commit? Maybe the key should be (commit-id, operation-id). - - // Note: currently walk_predecessors returns an error if the graph is cyclic, so - // we shouldn't encounter the same commit twice. But in the future we could - // allow cyclic evolution, and if we do there is no reason to disallow it here. - // By continuing we future proof this. + // TODO: think about this some more. Can 2 different operations + // result in the same commit? Maybe the key + // should be (commit-id, operation-id). + + // Note: currently walk_predecessors returns an error if the + // graph is cyclic, so we shouldn't encounter + // the same commit twice. But in the future we could + // allow cyclic evolution, and if we do there is no reason to + // disallow it here. By continuing we future + // proof this. continue; } let predecessors = entry @@ -331,9 +334,10 @@ impl TruncatedEvolutionGraph { let initial_node = if initial_nodes.len() == 1 { initial_nodes[0].clone() } else { - // In graphs with multiple "real" initial nodes we introduce a virtual initial - // node (the root commit) and pretend the two or more "real" initial nodes are - // successors of the root commit. + // In graphs with multiple "real" initial nodes we introduce a + // virtual initial node (the root commit) and pretend + // the two or more "real" initial nodes are successors + // of the root commit. let root_commit_id = repo.store().root_commit_id().clone(); for initial_node in initial_nodes { edges.push((root_commit_id.clone(), initial_node)); @@ -409,9 +413,10 @@ async fn converge_description( async fn converge_parents( graph: &TruncatedEvolutionGraph, ) -> Result>, ConvergeError> { - // Filter out divergent commits that are descendants of other divergent commits - // (we cannot use the parents of those commits because that would introduce - // cycles when we rebase everything on top of the parents). + // Filter out divergent commits that are descendants of other divergent + // commits (we cannot use the parents of those commits because that + // would introduce cycles when we rebase everything on top of the + // parents). let viable_commits = remove_descendants(graph.repo(), graph.divergent_commit_ids()).await?; let excluded_divergent_commits: HashSet = graph .divergent_commit_ids() @@ -497,9 +502,10 @@ async fn converge_trees( let parents_merged_tree = merge_commit_trees_no_resolve(repo.as_ref(), &parent_commits).await?; let rebased_resolved_trees = Arc::new(Mutex::new(HashMap::::new())); - // We first compute the dominator value of the trees (in the value history graph - // of the trees), together with the commit(s) that produce that tree. Any - // such commit is a good candidate to be used as the base of the merge. + // We first compute the dominator value of the trees (in the value history + // graph of the trees), together with the commit(s) that produce that + // tree. Any such commit is a good candidate to be used as the base of + // the merge. let value_fn = async |commit: &Commit| -> Result, ConvergeError> { let tree_ids_and_labels = TreeIdsAndLabels::new( @@ -509,10 +515,10 @@ async fn converge_trees( .lock() .unwrap() .insert(commit.id().clone(), tree_ids_and_labels.clone()); - // Note we only return the tree ids here, not the labels. We do that to increase - // the chances of finding a common dominator value that is closer to the - // divergent commits, ideally one that result in a simple merge of the trees - // later on. + // Note we only return the tree ids here, not the labels. We do that to + // increase the chances of finding a common dominator value that + // is closer to the divergent commits, ideally one that result + // in a simple merge of the trees later on. Ok(tree_ids_and_labels.tree_ids.clone()) }; @@ -645,13 +651,14 @@ where _ => {} } - // If there is more than one producer we choose the one of minimum rank, where - // rank is defined as lowest change-offset. Because some backends may not - // provide change-offsets for hidden commits, we consider those as having - // maximum change-offset and use input-order as the secondary sorting criterion. - // By input-order we refer to the order of commits passed to converge_change. - // But some commits are not given as input, so we use commit timestamp and - // CommitId as additional sorting criteria. + // If there is more than one producer we choose the one of minimum rank, + // where rank is defined as lowest change-offset. Because some backends + // may not provide change-offsets for hidden commits, we consider those + // as having maximum change-offset and use input-order as the secondary + // sorting criterion. By input-order we refer to the order of commits + // passed to converge_change. But some commits are not given as input, + // so we use commit timestamp and CommitId as additional sorting + // criteria. let resolved_change_targets = truncated_evolution_graph .repo() @@ -664,8 +671,8 @@ where .map(|(position, commit_id)| (commit_id, position)) .collect(); - // The sorting key is (change_offset, input_position, negated millis since Unix - // epoch, commit_id). + // The sorting key is (change_offset, input_position, negated millis since + // Unix epoch, commit_id). type SortingKey = (usize, usize, i64, CommitId); let producers: Vec<_> = try_join_all(producers.iter().map( async |commit_id| -> Result { @@ -679,8 +686,8 @@ where .store() .get_commit_async(commit_id) .await?; - // We take MillisSinceEpoch and negate it, so that more recent commits are - // before older ones. + // We take MillisSinceEpoch and negate it, so that more recent + // commits are before older ones. let millis_since_unix_epoch = commit.committer().timestamp.timestamp.0; Ok(( change_offset, diff --git a/lib/src/copies.rs b/lib/src/copies.rs index f12ce3a5bc5..c39097ddf7c 100644 --- a/lib/src/copies.rs +++ b/lib/src/copies.rs @@ -66,10 +66,11 @@ impl CopyRecords { /// conflicts is discarded and treated as not having an origin. pub fn add_records(&mut self, copy_records: impl IntoIterator) { for r in copy_records { - // The same copy or rename is reported once per parent when diffing a - // merge commit. Identical (source, target) pairs describe the same - // operation, so skip the duplicate instead of marking both maps as - // conflicting, which would otherwise drop the copy/rename entirely. + // The same copy or rename is reported once per parent when diffing + // a merge commit. Identical (source, target) pairs + // describe the same operation, so skip the duplicate + // instead of marking both maps as conflicting, which + // would otherwise drop the copy/rename entirely. let is_duplicate = self .targets .get(&r.target) @@ -281,7 +282,8 @@ fn collect_descendants(copy_graph: &CopyGraph) -> IndexMap IndexMap { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { - // First, check if we have newly-finished futures. If this returns Pending, we - // intentionally fall through to poll `self.inner`. + // First, check if we have newly-finished futures. If this returns + // Pending, we intentionally fall through to poll + // `self.inner`. if let Poll::Ready(Some(next)) = self.pending.poll_next_unpin(cx) { return Poll::Ready(Some(next)); } - // If we didn't have queued results above, we want to check our wrapped stream - // for the next non-copy-matched diff entry. + // If we didn't have queued results above, we want to check our + // wrapped stream for the next non-copy-matched diff + // entry. let next_diff_entry = match ready!(self.inner.poll_next_unpin(cx)) { Some(diff_entry) => diff_entry, None if self.pending.is_empty() => return Poll::Ready(None), @@ -439,7 +443,8 @@ impl Stream for CopyHistoryDiffStream<'_> { // Don't try copy-tracing if we have conflicts on either side. // - // TODO: consider accepting conflicts if the copy IDs can be resolved. + // TODO: consider accepting conflicts if the copy IDs can be + // resolved. let Some(before) = before.as_resolved() else { self.pending .push_back(Box::pin(ready(CopyHistoryTreeDiffEntry::normal( @@ -469,22 +474,31 @@ impl Stream for CopyHistoryDiffStream<'_> { (other, Some(f @ TreeValue::File { .. })) => { if let Some(other) = other { - // For files with non-matching copy-ids, or for a non-file that changes to a - // file, mark the first as deleted and do copy-tracing on the second. + // For files with non-matching copy-ids, or for a + // non-file that changes to a + // file, mark the first as deleted and do copy-tracing + // on the second. // - // NOTE[deletion-diff-entry]: this may emit two diff entries, where the old - // diffstream would contain only one (even with gix's heuristic-based copy + // NOTE[deletion-diff-entry]: this may emit two diff + // entries, where the old + // diffstream would contain only one (even with gix's + // heuristic-based copy // detection). // - // This may be desirable in some cases (such as replacing a file X with a - // copy of some other file Y; the deletion entry makes it more clear that - // the original X was replaced by a formerly unrelated file). It is less - // desirable in cases where the new file shares some actual relation to the + // This may be desirable in some cases (such as + // replacing a file X with a + // copy of some other file Y; the deletion entry makes + // it more clear that + // the original X was replaced by a formerly unrelated + // file). It is less + // desirable in cases where the new file shares some + // actual relation to the // old one. // - // We plan to improve this in the near future, but for now we'll keep the - // simpler implementation since this behavior is not visible outside of - // tests yet. + // We plan to improve this in the near future, but for + // now we'll keep the + // simpler implementation since this behavior is not + // visible outside of tests yet. self.pending .push_back(Box::pin(ready(CopyHistoryTreeDiffEntry { target_path: next_diff_entry.path.clone(), @@ -618,8 +632,8 @@ async fn classify_source( { Ok(CopyHistorySource::Copy(before_path)) } else { - // before_path in before_tree & after_tree are not ancestors/descendants of - // each other + // before_path in before_tree & after_tree are not + // ancestors/descendants of each other Ok(CopyHistorySource::Rename(before_path)) } } @@ -630,8 +644,8 @@ async fn find_diff_sources_from_copies( copy_graph: &CopyGraph, descendants: &IndexMap>, ) -> BackendResult> { - // Related copies MUST contain ancestors AND descendants. It may also contain - // unrelated copies. + // Related copies MUST contain ancestors AND descendants. It may also + // contain unrelated copies. let history = copy_graph.get(copy_id).ok_or(BackendError::Other( "CopyId should be present in `get_related_copies()` result".into(), ))?; @@ -651,8 +665,8 @@ async fn find_diff_sources_from_copies( let mut sources = vec![]; - // Finds at most one related TreeValue::File present in `tree` per parent listed - // in `file`'s CopyHistory. + // Finds at most one related TreeValue::File present in `tree` per parent + // listed in `file`'s CopyHistory. // // TODO: this correctly finds the shallowest relative, but it only finds // one. I'm not sure what is the best thing to do when one of our parents @@ -664,12 +678,12 @@ async fn find_diff_sources_from_copies( // / \ // A B // - // where D is `file`, C is its parent but is not present in `tree`, but both A - // and B are present, this will find either A or B, not both. Should we - // return both A and B instead? I don't think there's a way to do that with - // the current dag_walk functions. Do we care enough to implement something - // new there that pays more attention to the depth in the DAG? Perhaps - // a variant of closest_common_nodes? + // where D is `file`, C is its parent but is not present in `tree`, but both + // A and B are present, this will find either A or B, not both. Should + // we return both A and B instead? I don't think there's a way to do + // that with the current dag_walk functions. Do we care enough to + // implement something new there that pays more attention to the depth + // in the DAG? Perhaps a variant of closest_common_nodes? 'parents: for parent_copy_id in &history.parents { let mut absent_ancestors = vec![]; @@ -688,8 +702,8 @@ async fn find_diff_sources_from_copies( // If not, then try descendants of the parent // - // TODO: This will find a relative, when what we really want is probably the - // "closest" relative. + // TODO: This will find a relative, when what we really want is probably + // the "closest" relative. for descendant_id in &descendants[parent_copy_id] { if let Some(descendant) = tree.copy_value(descendant_id).await? { sources.push((copy_graph[descendant_id].current_path.clone(), descendant)); @@ -699,8 +713,8 @@ async fn find_diff_sources_from_copies( // Finally, try descendants of any ancestor // - // TODO: This will find a relative, when what we really want is probably the - // "closest" relative. + // TODO: This will find a relative, when what we really want is probably + // the "closest" relative. for ancestor_id in absent_ancestors { for descendant_id in descendants[ancestor_id].difference(&descendants[parent_copy_id]) { if let Some(descendant) = tree.copy_value(descendant_id).await? { diff --git a/lib/src/default_index/composite.rs b/lib/src/default_index/composite.rs index 8d1d16f971d..526f3dda52e 100644 --- a/lib/src/default_index/composite.rs +++ b/lib/src/default_index/composite.rs @@ -273,7 +273,8 @@ impl CompositeCommitIndex { let num_parent_commits = segment.num_parent_commits(); move |LocalCommitPosition(pos)| GlobalCommitPosition(pos + num_parent_commits) }; - // Similar to PrefixResolution::plus(), but merges matches of the same id. + // Similar to PrefixResolution::plus(), but merges matches of + // the same id. match (acc_match, segment.resolve_change_id_prefix(prefix)) { (NoMatch, local_match) => local_match.map(|(id, positions)| { (id, positions.into_iter().rev().map(to_global_pos).collect()) @@ -450,9 +451,10 @@ impl CompositeCommitIndex { return candidate_positions; }; - // Iterate though the candidates by reverse index position, keeping track of the - // ancestors of already-found heads. If a candidate is an ancestor of an - // already-found head, then it can be removed. + // Iterate though the candidates by reverse index position, keeping + // track of the ancestors of already-found heads. If a candidate + // is an ancestor of an already-found head, then it can be + // removed. let mut parents = BinaryHeap::new(); let mut heads = Vec::new(); 'outer: for candidate in candidate_positions { @@ -464,7 +466,8 @@ impl CompositeCommitIndex { shift_to_parents(&mut parents, parent, &entry.parent_positions()); } if parent == candidate { - // The candidate is an ancestor of an existing head, so we can skip it. + // The candidate is an ancestor of an existing head, so we + // can skip it. continue 'outer; } } @@ -692,8 +695,8 @@ impl ChangeIdIndex for ChangeIdIndexImpl { // Resolves change ID prefix among all IDs. // // If `SingleMatch` is returned, there is at least one commit with the given - // change ID (either visible or hidden). `AmbiguousMatch` may be returned even - // if the prefix is unique within the visible entries. + // change ID (either visible or hidden). `AmbiguousMatch` may be returned + // even if the prefix is unique within the visible entries. async fn resolve_prefix( &self, prefix: &HexPrefix, diff --git a/lib/src/default_index/mod.rs b/lib/src/default_index/mod.rs index 445e2073701..b1c512dc57b 100644 --- a/lib/src/default_index/mod.rs +++ b/lib/src/default_index/mod.rs @@ -231,8 +231,8 @@ mod tests { mutable_segment.add_commit_data(id_1.clone(), change_id1.clone(), &[id_0.clone()]); mutable_segment.add_commit_data(id_2.clone(), change_id2.clone(), &[id_0.clone()]); - // If testing incremental indexing, write the first three commits to one file - // now and build the remainder as another segment on top. + // If testing incremental indexing, write the first three commits to one + // file now and build the remainder as another segment on top. if incremental { let initial_file = mutable_segment.save_in(temp_dir.path()).unwrap(); mutable_segment = MutableCommitIndexSegment::incremental(initial_file); @@ -407,7 +407,8 @@ mod tests { mutable_segment.add_commit_data(id_1.clone(), new_change_id(), &[]); mutable_segment.add_commit_data(id_2.clone(), new_change_id(), &[]); - // Write the first three commits to one file and build the remainder on top. + // Write the first three commits to one file and build the remainder on + // top. let initial_file = mutable_segment.save_in(temp_dir.path())?; mutable_segment = MutableCommitIndexSegment::incremental(initial_file); @@ -480,7 +481,8 @@ mod tests { mutable_segment.add_commit_data(id_1.clone(), new_change_id(), &[]); mutable_segment.add_commit_data(id_2.clone(), new_change_id(), &[]); - // Write the first three commits to one file and build the remainder on top. + // Write the first three commits to one file and build the remainder on + // top. let initial_file = mutable_segment.save_in(temp_dir.path())?; mutable_segment = MutableCommitIndexSegment::incremental(initial_file.clone()); @@ -533,7 +535,8 @@ mod tests { (Some(id_3.clone()), None), ); - // Local lookup in mutable index, commit_id does not exist. id_5 < id_3 < id_4 + // Local lookup in mutable index, commit_id does not exist. id_5 < id_3 + // < id_4 assert_eq!( mutable_segment.resolve_neighbor_commit_ids(&CommitId::from_hex("033332")), (None, Some(id_5.clone())), @@ -547,7 +550,8 @@ mod tests { (Some(id_4.clone()), None), ); - // Global lookup, commit_id exists. id_0 < id_1 < id_5 < id_3 < id_2 < id_4 + // Global lookup, commit_id exists. id_0 < id_1 < id_5 < id_3 < id_2 < + // id_4 let composite_index = CompositeCommitIndex::new(&mutable_segment); assert_eq!( composite_index.resolve_neighbor_commit_ids(&id_0), @@ -574,8 +578,8 @@ mod tests { (Some(id_2.clone()), None), ); - // Global lookup, commit_id doesn't exist. id_0 < id_1 < id_5 < id_3 < id_2 < - // id_4 + // Global lookup, commit_id doesn't exist. id_0 < id_1 < id_5 < id_3 < + // id_2 < id_4 assert_eq!( composite_index.resolve_neighbor_commit_ids(&CommitId::from_hex("000000")), (None, Some(id_0.clone())), @@ -609,7 +613,8 @@ mod tests { mutable_segment.add_commit_data(id_1.clone(), new_change_id(), &[]); mutable_segment.add_commit_data(id_2.clone(), new_change_id(), &[]); - // Write the first three commits to one file and build the remainder on top. + // Write the first three commits to one file and build the remainder on + // top. let initial_file = mutable_segment.save_in(temp_dir.path())?; mutable_segment = MutableCommitIndexSegment::incremental(initial_file); @@ -630,7 +635,8 @@ mod tests { assert_eq!(index.shortest_unique_commit_id_prefix_len(&id_4), 4); assert_eq!(index.shortest_unique_commit_id_prefix_len(&id_5), 2); - // Public API: calculate shortest unique prefix len with unknown commit_id + // Public API: calculate shortest unique prefix len with unknown + // commit_id assert_eq!( index.shortest_unique_commit_id_prefix_len(&CommitId::from_hex("000002")), 6 @@ -1328,8 +1334,8 @@ mod tests { index.add_commit_data(id_4.clone(), new_change_id(), &[id_1.clone()]); index.add_commit_data(id_5.clone(), new_change_id(), &[id_4.clone(), id_2.clone()]); - // Helper function to convert commit IDs to/from index positions and call - // `heads_from_range_and_filter`. + // Helper function to convert commit IDs to/from index positions and + // call `heads_from_range_and_filter`. let heads_range = |roots: &[&CommitId], heads: &[&CommitId], parents_range: &Range, diff --git a/lib/src/default_index/mutable.rs b/lib/src/default_index/mutable.rs index 3194a7f9a4e..e729d521837 100644 --- a/lib/src/default_index/mutable.rs +++ b/lib/src/default_index/mutable.rs @@ -320,8 +320,9 @@ impl MutableCommitIndexSegment { let mut files_to_squash = vec![]; let mut base_parent_file = None; for parent_file in self.as_composite().ancestor_files_without_local() { - // TODO: We should probably also squash if the parent file has less than N - // commits, regardless of how many (few) are in `self`. + // TODO: We should probably also squash if the parent file has less + // than N commits, regardless of how many (few) are in + // `self`. if 2 * num_new_commits < parent_file.num_local_commits() { base_parent_file = Some(parent_file.clone()); break; diff --git a/lib/src/default_index/readonly.rs b/lib/src/default_index/readonly.rs index f16f40ef3bc..5906d35631c 100644 --- a/lib/src/default_index/readonly.rs +++ b/lib/src/default_index/readonly.rs @@ -114,8 +114,9 @@ impl ReadonlyIndexLoadError { match self { Self::UnexpectedVersion { .. } => true, Self::Other { error, .. } => { - // If the parent file name field is corrupt, the file wouldn't be found. - // And there's no need to distinguish it from an empty file. + // If the parent file name field is corrupt, the file wouldn't + // be found. And there's no need to distinguish + // it from an empty file. matches!( error.kind(), io::ErrorKind::NotFound diff --git a/lib/src/default_index/rev_walk.rs b/lib/src/default_index/rev_walk.rs index 584f02dceaa..67661a84e86 100644 --- a/lib/src/default_index/rev_walk.rs +++ b/lib/src/default_index/rev_walk.rs @@ -271,7 +271,8 @@ impl RevWalkDescendantsIndex { index: &CompositeCommitIndex, positions: impl IntoIterator, ) -> Self { - // For dense set, it's probably cheaper to use `Vec` instead of `HashMap`. + // For dense set, it's probably cheaper to use `Vec` instead of + // `HashMap`. let mut children_map: HashMap = HashMap::new(); for pos in positions { @@ -393,8 +394,8 @@ impl<'a> RevWalkBuilder<'a> { self, root_positions: impl IntoIterator, ) -> RevWalkAncestors<'a> { - // We can also make it stop visiting based on the generation number. Maybe - // it will perform better for unbalanced branchy history. + // We can also make it stop visiting based on the generation number. + // Maybe it will perform better for unbalanced branchy history. // https://github.com/jj-vcs/jj/pull/1492#discussion_r1160678325 let min_pos = root_positions .into_iter() @@ -554,8 +555,9 @@ impl RevWalk for RevWalkGenerationRangeImpl7: 3..5, 7: 0..2 + // Multiple non-overlapping generation ranges to track, and merged + // later: 10->7: 3..5, 7: 0..2 // 10->6: 4..6, 7->6, 1..3, 6: 0..2 assert_eq!( walk_commit_ids(&[&ids[10], &ids[7], &ids[6]].map(Clone::clone), 5..7), diff --git a/lib/src/default_index/revset_engine.rs b/lib/src/default_index/revset_engine.rs index 041e22bd735..66e92cc068f 100644 --- a/lib/src/default_index/revset_engine.rs +++ b/lib/src/default_index/revset_engine.rs @@ -195,9 +195,10 @@ impl Revset for RevsetImpl { fn count_estimate(&self) -> Result<(usize, Option), RevsetEvaluationError> { if cfg!(feature = "testing") { - // Exercise the estimation feature in tests. (If we ever have a Revset - // implementation in production code that returns estimates, we can probably - // remove this and rewrite the associated tests.) + // Exercise the estimation feature in tests. (If we ever have a + // Revset implementation in production code that returns + // estimates, we can probably remove this and rewrite + // the associated tests.) let count = self .positions() .take(10) @@ -841,7 +842,8 @@ impl EvaluationContext<'_> { .iter() .any(|parent_pos| root_positions.contains(parent_pos))) }); - // TODO: Suppose heads include all visible heads, ToPredicateFn version can be + // TODO: Suppose heads include all visible heads, + // ToPredicateFn version can be // optimized to only test the predicate() Ok(Box::new(FilterRevset { candidates, @@ -854,8 +856,9 @@ impl EvaluationContext<'_> { positions.reverse(); Ok(Box::new(EagerRevset { positions })) } else { - // For small generation range, it might be better to build a reachable map - // with generation bit set, which can be calculated incrementally from roots: + // For small generation range, it might be better to build a + // reachable map with generation bit + // set, which can be calculated incrementally from roots: // reachable[pos] = (reachable[parent_pos] | ...) << 1 let mut positions = builder .descendants_filtered_by_generation( @@ -882,19 +885,22 @@ impl EvaluationContext<'_> { } } } - // `UnionFind::find` is somewhat slow, so it's faster to only do this once and - // then cache the result. + // `UnionFind::find` is somewhat slow, so it's faster to only do + // this once and then cache the result. let domain_reps = domain_vec.iter().map(|&pos| sets.find(pos)).collect_vec(); - // Identify disjoint sets reachable from sources. Using a predicate here can be - // significantly faster for cases like `reachable(filter, X)`, since the filter - // can be checked for only commits in `X` instead of for all visible commits, - // and the difference is usually negligible for non-filter revsets. + // Identify disjoint sets reachable from sources. Using a + // predicate here can be significantly faster + // for cases like `reachable(filter, X)`, since the filter + // can be checked for only commits in `X` instead of for all + // visible commits, and the difference is + // usually negligible for non-filter revsets. let sources_revset = self.evaluate(sources)?; let mut sources_predicate = sources_revset.to_predicate_fn(); let mut set_reps = HashSet::new(); for (&pos, &rep) in domain_vec.iter().zip(&domain_reps) { - // Skip evaluating predicate if `rep` has already been added. + // Skip evaluating predicate if `rep` has already been + // added. if set_reps.contains(&rep) { continue; } @@ -1232,9 +1238,9 @@ impl EvaluationContext<'_> { })) }; - // Maintain min-heap containing the latest (greatest) count items. For small - // count and large candidate set, this is probably cheaper than building vec - // and applying selection algorithm. + // Maintain min-heap containing the latest (greatest) count items. For + // small count and large candidate set, this is probably cheaper + // than building vec and applying selection algorithm. let mut candidate_iter = candidate_set .positions() .attach(self.index) diff --git a/lib/src/default_index/revset_graph_iterator.rs b/lib/src/default_index/revset_graph_iterator.rs index 3966a108c87..d2576b9ac95 100644 --- a/lib/src/default_index/revset_graph_iterator.rs +++ b/lib/src/default_index/revset_graph_iterator.rs @@ -231,8 +231,9 @@ impl<'a> RevsetGraphWalk<'a> { // The parent is not in the input set Some([CommitGraphEdge::missing(parent_position)].into()) } else { - // The parent is not in the input set but it's somewhere in the range - // where we have commits in the input set, so continue searching. + // The parent is not in the input set but it's somewhere in + // the range where we have commits in + // the input set, so continue searching. stack.push(parent); None } @@ -260,8 +261,9 @@ impl<'a> RevsetGraphWalk<'a> { // The parent is not in the input set edges.push(CommitGraphEdge::missing(parent_position)); } else { - // The parent is not in the input set but it's somewhere in the range - // where we have commits in the input set, so continue searching. + // The parent is not in the input set but it's somewhere + // in the range where we have + // commits in the input set, so continue searching. stack.push(parent); parents_complete = false; } @@ -315,7 +317,8 @@ impl<'a> RevsetGraphWalk<'a> { min_generation = min(min_generation, entry.generation_number()); enqueue_parents(&mut work, &entry); } - // Find commits reachable transitively and add them to the `unwanted` set. + // Find commits reachable transitively and add them to the `unwanted` + // set. let mut unwanted = PositionsBitSet::with_max_pos(max_pos); while let Some(pos) = work.pop() { if unwanted.get_set(pos) { diff --git a/lib/src/default_index/store.rs b/lib/src/default_index/store.rs index 07796c112ad..1ef336d87d4 100644 --- a/lib/src/default_index/store.rs +++ b/lib/src/default_index/store.rs @@ -532,8 +532,8 @@ impl IndexStore for DefaultIndexStore { self.build_index_at_operation(op, store).await } Err(DefaultIndexStoreError::LoadIndex(err)) if err.is_corrupt_or_not_found() => { - // If the index was corrupt (maybe it was written in a different format), - // we just reindex. + // If the index was corrupt (maybe it was written in a different + // format), we just reindex. match &err { ReadonlyIndexLoadError::UnexpectedVersion { kind, diff --git a/lib/src/diff_presentation/mod.rs b/lib/src/diff_presentation/mod.rs index cd1bffb756c..6d643990b21 100644 --- a/lib/src/diff_presentation/mod.rs +++ b/lib/src/diff_presentation/mod.rs @@ -59,12 +59,12 @@ pub async fn file_content_for_diff( map_resolved: impl FnOnce(BString) -> T, ) -> BackendResult> { // If this is a binary file, don't show the full contents. - // Determine whether it's binary by whether the first 8k bytes contain a null - // character; this is the same heuristic used by git as of writing: https://github.com/git/git/blob/eea0e59ffbed6e33d171ace5be13cde9faa41639/xdiff-interface.c#L192-L198 + // Determine whether it's binary by whether the first 8k bytes contain a + // null character; this is the same heuristic used by git as of writing: https://github.com/git/git/blob/eea0e59ffbed6e33d171ace5be13cde9faa41639/xdiff-interface.c#L192-L198 const PEEK_SIZE: usize = 8000; - // TODO: currently we look at the whole file, even though for binary files we - // only need to know the file size. To change that we'd have to extend all - // the data backends to support getting the length. + // TODO: currently we look at the whole file, even though for binary files + // we only need to know the file size. To change that we'd have to + // extend all the data backends to support getting the length. let contents = BString::new(file.read_all(path).await?); let start = &contents[..PEEK_SIZE.min(contents.len())]; Ok(FileContent { diff --git a/lib/src/dsl_util.rs b/lib/src/dsl_util.rs index 27596d26fa8..01715d417c2 100644 --- a/lib/src/dsl_util.rs +++ b/lib/src/dsl_util.rs @@ -882,8 +882,8 @@ where }; return Err(E::invalid_arguments(err)); }; - // Resolve arguments in the current scope, and pass them in to the alias - // expansion scope. + // Resolve arguments in the current scope, and pass them in to the + // alias expansion scope. let args = fold_expression_nodes(self, function.args)?; let locals = params.iter().map(|s| s.as_str()).zip(args).collect(); self.expand_defn(id, defn, locals, span) diff --git a/lib/src/eol.rs b/lib/src/eol.rs index bfb111d3de5..3466c75c02b 100644 --- a/lib/src/eol.rs +++ b/lib/src/eol.rs @@ -21,9 +21,9 @@ use crate::config::ConfigGetError; use crate::settings::UserSettings; fn is_binary(bytes: &[u8]) -> bool { - // TODO(06393993): align the algorithm with git so that the git config autocrlf - // users won't see different decisions on whether a file is binary and needs to - // perform EOL conversion. + // TODO(06393993): align the algorithm with git so that the git config + // autocrlf users won't see different decisions on whether a file is + // binary and needs to perform EOL conversion. let mut bytes = bytes.iter().peekable(); while let Some(byte) = bytes.next() { match *byte { @@ -179,8 +179,8 @@ async fn convert_eol<'a>( // If the line ends with an EOL, we should append the target EOL. res.extend_from_slice(eol); } else { - // If the line doesn't end with an EOL, we don't append the EOL. This can happen - // on the last line. + // If the line doesn't end with an EOL, we don't append the EOL. + // This can happen on the last line. res.extend_from_slice(line); } } @@ -252,8 +252,8 @@ mod tests { let message = "test error"; let error_reader = ErrorReader::new(std::io::Error::other(message)); let mut output = vec![]; - // TODO: use TryFutureExt::and_then and async closure after we upgrade to 1.85.0 - // or later. + // TODO: use TryFutureExt::and_then and async closure after we upgrade + // to 1.85.0 or later. let err = match convert_eol(error_reader, target_eol).await { Ok(mut reader) => reader.read_to_end(&mut output).await, Err(e) => Err(e), diff --git a/lib/src/files.rs b/lib/src/files.rs index 731582080a2..b227d95562e 100644 --- a/lib/src/files.rs +++ b/lib/src/files.rs @@ -128,8 +128,8 @@ where type Item = DiffLine<'a>; fn next(&mut self) -> Option { - // TODO: Should we attempt to interpret as utf-8 and otherwise break only at - // newlines? + // TODO: Should we attempt to interpret as utf-8 and otherwise break + // only at newlines? while self.queued_lines.is_empty() { let Some(hunk) = self.diff_hunks.next() else { break; @@ -312,8 +312,8 @@ where B: FromMergeHunks<'input>, { // TODO: Using the first remove as base (first in the inputs) is how it's - // usually done for 3-way conflicts. Are there better heuristics when there are - // more than 3 parts? + // usually done for 3-way conflicts. Are there better heuristics when there + // are more than 3 parts? let num_diffs = inputs.removes().len(); let diff = ContentDiff::by_line(inputs.removes().chain(inputs.adds())); let hunks = resolve_diff_hunks(&diff, num_diffs, options.same_change); @@ -947,9 +947,9 @@ mod tests { merge_hunks(&conflict([b"b", b"a", b"a", b"a", b"c"])), MergeResult::Conflict(vec![conflict([b"b", b"a", b"a", b"a", b"c"])]) ); - // Merge of an unresolved conflict and another branch, where the other branch - // undid the change from one of the inputs to the unresolved conflict in the - // first. + // Merge of an unresolved conflict and another branch, where the other + // branch undid the change from one of the inputs to the + // unresolved conflict in the first. assert_eq!( merge_hunks(&conflict([b"b", b"a", b"a", b"b", b"c"])), MergeResult::Resolved(hunk(b"c")) @@ -975,7 +975,8 @@ mod tests { let merge_hunks = |inputs: &_| merge_hunks(inputs, &options); let merge = |inputs: &_| merge(inputs, &options); let try_merge = |inputs: &_| try_merge(inputs, &options); - // Two sides left one line unchanged, and added conflicting additional lines + // Two sides left one line unchanged, and added conflicting additional + // lines let inputs = conflict([b"a\nb\n", b"a\n", b"a\nc\n"]); assert_eq!( merge_hunks(&inputs), @@ -1024,9 +1025,10 @@ mod tests { ); assert_eq!(try_merge(&inputs), None); - // One side changes a line and adds a block after. The other side just adds the - // same block. You might expect the last block would be deduplicated. However, - // the changes in the first side can be parsed as follows: + // One side changes a line and adds a block after. The other side just + // adds the same block. You might expect the last block would be + // deduplicated. However, the changes in the first side can be + // parsed as follows: // ``` // a { // - p @@ -1037,8 +1039,9 @@ mod tests { // + x // } // ``` - // Therefore, the first side modifies the block `a { .. }`, and the second side - // adds `b { .. }`. Git and Mercurial both duplicate the block in the result. + // Therefore, the first side modifies the block `a { .. }`, and the + // second side adds `b { .. }`. Git and Mercurial both duplicate + // the block in the result. let base = indoc! {b" a { p diff --git a/lib/src/fileset.rs b/lib/src/fileset.rs index b9ee3b9d27d..6f27bb4fa28 100644 --- a/lib/src/fileset.rs +++ b/lib/src/fileset.rs @@ -996,7 +996,8 @@ mod tests { ) "#); - // case-insensitive pattern with directory component (should not split the path) + // case-insensitive pattern with directory component (should not split + // the path) insta::assert_debug_snapshot!( parse(r#"glob-i:"SubDir/*.rs""#)?, @r#" Pattern( @@ -1011,7 +1012,8 @@ mod tests { ) "#); - // case-sensitive pattern with directory component (should split the path) + // case-sensitive pattern with directory component (should split the + // path) insta::assert_debug_snapshot!( parse(r#"glob:"SubDir/*.rs""#)?, @r#" Pattern( @@ -1026,7 +1028,8 @@ mod tests { ) "#); - // case-insensitive pattern with leading dots (should split dots but not dirs) + // case-insensitive pattern with leading dots (should split dots but not + // dirs) insta::assert_debug_snapshot!( parse(r#"glob-i:"../SomeDir/*.rs""#)?, @r#" Pattern( diff --git a/lib/src/fileset_parser.rs b/lib/src/fileset_parser.rs index d308df1f398..31adacebbb1 100644 --- a/lib/src/fileset_parser.rs +++ b/lib/src/fileset_parser.rs @@ -1166,7 +1166,8 @@ mod tests { parse_normalized("b|c") ); - // Infinite recursion, where the top-level error isn't of RecursiveAlias kind. + // Infinite recursion, where the top-level error isn't of RecursiveAlias + // kind. assert_eq!( with_aliases([("A", "A")]).parse("A").unwrap_err().kind, FilesetParseErrorKind::InAliasExpansion("A".to_owned()) @@ -1228,7 +1229,8 @@ mod tests { parse_normalized("a") ); - // Infinite recursion, where the top-level error isn't of RecursiveAlias kind. + // Infinite recursion, where the top-level error isn't of RecursiveAlias + // kind. assert_eq!( with_aliases([("P:x", "Q:x"), ("Q:x", "R:x"), ("R:x", "P:x")]) .parse("P:a") @@ -1345,7 +1347,8 @@ mod tests { } ); - // Infinite recursion, where the top-level error isn't of RecursiveAlias kind. + // Infinite recursion, where the top-level error isn't of RecursiveAlias + // kind. assert_eq!( with_aliases([("F(x)", "G(x)"), ("G(x)", "H(x)"), ("H(x)", "F(x)")]) .parse("F(a)") diff --git a/lib/src/fix.rs b/lib/src/fix.rs index 095465e2cbb..5977396c5bf 100644 --- a/lib/src/fix.rs +++ b/lib/src/fix.rs @@ -187,21 +187,22 @@ pub async fn fix_files( ) -> Result { let mut summary = FixSummary::default(); - // Collect all of the unique `FileToFix`s we're going to use. file_fixer should - // be deterministic, and should not consider outside information, so it is - // safe to deduplicate inputs that correspond to multiple files or commits. - // This is typically more efficient, but it does prevent certain use cases - // like providing commit IDs as inputs to be inserted into files. We also - // need to record the mapping between files-to-fix and paths/commits, to - // efficiently rewrite the commits later. + // Collect all of the unique `FileToFix`s we're going to use. file_fixer + // should be deterministic, and should not consider outside information, + // so it is safe to deduplicate inputs that correspond to multiple files + // or commits. This is typically more efficient, but it does prevent + // certain use cases like providing commit IDs as inputs to be inserted + // into files. We also need to record the mapping between files-to-fix + // and paths/commits, to efficiently rewrite the commits later. // - // If a path is being fixed in a particular commit, it must also be fixed in all - // that commit's descendants. We do this as a way of propagating changes, - // under the assumption that it is more useful than performing a rebase and - // risking merge conflicts. In the case of code formatters, rebasing wouldn't - // reliably produce well formatted code anyway. Deduplicating inputs helps - // to prevent quadratic growth in the number of tool executions required for - // doing this in long chains of commits with disjoint sets of modified files. + // If a path is being fixed in a particular commit, it must also be fixed in + // all that commit's descendants. We do this as a way of propagating + // changes, under the assumption that it is more useful than performing + // a rebase and risking merge conflicts. In the case of code formatters, + // rebasing wouldn't reliably produce well formatted code anyway. + // Deduplicating inputs helps to prevent quadratic growth in the number + // of tool executions required for doing this in long chains of commits + // with disjoint sets of modified files. let commits: Vec<_> = RevsetExpression::commits(root_commits.clone()) .descendants() .evaluate(repo_mut)? @@ -242,10 +243,11 @@ pub async fn fix_files( } let base_tree = merge_commit_trees(repo_mut, &base_commits).await?; - // If --include-unchanged-files, we always fix every matching file in the tree. - // Otherwise, we fix the matching changed files in this commit, plus any that - // were fixed in ancestors, so we don't lose those changes. We do this - // instead of rebasing onto those changes, to avoid merge conflicts. + // If --include-unchanged-files, we always fix every matching file in + // the tree. Otherwise, we fix the matching changed files in + // this commit, plus any that were fixed in ancestors, so we + // don't lose those changes. We do this instead of rebasing onto + // those changes, to avoid merge conflicts. let diff_base_tree = if include_unchanged_files { &repo_mut.store().empty_merged_tree() } else { @@ -269,9 +271,10 @@ pub async fn fix_files( values.before.into_iter().next() }; - // Deleted files have no file content to fix, and they have no terms in `after`, - // so we don't add any files-to-fix for them. For conflicted files in the base - // commit(s), we diff against the first side of the conflict. For conflicted + // Deleted files have no file content to fix, and they have no terms + // in `after`, so we don't add any files-to-fix for + // them. For conflicted files in the base commit(s), we + // diff against the first side of the conflict. For conflicted // files in the current commit, we add all sides of the conflict to // the files-to-fix. let before_file_id = if let Some(Some(TreeValue::File { @@ -287,16 +290,18 @@ pub async fn fix_files( }; for after_term in values.after { - // We currently only support fixing the content of normal files, so we skip - // directories and symlinks, and we ignore the executable bit. + // We currently only support fixing the content of normal files, + // so we skip directories and symlinks, and we + // ignore the executable bit. if let Some(TreeValue::File { id, executable: _, copy_id: _, }) = after_term { - // TODO: Skip the file if its content is larger than some configured size, - // preferably without actually reading it yet. + // TODO: Skip the file if its content is larger than some + // configured size, preferably without + // actually reading it yet. let file_to_fix = FileToFix { file_id: id.clone(), base_file_id: before_file_id.clone(), @@ -320,13 +325,14 @@ pub async fn fix_files( let fixed_file_ids = file_fixer.fix_files(repo_mut.store().as_ref(), &unique_files_to_fix)?; tracing::debug!(?fixed_file_ids, "file fixer fixed these files:"); - // Substitute the fixed file IDs into all of the affected commits. Currently, - // fixes cannot delete or rename files, change the executable bit, or modify - // other parts of the commit like the description. + // Substitute the fixed file IDs into all of the affected commits. + // Currently, fixes cannot delete or rename files, change the executable + // bit, or modify other parts of the commit like the description. repo_mut .transform_descendants(root_commits, async |rewriter| { - // TODO: Build the trees in parallel before `transform_descendants()` and only - // keep the tree IDs in memory, so we can pass them to the rewriter. + // TODO: Build the trees in parallel before + // `transform_descendants()` and only keep the tree IDs + // in memory, so we can pass them to the rewriter. let old_commit_id = rewriter.old_commit().id().clone(); let repo_paths = commit_paths.get(&old_commit_id).unwrap(); let old_tree = rewriter.old_commit().tree(); @@ -427,8 +433,9 @@ pub fn compute_changed_ranges(base: &[u8], current: &[u8]) -> RegionsToFormat { DiffHunkKind::Matching => {} DiffHunkKind::Different => { if line_count > 0 { - // We want the diff ranges to be 1-based and inclusive [first, last] as this - // is what most formatters expect. + // We want the diff ranges to be 1-based and inclusive + // [first, last] as this is what most + // formatters expect. ranges.push(LineRange { first: current_line, last: current_line + line_count - 1, @@ -480,12 +487,13 @@ pub async fn get_base_commit_map( .map(|base_commit| base_commit.id().clone()) .collect(); - // Build a map of each commit to its "base commits" (closest ancestors not in - // `commits`). + // Build a map of each commit to its "base commits" (closest ancestors not + // in `commits`). // // We process commits in topological order (parents before children) so that // we can propagate the base commits from parents to children. Note that the - // `commits` vector is in reverse topological order, so we iterate in reverse. + // `commits` vector is in reverse topological order, so we iterate in + // reverse. let mut base_commit_map: HashMap> = HashMap::new(); for commit in commits.iter().rev() { let mut parent_commit_ids: IndexSet = IndexSet::new(); diff --git a/lib/src/fsmonitor.rs b/lib/src/fsmonitor.rs index 62fc639072f..f0740d3a151 100644 --- a/lib/src/fsmonitor.rs +++ b/lib/src/fsmonitor.rs @@ -199,8 +199,8 @@ pub mod watchman { resolved_root, }; - // Registering the trigger causes an unconditional evaluation of the query, so - // test if it is already registered first. + // Registering the trigger causes an unconditional evaluation of the + // query, so test if it is already registered first. if !config.register_trigger { monitor.unregister_trigger().await?; } else if !monitor.is_trigger_registered().await? { @@ -248,9 +248,10 @@ pub mod watchman { let clock = Clock(clock); if is_fresh_instance { // The Watchman documentation states that if it was a fresh - // instance, we need to delete any tree entries that didn't appear - // in the returned list of changed files. For now, the caller will - // handle this by manually crawling the working copy again. + // instance, we need to delete any tree entries that didn't + // appear in the returned list of changed files. + // For now, the caller will handle this by + // manually crawling the working copy again. Ok((clock, None)) } else { let paths = files diff --git a/lib/src/git.rs b/lib/src/git.rs index 5c3c178f453..98db75cbf92 100644 --- a/lib/src/git.rs +++ b/lib/src/git.rs @@ -438,7 +438,8 @@ fn resolve_git_ref_to_commit_id( ) -> Option { let mut peeling_ref = Cow::Borrowed(git_ref); - // Try fast path if we have a candidate id which is known to be a commit object. + // Try fast path if we have a candidate id which is known to be a commit + // object. if let Some(known_oid) = known_commit_oid { let raw_ref = &git_ref.inner; if let Some(oid) = raw_ref.target.try_id() @@ -449,13 +450,13 @@ fn resolve_git_ref_to_commit_id( if let Some(oid) = raw_ref.peeled && oid == known_oid { - // Perhaps an annotated tag stored in packed-refs file, and pointing to the - // already known target commit. + // Perhaps an annotated tag stored in packed-refs file, and pointing + // to the already known target commit. return Some(oid); } - // A tag (according to ref name.) Try to peel one more level. This is slightly - // faster than recurse into into_fully_peeled_id(). If we recorded a tag oid, we - // could skip this at all. + // A tag (according to ref name.) Try to peel one more level. This is + // slightly faster than recurse into into_fully_peeled_id(). If + // we recorded a tag oid, we could skip this at all. if raw_ref.peeled.is_none() && git_ref.name().as_bstr().starts_with(b"refs/tags/") { let maybe_tag = git_ref .try_id() @@ -464,11 +465,12 @@ fn resolve_git_ref_to_commit_id( if let Some(oid) = maybe_tag.as_ref().and_then(|tag| tag.target_id().ok()) { let oid = oid.detach(); if oid == known_oid { - // An annotated tag pointing to the already known target commit. + // An annotated tag pointing to the already known target + // commit. return Some(oid); } - // Unknown id. Recurse from the current state. A tag may point to - // non-commit object. + // Unknown id. Recurse from the current state. A tag may point + // to non-commit object. peeling_ref.to_mut().inner.target = gix::refs::Target::Object(oid); } } @@ -713,8 +715,9 @@ async fn import_refs_inner( .merge_local_bookmark(symbol.name, base_target, &new_remote_ref.target) .await?; } - // Remote-tracking branch is the last known state of the branch in the remote. - // It shouldn't diverge even if we had inconsistent view. + // Remote-tracking branch is the last known state of the branch in the + // remote. It shouldn't diverge even if we had inconsistent + // view. mut_repo.set_remote_bookmark(symbol, new_remote_ref); } for update in &changed_remote_tags { @@ -865,7 +868,8 @@ async fn record_synthetic_predecessors( // Predecessors are recorded only for newly imported commits to prevent // cycles in the evolution graph. While this restriction can be lifted // later, note that the existing predecessor chain may be more detailed - // than "imported from Git" if the original commits were created locally. + // than "imported from Git" if the original commits were created + // locally. for new_commit_id in new_commit_ids .iter() .filter(|&id| imported_commit_ids.contains(id)) @@ -903,7 +907,8 @@ fn diff_refs_to_import( .git_refs() .iter() .filter_map(|(full_name, target)| { - // TODO: or clean up invalid ref in case it was stored due to historical bug? + // TODO: or clean up invalid ref in case it was stored due to + // historical bug? let (kind, symbol) = parse_git_ref(full_name).expect("stored git ref should be parsable"); git_ref_filter(kind, symbol).then_some((full_name.as_ref(), target)) @@ -1051,8 +1056,8 @@ fn collect_changed_refs_to_import( if new_target != *old_git_target { changed_git_refs.push((full_name.to_owned(), new_target.clone())); } - // TODO: Make it configurable which remotes are publishing and update public - // heads here. + // TODO: Make it configurable which remotes are publishing and update + // public heads here. let old_remote_ref = known_remote_refs .remove(&symbol) .unwrap_or_else(|| RemoteRef::absent_ref()); @@ -1487,8 +1492,8 @@ fn copy_exportable_local_bookmarks_to_remote_view( .view() .local_remote_bookmarks(remote) .filter_map(|(name, targets)| { - // TODO: filter out untracked bookmarks (if we add support for untracked @git - // bookmarks) + // TODO: filter out untracked bookmarks (if we add support for + // untracked @git bookmarks) let old_target = &targets.remote_ref.target; let new_target = targets.local_target; (!new_target.has_conflict() && old_target != new_target).then_some((name, new_target)) @@ -1514,7 +1519,8 @@ fn copy_exportable_local_tags_to_remote_view( .view() .local_remote_tags(remote) .filter_map(|(name, targets)| { - // TODO: filter out untracked tags (if we add support for untracked @git tags) + // TODO: filter out untracked tags (if we add support for untracked + // @git tags) let old_target = &targets.remote_ref.target; let new_target = targets.local_target; (!new_target.has_conflict() && old_target != new_target).then_some((name, new_target)) @@ -1537,8 +1543,9 @@ fn diff_refs_to_export( root_commit_id: &CommitId, git_ref_filter: impl Fn(GitRefKind, RemoteRefSymbol<'_>) -> bool, ) -> AllRefsToExport { - // Local targets will be copied to the "git" remote if successfully exported. So - // the local refs are considered to be the new "git" remote refs. + // Local targets will be copied to the "git" remote if successfully + // exported. So the local refs are considered to be the new "git" remote + // refs. let mut all_bookmark_targets: HashMap = itertools::chain( view.local_bookmarks().map(|(name, target)| { @@ -1610,8 +1617,9 @@ fn collect_changed_refs_to_export( let old_oid = if let Some(id) = old_target.as_normal() { Some(owned_oid_from_commit_id(id)) } else if old_target.has_conflict() { - // The old git ref should only be a conflict if there were concurrent import - // operations while the value changed. Don't overwrite these values. + // The old git ref should only be a conflict if there were + // concurrent import operations while the value changed. + // Don't overwrite these values. failed.push((symbol.to_owned(), FailedRefExportReason::ConflictedOldState)); continue; } else { @@ -1881,8 +1889,8 @@ pub async fn reset_head( mut_repo.set_git_head_target(workspace_name, new_head_target); } - // If there is an ongoing operation (merge, rebase, etc.), we need to clean it - // up. + // If there is an ongoing operation (merge, rebase, etc.), we need to clean + // it up. if git_repo.state().is_some() { clear_operation_state(&git_repo)?; } @@ -1929,21 +1937,23 @@ async fn reset_index( wc_commit: &Commit, ) -> Result<(), GitResetHeadError> { let parent_tree = wc_commit.parent_tree(repo).await?; - // Use the merged parent tree as the Git index, allowing `git diff` to show the - // same changes as `jj diff`. If the merged parent tree has conflicts, then the - // Git index will also be conflicted. + // Use the merged parent tree as the Git index, allowing `git diff` to show + // the same changes as `jj diff`. If the merged parent tree has + // conflicts, then the Git index will also be conflicted. let mut index = if let Some(tree_id) = parent_tree.tree_ids().as_resolved() { if tree_id == repo.store().empty_tree_id() { - // If the tree is empty, gix can fail to load the object (since Git doesn't - // require the empty tree to actually be present in the object database), so we - // just use an empty index directly. + // If the tree is empty, gix can fail to load the object (since Git + // doesn't require the empty tree to actually be present + // in the object database), so we just use an empty + // index directly. gix::index::File::from_state( gix::index::State::new(git_repo.object_hash()), git_repo.index_path(), ) } else { - // If the parent tree is resolved, we can use gix's `index_from_tree` method. - // This is more efficient than iterating over the tree and adding each entry. + // If the parent tree is resolved, we can use gix's + // `index_from_tree` method. This is more efficient than + // iterating over the tree and adding each entry. git_repo .index_from_tree(&gix::ObjectId::from_bytes_or_panic(tree_id.as_bytes())) .map_err(GitResetHeadError::from_git)? @@ -1955,8 +1965,8 @@ async fn reset_index( let wc_tree = wc_commit.tree(); update_intent_to_add_impl(git_repo, &mut index, &parent_tree, &wc_tree).await?; - // Match entries in the new index with entries in the old index, and copy stat - // information if the entry didn't change. + // Match entries in the new index with entries in the old index, and copy + // stat information if the entry didn't change. if let Some(old_index) = git_repo.try_index().map_err(GitResetHeadError::from_git)? { index .entries_mut_with_paths() @@ -1986,47 +1996,50 @@ fn build_index_from_merged_tree( git_repo.index_path(), ); - let mut push_index_entry = - |path: &RepoPath, maybe_entry: &Option, stage: gix::index::entry::Stage| { - let Some(entry) = maybe_entry else { - return; - }; + let mut push_index_entry = |path: &RepoPath, + maybe_entry: &Option, + stage: gix::index::entry::Stage| { + let Some(entry) = maybe_entry else { + return; + }; - let (id, mode) = match entry { - TreeValue::File { - id, - executable, - copy_id: _, - } => { - if *executable { - (id.as_bytes(), gix::index::entry::Mode::FILE_EXECUTABLE) - } else { - (id.as_bytes(), gix::index::entry::Mode::FILE) - } - } - TreeValue::Symlink(id) => (id.as_bytes(), gix::index::entry::Mode::SYMLINK), - TreeValue::Tree(_) => { - // This case is only possible if there is a file-directory conflict, since - // `MergedTree::entries` handles the recursion otherwise. We only materialize a - // file in the working copy for file-directory conflicts, so we don't add the - // tree to the index here either. - return; + let (id, mode) = match entry { + TreeValue::File { + id, + executable, + copy_id: _, + } => { + if *executable { + (id.as_bytes(), gix::index::entry::Mode::FILE_EXECUTABLE) + } else { + (id.as_bytes(), gix::index::entry::Mode::FILE) } - TreeValue::GitSubmodule(id) => (id.as_bytes(), gix::index::entry::Mode::COMMIT), - }; + } + TreeValue::Symlink(id) => (id.as_bytes(), gix::index::entry::Mode::SYMLINK), + TreeValue::Tree(_) => { + // This case is only possible if there is a file-directory + // conflict, since `MergedTree::entries` handles + // the recursion otherwise. We only materialize a + // file in the working copy for file-directory conflicts, so we + // don't add the tree to the index here either. + return; + } + TreeValue::GitSubmodule(id) => (id.as_bytes(), gix::index::entry::Mode::COMMIT), + }; - let path = BStr::new(path.as_internal_file_string()); + let path = BStr::new(path.as_internal_file_string()); - // It is safe to push the entry because we ensure that we only add each path to - // a stage once, and we sort the entries after we finish adding them. - index.dangerously_push_entry( - gix::index::entry::Stat::default(), - gix::ObjectId::from_bytes_or_panic(id), - gix::index::entry::Flags::from_stage(stage), - mode, - path, - ); - }; + // It is safe to push the entry because we ensure that we only add each + // path to a stage once, and we sort the entries after we finish + // adding them. + index.dangerously_push_entry( + gix::index::entry::Stat::default(), + gix::ObjectId::from_bytes_or_panic(id), + gix::index::entry::Flags::from_stage(stage), + mode, + path, + ); + }; let mut has_many_sided_conflict = false; @@ -2044,12 +2057,14 @@ fn build_index_from_merged_tree( push_index_entry(&path, base, gix::index::entry::Stage::Base); push_index_entry(&path, right, gix::index::entry::Stage::Theirs); } else { - // We can't represent many-sided conflicts in the Git index, so just add the - // first side as staged. This is preferable to adding the first 2 sides as a - // conflict, since some tools rely on being able to resolve conflicts using the - // index, which could lead to an incorrect conflict resolution if the index - // didn't contain all of the conflict sides. Instead, we add a dummy conflict of - // a file named ".jj-do-not-resolve-this-conflict" to prevent the user from + // We can't represent many-sided conflicts in the Git index, so just + // add the first side as staged. This is preferable to + // adding the first 2 sides as a conflict, since some + // tools rely on being able to resolve conflicts using the + // index, which could lead to an incorrect conflict resolution if + // the index didn't contain all of the conflict sides. + // Instead, we add a dummy conflict of a file named + // ".jj-do-not-resolve-this-conflict" to prevent the user from // accidentally committing the conflict markers. has_many_sided_conflict = true; push_index_entry( @@ -2060,12 +2075,13 @@ fn build_index_from_merged_tree( } } - // Required after `dangerously_push_entry` for correctness. We use do a lookup - // in the index after this, so it must be sorted before we do the lookup. + // Required after `dangerously_push_entry` for correctness. We use do a + // lookup in the index after this, so it must be sorted before we do the + // lookup. index.sort_entries(); - // If the conflict had an unrepresentable conflict and the dummy file path isn't - // already added in the index, add a dummy file as a conflict. + // If the conflict had an unrepresentable conflict and the dummy file path + // isn't already added in the index, add a dummy file as a conflict. if has_many_sided_conflict && index .entry_index_by_path(INDEX_DUMMY_CONFLICT_FILE.into()) @@ -2083,8 +2099,8 @@ fn build_index_from_merged_tree( gix::index::entry::Mode::FILE, INDEX_DUMMY_CONFLICT_FILE.into(), ); - // We need to sort again for correctness before writing the index file since we - // added a new entry. + // We need to sort again for correctness before writing the index file + // since we added a new entry. index.sort_entries(); } @@ -2159,7 +2175,8 @@ async fn update_intent_to_add_impl( } if !added_paths.is_empty() { - // We need to write the empty blob, otherwise `jj util gc` will report an error. + // We need to write the empty blob, otherwise `jj util gc` will report + // an error. let empty_blob = git_repo .write_blob(b"") .map_err(GitResetHeadError::from_git)? @@ -3189,8 +3206,8 @@ impl<'a> GitFetch<'a> { return Err(GitFetchError::RejectedUpdates(names)); } - // Even if git fetch has --prune, if a branch is not found it will not be - // pruned on fetch + // Even if git fetch has --prune, if a branch is not found it will not + // be pruned on fetch self.git_ctx.spawn_branch_prune(&branches_to_prune)?; self.fetched.push(FetchedRefs { diff --git a/lib/src/git_backend.rs b/lib/src/git_backend.rs index edf870bcc3c..e4e3fd995ac 100644 --- a/lib/src/git_backend.rs +++ b/lib/src/git_backend.rs @@ -309,12 +309,14 @@ impl GitBackend { .map_err(GitBackendInitError::Path)?; let target_path = store_path.join("git_target"); let git_repo_path = if cfg!(windows) && git_repo_path.is_relative() { - // When a repository is created in Windows, format the path with *forward - // slashes* and not backwards slashes. This makes it possible to use the same - // repository under Windows Subsystem for Linux. + // When a repository is created in Windows, format the path with + // *forward slashes* and not backwards slashes. This + // makes it possible to use the same repository under + // Windows Subsystem for Linux. // - // This only works for relative paths. If the path is absolute, there's not much - // we can do, and it simply won't work inside and outside WSL at the same time. + // This only works for relative paths. If the path is absolute, + // there's not much we can do, and it simply won't work + // inside and outside WSL at the same time. file_util::slash_path(git_repo_path) } else { git_repo_path.into() @@ -466,8 +468,9 @@ impl GitBackend { .extra_metadata_store .save_table(mut_table) .map_err(GitBackendError::WriteMetadata)?; - // Since the parent table was the head, saved table are likely to be new head. - // If it's not, cache will be reloaded when entry can't be found. + // Since the parent table was the head, saved table are likely to be new + // head. If it's not, cache will be reloaded when entry can't be + // found. *self.cached_extra_metadata.lock().unwrap() = Some(table); Ok(()) } @@ -496,8 +499,9 @@ impl GitBackend { .edit_references(head_ids.iter().copied().map(to_no_gc_ref_update)) .map_err(|err| BackendError::Other(Box::new(err)))?; - // These commits are imported from Git. Make our change ids persist (otherwise - // future write_commit() could reassign new change id.) + // These commits are imported from Git. Make our change ids persist + // (otherwise future write_commit() could reassign new change + // id.) tracing::debug!( heads_count = head_ids.len(), "import extra metadata entries" @@ -586,8 +590,8 @@ impl GitBackend { let locked_repo = self.lock_git_repo(); if !locked_repo.objects.exists(&oid) { - // reuse the precomputed hash, since Gitoxide provides an API for it (otherwise - // Gitoxide recomputes it). + // reuse the precomputed hash, since Gitoxide provides an API for it + // (otherwise Gitoxide recomputes it). let write_oid = locked_repo .objects .write_buf_with_known_id(gix::objs::Kind::Blob, bytes, oid) @@ -694,7 +698,8 @@ fn commit_from_git_without_root_parent( // shallow commits don't have parents their parents actually fetched, so we // discard them here - // TODO: This causes issues when a shallow repository is deepened/unshallowed + // TODO: This causes issues when a shallow repository is + // deepened/unshallowed let parents = if is_shallow { vec![] } else { @@ -708,12 +713,12 @@ fn commit_from_git_without_root_parent( let conflict_labels = extract_conflict_labels_from_commit(&commit); // Conflicted commits written before we started using the `jj:trees` header // (~March 2024) may have the root trees stored in the extra metadata table - // instead. For such commits, we'll update the root tree later when we read the - // extra metadata. + // instead. For such commits, we'll update the root tree later when we read + // the extra metadata. let root_tree = extract_root_tree_from_commit(&commit) .map_err(|()| to_read_object_err("Invalid jj:trees header", id))?; - // Use lossy conversion as commit message with "mojibake" is still better than - // nothing. + // Use lossy conversion as commit message with "mojibake" is still better + // than nothing. // TODO: what should we do with commit.encoding? let description = String::from_utf8_lossy(commit.message).into_owned(); let author = signature_from_git(commit.author().map_err(decode_err)?); @@ -721,8 +726,8 @@ fn commit_from_git_without_root_parent( // If the commit is signed, extract both the signature and the signed data // (which is the commit buffer with the gpgsig header omitted). - // We have to re-parse the raw commit data because gix CommitRef does not give - // us the sogned data, only the signature. + // We have to re-parse the raw commit data because gix CommitRef does not + // give us the sogned data, only the signature. // Ideally, we could use try_to_commit_ref_iter at the beginning of this // function and extract everything from that. For now, this works let secure_sig = commit @@ -1053,8 +1058,9 @@ fn import_extra_metadata_entries_from_heads( .map_err(|err| map_not_found_err(err, &id))?; let is_shallow = shallow_roots.contains(&id); // TODO(#1624): Should we read the root tree here and check if it has a - // `.jjconflict-...` entries? That could happen if the user used `git` to e.g. - // change the description of a commit with tree-level conflicts. + // `.jjconflict-...` entries? That could happen if the user used `git` + // to e.g. change the description of a commit with tree-level + // conflicts. let commit = commit_from_git_without_root_parent(&id, &git_object, is_shallow)?; mut_table.add_entry(id.to_bytes(), serialize_extras(&commit)); work_ids.extend( @@ -1304,10 +1310,10 @@ impl Backend for GitBackend { if let Some(extras) = table.get_value(id.as_bytes()) { deserialize_extras(&mut commit, extras); } else { - // TODO: Remove this hack and map to ObjectNotFound error if we're sure that - // there are no reachable ancestor commits without extras metadata. Git commits - // imported by jj < 0.8.0 might not have extras (#924). - // https://github.com/jj-vcs/jj/issues/2343 + // TODO: Remove this hack and map to ObjectNotFound error if we're + // sure that there are no reachable ancestor commits + // without extras metadata. Git commits imported by jj < + // 0.8.0 might not have extras (#924). https://github.com/jj-vcs/jj/issues/2343 tracing::info!("unimported Git commit found"); self.import_head_commits([id])?; let table = self.cached_extra_metadata_table()?; @@ -1341,10 +1347,11 @@ impl Backend for GitBackend { let mut parents = SmallVec::new(); for parent_id in &contents.parents { if *parent_id == self.root_commit_id { - // Git doesn't have a root commit, so if the parent is the root commit, we don't - // add it to the list of parents to write in the Git commit. We also check that - // there are no other parents since Git cannot represent a merge between a root - // commit and another commit. + // Git doesn't have a root commit, so if the parent is the root + // commit, we don't add it to the list of + // parents to write in the Git commit. We also check that + // there are no other parents since Git cannot represent a merge + // between a root commit and another commit. if contents.parents.len() > 1 { return Err(BackendError::Unsupported( "The Git backend does not support creating merge commits with the root \ @@ -1358,7 +1365,8 @@ impl Backend for GitBackend { } let mut extra_headers: Vec<(BString, BString)> = vec![]; if !contents.conflict_labels.is_resolved() { - // Labels cannot contain '\n' since we use it as a separator in the header. + // Labels cannot contain '\n' since we use it as a separator in the + // header. assert!( contents .conflict_labels @@ -1397,12 +1405,13 @@ impl Backend for GitBackend { let extras = serialize_extras(&contents); - // If two writers write commits of the same id with different metadata, they - // will both succeed and the metadata entries will be "merged" later. Since - // metadata entry is keyed by the commit id, one of the entries would be lost. - // To prevent such race condition locally, we extend the scope covered by the - // table lock. This is still racy if multiple machines are involved and the - // repository is rsync-ed. + // If two writers write commits of the same id with different metadata, + // they will both succeed and the metadata entries will be + // "merged" later. Since metadata entry is keyed by the commit + // id, one of the entries would be lost. To prevent such race + // condition locally, we extend the scope covered by the + // table lock. This is still racy if multiple machines are involved and + // the repository is rsync-ed. let (table, table_lock) = self.read_extra_metadata_table_locked()?; let id = loop { let mut commit = gix::objs::Commit { @@ -1459,14 +1468,14 @@ impl Backend for GitBackend { } }; - // Everything up to this point had no permanent effect on the repo except - // GC-able objects + // Everything up to this point had no permanent effect on the repo + // except GC-able objects locked_repo .edit_reference(to_no_gc_ref_update(&id)) .map_err(|err| BackendError::Other(Box::new(err)))?; - // Update the signature to match the one that was actually written to the object - // store + // Update the signature to match the one that was actually written to + // the object store contents.committer.timestamp.timestamp = MillisSinceEpoch(committer.time.seconds * 1000); let mut mut_table = table.start_mutation(); mut_table.add_entry(id.to_bytes(), extras); @@ -1935,8 +1944,8 @@ mod tests { let backend = GitBackend::init_external(&settings, store_path, git_repo.path())?; - // read_commit() without import_head_commits() works as of now. This might be - // changed later. + // read_commit() without import_head_commits() works as of now. This + // might be changed later. assert!( backend .read_commit(&CommitId::from_bytes(git_commit_id.as_bytes())) @@ -2060,8 +2069,8 @@ mod tests { @r#"Some(ChangeId("efbc06dc4721683f2a45568dbda31e99"))"# ); - // We only look at the first change id if multiple are present, so this should - // error + // We only look at the first change id if multiple are present, so this + // should error let commit = indoc! {b" tree 126799bf8058d1b5c531e93079f4fe79733920dd parent bd50783bdf38406dd6143475cd1a3c27938db2ee @@ -2291,8 +2300,8 @@ mod tests { backend.write_commit(commit, None).block_on() }; - // When writing a tree-level conflict, the root tree on the git side has the - // individual trees as subtrees. + // When writing a tree-level conflict, the root tree on the git side has + // the individual trees as subtrees. let read_commit_id = write_commit(commit.clone())?.0; let read_commit = backend.read_commit(&read_commit_id).block_on()?; assert_eq!(read_commit, commit); @@ -2350,8 +2359,8 @@ mod tests { assert_eq!(entry.mode().value(), 0o100644); assert!(iter.next().is_none()); - // When writing a single tree using the new format, it's represented by a - // regular git tree. + // When writing a single tree using the new format, it's represented by + // a regular git tree. commit.root_tree = Merge::resolved(create_tree(5)); let read_commit_id = write_commit(commit.clone())?.0; let read_commit = backend.read_commit(&read_commit_id).block_on()?; @@ -2476,8 +2485,8 @@ mod tests { let (commit_id1, mut commit2) = write_commit(commit1)?; commit2.predecessors.push(commit_id1.clone()); - // `write_commit` should prevent the ids from being the same by changing the - // committer timestamp of the commit it actually writes. + // `write_commit` should prevent the ids from being the same by changing + // the committer timestamp of the commit it actually writes. let (commit_id2, mut actual_commit2) = write_commit(commit2.clone())?; // The returned matches the ID assert_eq!(backend.read_commit(&commit_id2).block_on()?, actual_commit2); diff --git a/lib/src/git_subprocess.rs b/lib/src/git_subprocess.rs index a2acf811d5c..61dd85d4deb 100644 --- a/lib/src/git_subprocess.rs +++ b/lib/src/git_subprocess.rs @@ -106,10 +106,10 @@ impl GitSubprocessContext { git_cmd.creation_flags(CREATE_NO_WINDOW); } - // TODO: here we are passing the full path to the git_dir, which can lead to UNC - // bugs in Windows. The ideal way to do this is to pass the workspace - // root to Command::current_dir and then pass a relative path to the git - // dir + // TODO: here we are passing the full path to the git_dir, which can + // lead to UNC bugs in Windows. The ideal way to do this is to + // pass the workspace root to Command::current_dir and then pass + // a relative path to the git dir git_cmd // The gitconfig-controlled automated spawning of the macOS `fsmonitor--daemon` // can cause strange behavior with certain subprocess operations. @@ -179,7 +179,8 @@ impl GitSubprocessContext { let mut command = self.create_command(); command.stdout(Stdio::piped()); // attempt to prune stale refs with --prune - // --no-write-fetch-head ensures our request is invisible to other parties + // --no-write-fetch-head ensures our request is invisible to other + // parties command.args(["fetch", "--porcelain", "--prune", "--no-write-fetch-head"]); if callback.needs_progress() { command.arg("--progress"); @@ -263,8 +264,8 @@ impl GitSubprocessContext { ) -> Result { let mut command = self.create_command(); command.stdout(Stdio::piped()); - // Currently jj does not support commit hooks, so we prevent git from running - // them + // Currently jj does not support commit hooks, so we prevent git from + // running them // // https://github.com/jj-vcs/jj/issues/3577 and https://github.com/jj-vcs/jj/issues/405 // offer more context diff --git a/lib/src/graph_dominators.rs b/lib/src/graph_dominators.rs index f359e56693b..f5619c484a5 100644 --- a/lib/src/graph_dominators.rs +++ b/lib/src/graph_dominators.rs @@ -218,8 +218,8 @@ where rev_adj[node_to_id[v]].push(node_to_id[u]); } - // Find the immediate dominators for each node using the Cooper-Harvey-Kennedy - // iterative algorithm. + // Find the immediate dominators for each node using the + // Cooper-Harvey-Kennedy iterative algorithm. let immediate_dominators = Self::calculate_immediate_dominators(&rev_adj); Ok(Self { @@ -265,8 +265,8 @@ where return Err(DominatorFinderError::EmptyTargetSet); } - // The closest common dominator of a set of nodes is the lowest common ancestor - // of those nodes in the dominator tree. + // The closest common dominator of a set of nodes is the lowest common + // ancestor of those nodes in the dominator tree. let closest_common_dominator = Self::find_lowest_common_ancestor(&target_ids, &self.immediate_dominators); @@ -274,33 +274,34 @@ where Ok(self.id_to_node[closest_common_dominator].clone()) } - // Applies the Cooper-Harvey-Kennedy iterative algorithm to find the immediate - // dominators for each node in the graph. + // Applies the Cooper-Harvey-Kennedy iterative algorithm to find the + // immediate dominators for each node in the graph. // See http://www.hipersoft.rice.edu/grads/publications/dom14.pdf for details on how this function works. fn calculate_immediate_dominators(rev_adj: &[Vec]) -> Vec { // Step 1: Compute Dominators on Reverse Graph let num_nodes = rev_adj.len(); let start_node_id = num_nodes - 1; - // We hold the immediate dominator for each node in the following vector, in - // index position (the kth entry is the immediate dominator of the node with ID - // k). We initialize the immediate dominator of every node to usize::MAX to - // represent that those nodes are not processed yet. Once a node is - // processed, its immediate dominator is guaranteed to be a valid node - // index. + // We hold the immediate dominator for each node in the following + // vector, in index position (the kth entry is the immediate + // dominator of the node with ID k). We initialize the immediate + // dominator of every node to usize::MAX to represent that those + // nodes are not processed yet. Once a node is processed, its + // immediate dominator is guaranteed to be a valid node index. let mut immediate_dominators: Vec = vec![usize::MAX; num_nodes]; - // NOTE: technically speaking the immediate dominator is NOT defined for the - // start node, but it is convenient for the algorithm to set it to itself; this - // is consistent with the literature and specifically with - // Cooper-Harvey-Kennedy. + // NOTE: technically speaking the immediate dominator is NOT defined for + // the start node, but it is convenient for the algorithm to set + // it to itself; this is consistent with the literature and + // specifically with Cooper-Harvey-Kennedy. immediate_dominators[start_node_id] = start_node_id; loop { - // Each iteration of the loop processes all nodes in reverse postorder, trying - // to improve the immediate dominator for each node. The loop continues until we - // have an iteration where no immediate dominator is changed. Note that the - // entries in immediate_dominators are only guaranteed to be correct when the - // loop terminates. + // Each iteration of the loop processes all nodes in reverse + // postorder, trying to improve the immediate dominator + // for each node. The loop continues until we + // have an iteration where no immediate dominator is changed. Note + // that the entries in immediate_dominators are only + // guaranteed to be correct when the loop terminates. let mut changed = false; // Iterate in reverse postorder, skipping the start node. @@ -314,8 +315,10 @@ where continue; } if new_idom == usize::MAX { - // This is the first predecessor of u that has been processed so far. We use - // it as the starting point for finding the new "improved" immediate + // This is the first predecessor of u that has been + // processed so far. We use + // it as the starting point for finding the new + // "improved" immediate // dominator for u. new_idom = p; } else { @@ -324,8 +327,9 @@ where } } if new_idom == usize::MAX { - // None of the predecessors of u have been processed yet. That's fine, we will - // try again of the next iteration of the outer loop. + // None of the predecessors of u have been processed yet. + // That's fine, we will try again of the + // next iteration of the outer loop. continue; } if immediate_dominators[u] != new_idom { @@ -341,9 +345,9 @@ where } } - // At this point we know the immediate dominator of every node, but we keep the - // Option wrapper so that we can use the intersect function during - // find_lowest_common_ancestor. + // At this point we know the immediate dominator of every node, but we + // keep the Option wrapper so that we can use the intersect + // function during find_lowest_common_ancestor. immediate_dominators } @@ -443,7 +447,8 @@ where let mut values = vec![]; let mut futures = vec![]; - // 1. Filter out nodes already in the map and create futures for new nodes. + // 1. Filter out nodes already in the map and create futures for new + // nodes. for node in nodes { match self.node_values.get(node) { Some(value) => { @@ -544,7 +549,8 @@ where V: Hash + Eq, VF: AsyncFn(&N) -> Result, { - // First compute the values of all final nodes asynchronously and concurrently. + // First compute the values of all final nodes asynchronously and + // concurrently. let final_values = value_cache .get_values(final_nodes) .await @@ -557,8 +563,9 @@ where )); } [final_value] => { - // Optimization: if all final nodes have the same value, that value is the - // closest common dominator. There is no need to build the value flow graph. + // Optimization: if all final nodes have the same value, that + // value is the closest common dominator. There + // is no need to build the value flow graph. return Ok(final_value.clone()); } _ => {} @@ -578,20 +585,22 @@ where .await .map_err(|err| FindDominatorValueError::ValueFnError(err))?; - // NOTE: at this point we could compare the cardinality of the value set versus - // the number of nodes: if equal then we know that every node has a - // different value, and it is tempting to conclude that the result should be - // `start_value` (because the shape of the value flow graph is identical - // to the shape of the original flow graph). That is not always correct, + // NOTE: at this point we could compare the cardinality of the value set + // versus the number of nodes: if equal then we know that every + // node has a different value, and it is tempting to conclude + // that the result should be `start_value` (because the shape of + // the value flow graph is identical to the shape of the + // original flow graph). That is not always correct, // consider this example with start node A and final nodes C and D: // // A(1) -> B(2) -> C(3) // \--> D(4) // - // However, IF start node IS the closest common dominator of the original graph - // (it is not in the example above) then the answer would be `start_value`; - // so IF we knew that to be true we could skip building the value flow graph and - // running the dominator algorithm in the value flow graph. + // However, IF start node IS the closest common dominator of the + // original graph (it is not in the example above) then the + // answer would be `start_value`; so IF we knew that to be true + // we could skip building the value flow graph and running the + // dominator algorithm in the value flow graph. let value_flow_graph = self.create_value_flow_graph(&value_cache.node_values); let dominator_finder = DominatorFinder::calculate(&value_flow_graph)?; @@ -629,9 +638,9 @@ where // Push the node back onto the stack with processed = true. // It will be popped and yielded AFTER its children. stack.push((node, true)); - // Push the neighbors onto the stack with processed = false. The neighbors are - // added in reverse order, so they are processed in the - // original order. + // Push the neighbors onto the stack with processed = false. The + // neighbors are added in reverse order, so they are + // processed in the original order. for neighbor in neighbors.rev() { if !visited.contains(&neighbor) { stack.push((neighbor, false)); @@ -1582,8 +1591,8 @@ mod tests { #[test] fn test_find_dominator_value_with_invalid_flow_graph() { - // Invalid flow graph: A(1) -> B(1), C(2) -> D(2) (C and D are not reachable - // from A). + // Invalid flow graph: A(1) -> B(1), C(2) -> D(2) (C and D are not + // reachable from A). let simple_graph = SimpleDirectedGraph::new([("A", "B"), ("C", "D")]); let flow_graph = FlowGraph::new(simple_graph, "A"); let value_fn = async |node: &&str| match *node { @@ -1591,12 +1600,14 @@ mod tests { "C" | "D" => Ok(2), _ => Err("Unknown node".to_string()), }; - // Todo: the flow_graph is invalid because C and D are not reachable from A, so - // ideally find_dominator_value should return UnreachableNodesInFlowGraph, but - // the optimizations in find_dominator_value currently cause it to - // return the start value. The best way to fix this is to calculate (and store) - // the post-order in FlowGraph::new, that way we could not possibly construct an - // invalid flow graph. This is not a big concern in practice though. + // Todo: the flow_graph is invalid because C and D are not reachable + // from A, so ideally find_dominator_value should return + // UnreachableNodesInFlowGraph, but the optimizations in + // find_dominator_value currently cause it to return the start + // value. The best way to fix this is to calculate (and store) + // the post-order in FlowGraph::new, that way we could not possibly + // construct an invalid flow graph. This is not a big concern in + // practice though. assert_eq!( flow_graph .find_dominator_value(&["B", "D"], value_fn) diff --git a/lib/src/id_prefix.rs b/lib/src/id_prefix.rs index 9ddbccb5e3c..b43bba41095 100644 --- a/lib/src/id_prefix.rs +++ b/lib/src/id_prefix.rs @@ -172,8 +172,9 @@ impl IdPrefixIndex<'_> { // Fall back to resolving in entire repo } PrefixResolution::SingleMatch(id) => { - // The disambiguation set may be loaded from a different repo, - // and contain a commit that doesn't exist in the current repo. + // The disambiguation set may be loaded from a different + // repo, and contain a commit that + // doesn't exist in the current repo. if repo.index().has_id(&id).block_on()? { return Ok(PrefixResolution::SingleMatch(id)); } else { @@ -412,7 +413,8 @@ where let min_bytes = prefix.min_prefix_bytes(); if min_bytes.is_empty() { - // We consider an empty prefix ambiguous even if the index has a single entry. + // We consider an empty prefix ambiguous even if the index has a + // single entry. return PrefixResolution::AmbiguousMatch; } @@ -421,9 +423,10 @@ where (entry.to_key(), entry) }; if min_bytes.len() > N { - // If the min prefix (including odd byte) is longer than the stored short keys, - // we are sure that min_bytes[..N] does not include the odd byte. Use it to - // take contiguous range, then filter by (longer) prefix.matches(). + // If the min prefix (including odd byte) is longer than the stored + // short keys, we are sure that min_bytes[..N] does not + // include the odd byte. Use it to take contiguous + // range, then filter by (longer) prefix.matches(). let short_bytes = unwrap_as_short_key(min_bytes); let pos = self.index.partition_point(|(s, _)| s < short_bytes); let range = self.index[pos..] @@ -433,8 +436,9 @@ where .filter(|(k, _)| prefix.matches(k)); collect(range, entry_mapper) } else { - // Otherwise, use prefix.matches() to deal with odd byte. Since the prefix is - // covered by short key width, we're sure that the matching prefixes are sorted. + // Otherwise, use prefix.matches() to deal with odd byte. Since the + // prefix is covered by short key width, we're sure that + // the matching prefixes are sorted. let pos = self.index.partition_point(|(s, _)| &s[..] < min_bytes); let range = self.index[pos..] .iter() @@ -529,9 +533,10 @@ where } pub fn shortest_unique_prefix_len(&self) -> usize { - // Since entries having the same short key aren't sorted by the full-length key, - // we need to scan all entries in the current chunk, plus left/right neighbors. - // Typically, current.len() is 1. + // Since entries having the same short key aren't sorted by the + // full-length key, we need to scan all entries in the current + // chunk, plus left/right neighbors. Typically, current.len() is + // 1. let short_key = unwrap_as_short_key(self.key.as_bytes()); let left = self.pos.checked_sub(1).map(|p| &self.index[p]); let (current, right) = { @@ -540,8 +545,8 @@ where (&range[..count], range.get(count)) }; - // Left/right neighbors should have unique short keys. For the current chunk, - // we need to look up full-length keys. + // Left/right neighbors should have unique short keys. For the current + // chunk, we need to look up full-length keys. let unique_len = |a: &[u8], b: &[u8]| hex_util::common_hex_len(a, b) + 1; let neighbor_lens = left .iter() @@ -552,7 +557,8 @@ where .map(|(_, p)| self.source.entry_at(p).to_key()) .filter(|key| key != self.key) .map(|key| unique_len(key.as_bytes(), self.key.as_bytes())); - // Even if the key is the only one in the index, we require at least one digit. + // Even if the key is the only one in the index, we require at least one + // digit. neighbor_lens.chain(current_lens).max().unwrap_or(1) } } @@ -669,8 +675,8 @@ mod tests { resolve_prefix(&HexPrefix::try_from_hex("0001").unwrap()), PrefixResolution::NoMatch, ); - // For short key "00", ["0000", "0099", "0099"] would match. We shouldn't - // break at "009".matches("0000"). + // For short key "00", ["0000", "0099", "0099"] would match. We + // shouldn't break at "009".matches("0000"). assert_eq!( resolve_prefix(&HexPrefix::try_from_hex("009").unwrap()), PrefixResolution::SingleMatch((ChangeId::from_hex("0099"), vec![1, 2])), diff --git a/lib/src/local_working_copy.rs b/lib/src/local_working_copy.rs index 87da9f57800..3aef9284830 100644 --- a/lib/src/local_working_copy.rs +++ b/lib/src/local_working_copy.rs @@ -135,11 +135,12 @@ fn symlink_target_convert_to_store(path: &Path) -> Option> { if std::path::MAIN_SEPARATOR == '/' { Some(Cow::Borrowed(path)) } else { - // When storing the symlink target on Windows, convert "\" to "/", so that the - // symlink remains valid on Unix. + // When storing the symlink target on Windows, convert "\" to "/", so + // that the symlink remains valid on Unix. // // Note that we don't use std::path to handle the conversion, because it - // performs poorly with Windows verbatim paths like \\?\Global\C:\file.txt. + // performs poorly with Windows verbatim paths like + // \\?\Global\C:\file.txt. Some(Cow::Owned(path.replace(std::path::MAIN_SEPARATOR_STR, "/"))) } } @@ -148,8 +149,8 @@ fn symlink_target_convert_to_disk(path: &str) -> PathBuf { let path = if std::path::MAIN_SEPARATOR == '/' { Cow::Borrowed(path) } else { - // Use the main separator to reformat the input path to avoid creating a broken - // symlink with the incorrect separator "/". + // Use the main separator to reformat the input path to avoid creating a + // broken symlink with the incorrect separator "/". // // See https://github.com/jj-vcs/jj/issues/6934 for the relevant bug. Cow::Owned(path.replace('/', std::path::MAIN_SEPARATOR_STR)) @@ -339,8 +340,9 @@ impl FileState { fn for_symlink(metadata: &Metadata) -> Result { // When using fscrypt, the reported size is not the content size. So if - // we were to record the content size here (like we do for regular files), we - // would end up thinking the file has changed every time we snapshot. + // we were to record the content size here (like we do for regular + // files), we would end up thinking the file has changed every + // time we snapshot. Ok(Self { file_type: FileType::Symlink, mtime: mtime_from_metadata(metadata)?, @@ -861,8 +863,8 @@ fn reject_reserved_existing_path(disk_path: &Path) -> Result<(), CheckoutError> })? else { // If the existing disk_path pointed to the reserved path, we would have - // gotten an identity back. Since we got nothing, the file does not exist - // and cannot be a reserved path name. + // gotten an identity back. Since we got nothing, the file does not + // exist and cannot be a reserved path name. return Ok(()); }; @@ -895,9 +897,10 @@ fn reject_reserved_existing_file_identity( } })? else { - // If the existing disk_path pointed to the reserved path, we would have - // gotten an identity back. Since we got nothing, the file does not exist - // and cannot be a reserved path name. + // If the existing disk_path pointed to the reserved path, we would + // have gotten an identity back. Since we got nothing, + // the file does not exist and cannot be a reserved path + // name. continue; }; @@ -1210,8 +1213,8 @@ impl TreeState { // update own write time while we before we rename it, so we know // there is no unknown data in it self.update_own_mtime(); - // TODO: Retry if persisting fails (it will on Windows if the file happened to - // be open for read). + // TODO: Retry if persisting fails (it will on Windows if the file + // happened to be open for read). let target_path = self.state_path.join("tree_state"); persist_temp_file(temp_file, &target_path).map_err(|source| { TreeStateError::PersistTreeState { @@ -1458,7 +1461,8 @@ impl TreeState { .iter() .filter_map(|path| RepoPathBuf::from_relative_path(path).ok()) .collect_vec(); - // .gitignore changes require rescanning parent directories to pick up newly + // .gitignore changes require rescanning parent + // directories to pick up newly // unignored files. let gitignore_prefixes = repo_paths .iter() @@ -1832,8 +1836,9 @@ impl FileSnapshotter<'_> { false } Some(current_file_state) => { - // If the file's mtime was set at the same time as this state file's own mtime, - // then we don't know if the file was modified before or after this state file. + // If the file's mtime was set at the same time as this state + // file's own mtime, then we don't know if the + // file was modified before or after this state file. new_file_state.is_clean(current_file_state) && current_file_state.mtime < self.tree_state.own_mtime } @@ -1924,7 +1929,8 @@ impl FileSnapshotter<'_> { copy_id, })) } else if let Some(old_file_ids) = current_tree_values.to_file_merge() { - // Safe to unwrap because the copy id exists exactly on the file variant + // Safe to unwrap because the copy id exists exactly on the file + // variant let copy_id_merge = current_tree_values.to_copy_id_merge().unwrap(); let copy_id = copy_id_merge .resolve_trivial(SameChange::Accept) @@ -1965,7 +1971,8 @@ impl FileSnapshotter<'_> { .await?; match new_file_ids.into_resolved() { Ok(file_id) => { - // On Windows, we preserve the executable bit from the merged trees. + // On Windows, we preserve the executable bit from the + // merged trees. let executable = exec_bit.for_tree_value(self.tree_state.exec_policy, || { current_tree_values .to_executable_merge() @@ -2088,10 +2095,11 @@ impl TreeState { })?; set_executable(exec_bit, disk_path) .map_err(|err| checkout_error_for_stat_error(err, disk_path))?; - // Read the file state from the file descriptor. That way, know that the file - // exists and is of the expected type, and the stat information is most likely - // accurate, except for other processes modifying the file concurrently (The - // mtime is set at write time and won't change when we close the file.) + // Read the file state from the file descriptor. That way, know that the + // file exists and is of the expected type, and the stat + // information is most likely accurate, except for other + // processes modifying the file concurrently (The mtime is set + // at write time and won't change when we close the file.) let metadata = file .metadata() .map_err(|err| checkout_error_for_stat_error(err, disk_path))?; @@ -2103,13 +2111,13 @@ impl TreeState { let target = symlink_target_convert_to_disk(&target); if cfg!(windows) { - // On Windows, "/" can't be part of valid file name, and "/" is also not a valid - // separator for the symlink target. See an example of this issue in - // https://github.com/jj-vcs/jj/issues/6934. + // On Windows, "/" can't be part of valid file name, and "/" is also + // not a valid separator for the symlink target. See an + // example of this issue in https://github.com/jj-vcs/jj/issues/6934. // - // We use debug_assert_* instead of assert_* because we want to avoid panic in - // release build, and we are sure that we shouldn't create invalid symlinks in - // tests. + // We use debug_assert_* instead of assert_* because we want to + // avoid panic in release build, and we are sure that we + // shouldn't create invalid symlinks in tests. debug_assert_ne!( target.as_os_str().to_str().map(|path| path.contains('/')), Some(true), @@ -2216,8 +2224,8 @@ impl TreeState { new_tree: &MergedTree, matcher: &dyn Matcher, ) -> Result { - // TODO: maybe it's better not include the skipped counts in the "intended" - // counts + // TODO: maybe it's better not include the skipped counts in the + // "intended" counts let mut stats = CheckoutStats { updated_files: 0, added_files: 0, @@ -2256,26 +2264,29 @@ impl TreeState { return Ok(()); } - // This path and the previous one we did work for may have a common prefix. We - // can adjust the "working copy" path to the parent directory which we know - // is already created. If there is no common prefix, this will by default use + // This path and the previous one we did work for may have a common + // prefix. We can adjust the "working copy" path to the + // parent directory which we know is already created. If + // there is no common prefix, this will by default use // RepoPath::root() as the common prefix. let (common_prefix, adjusted_diff_file_path) = path.split_common_prefix(&prev_created_path); let disk_path = if adjusted_diff_file_path.is_root() { - // The path being "root" here implies that the entire path has already been - // created. + // The path being "root" here implies that the entire path has + // already been created. // - // e.g we may have have already processed a path like: "foo/bar/baz" and this is + // e.g we may have have already processed a path like: + // "foo/bar/baz" and this is // our `prev_created_path`. // // and the current path is: // "foo/bar" // - // This results in a common prefix of "foo/bar" with empty string for the - // remainder since its entire prefix has already been created. - // This means that we _dont_ need to create its parent dirs + // This results in a common prefix of "foo/bar" with empty + // string for the remainder since its entire + // prefix has already been created. This means + // that we _dont_ need to create its parent dirs // either. path.to_fs_path(self.working_copy_path())? @@ -2283,8 +2294,9 @@ impl TreeState { let adjusted_working_copy_path = common_prefix.to_fs_path(self.working_copy_path())?; - // Create parent directories no matter if after.is_present(). This - // ensures that the path never traverses symlinks. + // Create parent directories no matter if after.is_present(). + // This ensures that the path never traverses + // symlinks. let Some(disk_path) = create_parent_dirs(&adjusted_working_copy_path, adjusted_diff_file_path)? else { @@ -2341,11 +2353,13 @@ impl TreeState { // executable bit. let get_prev_exec = || self.file_states().get_exec_bit(&path); - // TODO: Check that the file has not changed before overwriting/removing it. + // TODO: Check that the file has not changed before + // overwriting/removing it. let file_state = match after { MaterializedTreeValue::Absent | MaterializedTreeValue::AccessDenied(_) => { - // Reset the previous path to avoid scenarios where this path is deleted, - // then on the next iteration recreation is skipped because of this + // Reset the previous path to avoid scenarios where this + // path is deleted, then on the next + // iteration recreation is skipped because of this // optimization. prev_created_path = RepoPathBuf::root(); @@ -2439,17 +2453,19 @@ impl TreeState { }) .buffered(self.store.concurrency()); - // If a conflicted file didn't change between the two trees, but the conflict - // labels did, we still need to re-materialize it in the working copy. We don't - // need to do this if the conflicts have different numbers of sides though since - // these conflicts are considered different, so they will be materialized by + // If a conflicted file didn't change between the two trees, but the + // conflict labels did, we still need to re-materialize it in + // the working copy. We don't need to do this if the conflicts + // have different numbers of sides though since these conflicts + // are considered different, so they will be materialized by // `MergedTree::diff_stream_for_file_system` already. let mut conflicts_to_rematerialize: HashMap = if old_tree.tree_ids().num_sides() == new_tree.tree_ids().num_sides() && old_tree.labels() != new_tree.labels() { - // TODO: it might be better to use an async stream here and merge it with the - // other diff stream, but it could be difficult since the diff stream is not + // TODO: it might be better to use an async stream here and + // merge it with the other diff stream, but it + // could be difficult since the diff stream is not // sorted in the same order as the conflicts iterator. new_tree .conflicts_matching(matcher) @@ -2473,8 +2489,8 @@ impl TreeState { process_diff_entry(path, conflict, materialized).await?; } - // We need to re-sort the changed file states since we may have inserted a - // conflicted file out of order. + // We need to re-sort the changed file states since we may have + // inserted a conflicted file out of order. changed_file_states.sort_unstable_by(|(path1, _), (path2, _)| path1.cmp(path2)); } @@ -2517,7 +2533,8 @@ impl TreeState { } }, Err(_values) => { - // TODO: Try to set the executable bit based on the conflict + // TODO: Try to set the executable bit based on the + // conflict FileType::Normal { exec_bit: ExecBit(false), } @@ -2603,8 +2620,8 @@ impl CheckoutState { .as_file_mut() .write_all(&proto.encode_to_vec()) .map_err(|err| wrap_err(err.into()))?; - // TODO: Retry if persisting fails (it will on Windows if the file happened to - // be open for read). + // TODO: Retry if persisting fails (it will on Windows if the file + // happened to be open for read). persist_temp_file(temp_file, state_path.join("checkout")) .map_err(|err| wrap_err(err.into()))?; Ok(()) @@ -2909,8 +2926,8 @@ impl LockedWorkingCopy for LockedLocalWorkingCopy { &mut self, new_sparse_patterns: Vec, ) -> Result { - // TODO: Write a "pending_checkout" file with new sparse patterns so we can - // continue an interrupted update if we find such a file. + // TODO: Write a "pending_checkout" file with new sparse patterns so we + // can continue an interrupted update if we find such a file. let stats = self .wc .tree_state_mut()? diff --git a/lib/src/lock/unix.rs b/lib/src/lock/unix.rs index b2b9d55a5cc..68ca084c0c3 100644 --- a/lib/src/lock/unix.rs +++ b/lib/src/lock/unix.rs @@ -71,7 +71,8 @@ impl FileLock { match rustix::fs::fstat(&file) { Ok(stat) => { if stat.st_nlink == 0 { - // Lockfile was deleted, probably by the previous holder's `Drop` impl; + // Lockfile was deleted, probably by the previous + // holder's `Drop` impl; // create a new one so our ownership is visible, // rather than hidden in an unlinked file. Not // always necessary, since the previous holder might @@ -106,9 +107,9 @@ impl Drop for FileLock { fn drop(&mut self) { // Removing the file isn't strictly necessary, but reduces confusion. std::fs::remove_file(&self.path).ok(); - // Unblock any processes that tried to acquire the lock while we held it. - // They're responsible for creating and locking a new lockfile, since we - // just deleted this one. + // Unblock any processes that tried to acquire the lock while we held + // it. They're responsible for creating and locking a new + // lockfile, since we just deleted this one. rustix::fs::flock(&self.file, FlockOperation::Unlock).ok(); } } diff --git a/lib/src/merged_tree.rs b/lib/src/merged_tree.rs index d9b186eade0..3c1471a6600 100644 --- a/lib/src/merged_tree.rs +++ b/lib/src/merged_tree.rs @@ -150,16 +150,18 @@ impl MergedTree { assert!(!self.labels.has_labels()); Merge::resolved(label) } else if self.labels.has_labels() { - // If the merge is conflicted and it already has labels, then we want to use - // those labels instead of the provided label. This ensures that rebasing - // conflicted commits keeps meaningful labels. + // If the merge is conflicted and it already has labels, then we + // want to use those labels instead of the provided + // label. This ensures that rebasing conflicted commits + // keeps meaningful labels. let labels = self.labels.as_merge(); assert_eq!(labels.num_sides(), self.tree_ids.num_sides()); labels.map(|label| label.as_str()) } else { - // If the merge is conflicted but it doesn't have labels (e.g. conflicts created - // before labels were added), then we use empty strings to indicate missing - // labels. We could consider using `label` for all the sides instead, but it + // If the merge is conflicted but it doesn't have labels (e.g. + // conflicts created before labels were added), then we + // use empty strings to indicate missing labels. We + // could consider using `label` for all the sides instead, but it // might be confusing. Merge::repeated("", self.tree_ids.num_sides()) } @@ -169,18 +171,19 @@ impl MergedTree { /// automatically resolved and leaving the rest unresolved. pub async fn resolve(self) -> BackendResult { let merged = merge_trees(&self.store, self.tree_ids).await?; - // If the result can be resolved, then `merge_trees()` above would have returned - // a resolved merge. However, that function will always preserve the arity of - // conflicts it cannot resolve. So we simplify the conflict again - // here to possibly reduce a complex conflict to a simpler one. + // If the result can be resolved, then `merge_trees()` above would have + // returned a resolved merge. However, that function will always + // preserve the arity of conflicts it cannot resolve. So we + // simplify the conflict again here to possibly reduce a complex + // conflict to a simpler one. let (simplified_labels, simplified) = if merged.is_resolved() { (ConflictLabels::unlabeled(), merged) } else { self.labels.simplify_with(&merged) }; - // If debug assertions are enabled, check that the merge was idempotent. In - // particular, that this last simplification doesn't enable further automatic - // resolutions + // If debug assertions are enabled, check that the merge was idempotent. + // In particular, that this last simplification doesn't enable + // further automatic resolutions if cfg!(debug_assertions) { let re_merged = merge_trees(&self.store, simplified.clone()).await.unwrap(); debug_assert_eq!(re_merged, simplified); @@ -572,13 +575,16 @@ impl Iterator for ConflictIterator<'_> { if let Some((path, tree_values)) = top.entries.pop() { match tree_values.to_tree_merge(&self.store, &path).block_on() { Ok(Some(trees)) => { - // If all sides are trees or missing, descend into the merged tree + // If all sides are trees or missing, descend into the + // merged tree self.stack.push(ConflictsDirItem::new(&trees, self.matcher)); } Ok(None) => { - // Otherwise this is a conflict between files, trees, etc. If they could - // be automatically resolved, they should have been when the top-level - // tree conflict was written, so we assume that they can't be. + // Otherwise this is a conflict between files, trees, + // etc. If they could + // be automatically resolved, they should have been when + // the top-level tree conflict + // was written, so we assume that they can't be. return Some((path, Ok(tree_values))); } Err(err) => { @@ -649,8 +655,8 @@ impl TreeDiffDir { let path = dir.join(name); let tree_before = diff.before.is_tree(); let tree_after = diff.after.is_tree(); - // Check if trees and files match, but only if either side is a tree or a file - // (don't query the matcher unnecessarily). + // Check if trees and files match, but only if either side is a tree + // or a file (don't query the matcher unnecessarily). let tree_matches = (tree_before || tree_after) && !matcher.visit(&path).is_nothing(); let file_matches = (!tree_before || !tree_after) && matcher.matches(&path); @@ -813,8 +819,8 @@ impl<'matcher> TreeDiffStreamImpl<'matcher> { let path = dir.join(basename); let tree_before = diff.before.is_tree(); let tree_after = diff.after.is_tree(); - // Check if trees and files match, but only if either side is a tree or a file - // (don't query the matcher unnecessarily). + // Check if trees and files match, but only if either side is a tree + // or a file (don't query the matcher unnecessarily). let tree_matches = (tree_before || tree_after) && !self.matcher.visit(&path).is_nothing(); let file_matches = (!tree_before || !tree_after) && self.matcher.matches(&path); @@ -834,7 +840,8 @@ impl<'matcher> TreeDiffStreamImpl<'matcher> { continue; } - // If the path was a tree on either side of the diff, read those trees. + // If the path was a tree on either side of the diff, read those + // trees. if tree_matches { let before_tree_future = Self::trees(self.store.clone(), path.clone(), before.cloned()); @@ -882,8 +889,9 @@ impl<'matcher> TreeDiffStreamImpl<'matcher> { } } - // If none of the futures have been polled and returned `Poll::Pending`, we must - // not return. If we did, nothing would call the waker so we might never get + // If none of the futures have been polled and returned + // `Poll::Pending`, we must not return. If we did, + // nothing would call the waker so we might never get // polled again. if all_pending || (some_pending && self.items.len() >= self.max_queued_items) { return; @@ -899,10 +907,11 @@ impl Stream for TreeDiffStreamImpl<'_> { // Go through all pending tree futures and poll them. self.poll_tree_futures(cx); - // Now emit the first file, or the first tree that completed with an error + // Now emit the first file, or the first tree that completed with an + // error if let Some((path, _)) = self.items.first_key_value() { - // Check if there are any pending trees before this item that we need to finish - // polling before we can emit this item. + // Check if there are any pending trees before this item that we + // need to finish polling before we can emit this item. if let Some((dir, _)) = self.pending_trees.first_key_value() && dir < path { @@ -966,8 +975,9 @@ impl Stream for DiffStreamForFileSystem<'_> { Some(next) => Some(next), None => ready!(self.inner.as_mut().poll_next(cx)), } { - // Filter out changes where neither side (before or after) is_file_like. - // This ensures we only process file-level changes and transitions. + // Filter out changes where neither side (before or after) + // is_file_like. This ensures we only process file-level + // changes and transitions. if let Ok(diff) = &next.values && !diff.before.is_file_like() && !diff.after.is_file_like() @@ -975,8 +985,9 @@ impl Stream for DiffStreamForFileSystem<'_> { continue; } - // If there's a held file "foo" and the next item to emit is not "foo/...", then - // we must be done with the "foo/" directory and it's time to emit "foo" as a + // If there's a held file "foo" and the next item to emit is not + // "foo/...", then we must be done with the "foo/" + // directory and it's time to emit "foo" as a // removed file. if let Some(held_entry) = self .held_file diff --git a/lib/src/merged_tree_builder.rs b/lib/src/merged_tree_builder.rs index cde2bfbc816..4e50541ef9c 100644 --- a/lib/src/merged_tree_builder.rs +++ b/lib/src/merged_tree_builder.rs @@ -64,10 +64,11 @@ impl MergedTreeBuilder { let labels = if labels.num_sides() == Some(new_tree_ids.num_sides()) { labels } else { - // If the number of sides changed, we need to discard the conflict labels, - // otherwise `MergedTree::new` would panic. - // TODO: we should preserve conflict labels when setting conflicted tree values - // originating from a different tree than the base tree. + // If the number of sides changed, we need to discard the conflict + // labels, otherwise `MergedTree::new` would panic. + // TODO: we should preserve conflict labels when setting conflicted + // tree values originating from a different tree than + // the base tree. ConflictLabels::unlabeled() }; let (labels, new_tree_ids) = labels.simplify_with(&new_tree_ids); @@ -96,25 +97,26 @@ impl MergedTreeBuilder { for (path, values) in self.overrides { match values.into_resolved() { Ok(value) => { - // This path was overridden with a resolved value. Apply that to all - // builders. + // This path was overridden with a resolved value. Apply + // that to all builders. for builder in &mut tree_builders { builder.set_or_remove(path.clone(), value.clone()); } } Err(mut values) => { values.pad_to(num_sides, &None); - // This path was overridden with a conflicted value. Apply each term to - // its corresponding builder. + // This path was overridden with a conflicted value. Apply + // each term to its corresponding + // builder. for (builder, value) in zip(&mut tree_builders, values) { builder.set_or_remove(path.clone(), value); } } } } - // TODO: This can be made more efficient. If there's a single resolved conflict - // in `dir/file`, we shouldn't have to write the `dir/` and root trees more than - // once. + // TODO: This can be made more efficient. If there's a single resolved + // conflict in `dir/file`, we shouldn't have to write the `dir/` + // and root trees more than once. let tree_ids = try_join_all( tree_builders .into_iter() diff --git a/lib/src/op_heads_store.rs b/lib/src/op_heads_store.rs index 7e8ea3c38a7..e576b32efa1 100644 --- a/lib/src/op_heads_store.rs +++ b/lib/src/op_heads_store.rs @@ -126,8 +126,8 @@ where }, )) .await?; - // Remove ancestors so we don't create merge operation with an operation and its - // ancestor + // Remove ancestors so we don't create merge operation with an operation and + // its ancestor let op_head_ids_before: HashSet<_> = op_heads.iter().map(|op| op.id().clone()).collect(); let filtered_op_heads = dag_walk_async::heads( op_heads, diff --git a/lib/src/op_walk.rs b/lib/src/op_walk.rs index 03bf76ae8d9..797d1684039 100644 --- a/lib/src/op_walk.rs +++ b/lib/src/op_walk.rs @@ -268,8 +268,8 @@ pub fn walk_ancestors( .cloned() .map(OperationByEndTime) .collect_vec(); - // Lazily load operations based on timestamp-based heuristic. This works so long - // as the operation history is mostly linear. + // Lazily load operations based on timestamp-based heuristic. This works so + // long as the operation history is mostly linear. dag_walk_async::topo_order_reverse_lazy( head_ops.into_iter().map(Ok), |OperationByEndTime(op)| op.id().clone(), @@ -304,8 +304,8 @@ pub fn walk_ancestors_range( collect_ancestors_until_roots(&mut start_ops, unwanted_ids) }; - // Lazily load operations based on timestamp-based heuristic. This works so long - // as the operation history is mostly linear. + // Lazily load operations based on timestamp-based heuristic. This works so + // long as the operation history is mostly linear. let trailing_stream = dag_walk_async::topo_order_reverse_lazy( start_ops.into_iter().map(Ok), |OperationByEndTime(op)| op.id().clone(), diff --git a/lib/src/refs.rs b/lib/src/refs.rs index aa466a640db..483b3a80dbd 100644 --- a/lib/src/refs.rs +++ b/lib/src/refs.rs @@ -172,8 +172,8 @@ async fn find_pair_to_remove( // "adds" is an ancestor of the other, then pick the descendant. for (add_index1, add1) in conflict.adds().enumerate() { for (add_index2, add2) in conflict.adds().enumerate().skip(add_index1 + 1) { - // TODO: Instead of relying on the list order, maybe ((add1, add2), remove) - // combination should be somehow weighted? + // TODO: Instead of relying on the list order, maybe ((add1, add2), + // remove) combination should be somehow weighted? let (add_index, add_id) = match (add1, add2) { (Some(id1), Some(id2)) if id1 == id2 => (add_index1, id1), (Some(id1), Some(id2)) if index.is_ancestor(id1, id2).await? => (add_index1, id1), diff --git a/lib/src/repo.rs b/lib/src/repo.rs index 651e8f2057f..d1c8fac5cd0 100644 --- a/lib/src/repo.rs +++ b/lib/src/repo.rs @@ -810,8 +810,8 @@ impl RepoLoader { // Caches the result of merging some operations. let mut merged_operations: HashMap, Operation> = HashMap::new(); - // Caches the result of op_walk::closest_common_ancestors invocations. Keyed by - // the arguments to that method. + // Caches the result of op_walk::closest_common_ancestors invocations. + // Keyed by the arguments to that method. let mut closest_common_ancestors: HashMap<_, Vec> = HashMap::new(); let mut tx = self.load_at(&operations[0]).await?.start_transaction(); @@ -827,8 +827,9 @@ impl RepoLoader { assert!(operations.len() > 1); assert!(index <= operations.len()); if index == operations.len() { - // We are done processing the operations, but there is more work on the stack. - // Commit the transaction and cache the result. + // We are done processing the operations, but there is more work + // on the stack. Commit the transaction and + // cache the result. let tx_description = transaction_description.map_or_else( || format!("merge {} operations", operations.len()), |tx_description| tx_description.to_string(), @@ -843,9 +844,9 @@ impl RepoLoader { let other_op = &operations[index]; - // Get the ancestor operations between the operations we have merged so far - // (represented by `tx.parent_ops()`) and the next operation to merge - // (`other_op`). + // Get the ancestor operations between the operations we have merged + // so far (represented by `tx.parent_ops()`) and the + // next operation to merge (`other_op`). let ancestor_ops = match closest_common_ancestors .entry((to_operation_ids(tx.parent_ops()), other_op.id().clone())) { @@ -865,28 +866,31 @@ impl RepoLoader { // There is a single common ancestor. Some(ancestor_op) } else { - // There are multiple common ancestors, check to see if we have cached their - // merge result. + // There are multiple common ancestors, check to see if we have + // cached their merge result. let ancestor_op_ids = ancestor_ops.iter().map(|op| op.id().clone()).collect_vec(); merged_operations.get(&ancestor_op_ids) }; if let Some(merged_ancestor_op) = ancestor_op { - // We have the merge of the ancestor operations. We can proceed to merge with - // other_op. + // We have the merge of the ancestor operations. We can proceed + // to merge with other_op. tx.merge_operation(merged_ancestor_op, other_op).await?; num_rebased += tx.repo_mut().rebase_descendants().await?; - // Push state on the stack to continue merging the rest of the operations. + // Push state on the stack to continue merging the rest of the + // operations. stack.push((index + 1, operations, tx)); continue; } // We have to merge the ancestor ops. - // We first push the current state to the stack so that after we merge the - // ancestor ops, we can continue merging the rest of the operations. + // We first push the current state to the stack so that after we + // merge the ancestor ops, we can continue merging the + // rest of the operations. stack.push((index, operations, tx)); - // Then we push the ancestor ops to the stack so that we can merge them first. - // We need to start a separate transaction for this. + // Then we push the ancestor ops to the stack so that we can merge + // them first. We need to start a separate transaction + // for this. let new_tx = self.load_at(&ancestor_ops[0]).await?.start_transaction(); stack.push((1, ancestor_ops.clone(), new_tx)); } @@ -1264,7 +1268,8 @@ impl MutableRepo { Some(Rewrite::Abandoned(_)) ); let new_wc_commit = if !abandoned_old_commit { - // We arbitrarily pick a new working-copy commit among the candidates. + // We arbitrarily pick a new working-copy commit among the + // candidates. self.store().get_commit_async(&new_commit_ids[0]).await? } else if let Some(commit) = recreated_wc_commits.get(old_commit_id) { commit.clone() @@ -1356,8 +1361,9 @@ impl MutableRepo { let to_visit_set: HashSet = to_visit.iter().map(|commit| commit.id().clone()).collect(); let mut visited = HashSet::new(); - // Calculate an order where we rebase parents first, but if the parents were - // rewritten, make sure we rebase the rewritten parent first. + // Calculate an order where we rebase parents first, but if the parents + // were rewritten, make sure we rebase the rewritten parent + // first. let store = self.store(); dag_walk_async::topo_order_reverse( to_visit.into_iter().map(Ok), @@ -1464,12 +1470,13 @@ impl MutableRepo { callback(rewriter).await?; } self.update_rewritten_references(options).await?; - // Since we didn't necessarily visit all descendants of rewritten commits (e.g. - // if they were rewritten in the callback), there can still be commits left to - // rebase, so we don't clear `parent_mapping` here. - // TODO: Should we make this stricter? We could check that there were no - // rewrites before this function was called, and we can check that only - // commits in the `to_visit` set were added by the callback. Then we + // Since we didn't necessarily visit all descendants of rewritten + // commits (e.g. if they were rewritten in the callback), there + // can still be commits left to rebase, so we don't clear + // `parent_mapping` here. TODO: Should we make this stricter? We + // could check that there were no rewrites before this function + // was called, and we can check that only commits in the + // `to_visit` set were added by the callback. Then we // could clear `parent_mapping` here and not have to scan it again at // the end of the transaction when we call `rebase_descendants()`. @@ -1665,8 +1672,9 @@ impl MutableRepo { .get_commit_async(&wc_commit_id) .await .map_err(EditCommitError::WorkingCopyCommitNotFound)?; - // Call normalized_heads() prior to .view().heads().contains() because - // the caller expects non-head revisions don't exist in the set. + // Call normalized_heads() prior to .view().heads().contains() + // because the caller expects non-head revisions don't + // exist in the set. self.normalize_heads().await?; if wc_commit.is_discardable(self).await? && !is_commit_referenced(&self.view, wc_commit.id()) @@ -1696,9 +1704,9 @@ impl MutableRepo { /// should exist in the store. pub async fn add_heads(&mut self, heads: &[Commit]) -> BackendResult<()> { let current_heads = self.view.heads(); - // Use incremental update for common case of adding a single commit on top a - // current head. TODO: Also use incremental update when adding a single - // commit on top a non-head. + // Use incremental update for common case of adding a single commit on + // top a current head. TODO: Also use incremental update when + // adding a single commit on top a non-head. match heads { [] => {} [head] @@ -1954,10 +1962,11 @@ impl MutableRepo { base_repo: &ReadonlyRepo, other_repo: &ReadonlyRepo, ) -> Result<(), RepoLoaderError> { - // First, merge the index, so we can take advantage of a valid index when - // merging the view. Merging in base_repo's index isn't typically - // necessary, but it can be if base_repo is ahead of either self or other_repo - // (e.g. because we're undoing an operation that hasn't been published). + // First, merge the index, so we can take advantage of a valid index + // when merging the view. Merging in base_repo's index isn't + // typically necessary, but it can be if base_repo is ahead of + // either self or other_repo (e.g. because we're undoing an + // operation that hasn't been published). self.index.merge_in(base_repo.readonly_index())?; self.index.merge_in(other_repo.readonly_index())?; @@ -1981,11 +1990,12 @@ impl MutableRepo { let own_heads = self.view().heads().iter().cloned().collect_vec(); let other_heads = other.heads().iter().cloned().collect_vec(); - // HACK: Don't walk long ranges of commits to find rewrites when using other - // custom implementations. The only custom index implementation we're currently - // aware of is Google's. That repo has too high commit rate for it to be - // feasible to walk all added and removed commits. - // TODO: Fix this somehow. Maybe a method on `Index` to find rewritten commits + // HACK: Don't walk long ranges of commits to find rewrites when using + // other custom implementations. The only custom index + // implementation we're currently aware of is Google's. That + // repo has too high commit rate for it to be feasible to walk + // all added and removed commits. TODO: Fix this somehow. Maybe + // a method on `Index` to find rewritten commits // given `base_heads`, `own_heads` and `other_heads`? if self.is_backed_by_default_index() { self.record_rewrites(&base_heads, &own_heads).await?; diff --git a/lib/src/revset.rs b/lib/src/revset.rs index fb96220f2e5..c3091768cea 100644 --- a/lib/src/revset.rs +++ b/lib/src/revset.rs @@ -126,8 +126,8 @@ pub enum RevsetEvaluationError { } impl RevsetEvaluationError { - // TODO: Create a higher-level error instead of putting non-BackendErrors in a - // BackendError + // TODO: Create a higher-level error instead of putting non-BackendErrors in + // a BackendError pub fn into_backend_error(self) -> BackendError { match self { Self::Backend(err) => err, @@ -1087,9 +1087,10 @@ static BUILTIN_FUNCTION_MAP: LazyLock> = LazyLock: }); map.insert("mine", |_diagnostics, function, context| { function.expect_no_arguments()?; - // Email address domains are inherently case‐insensitive, and the local‐parts - // are generally (although not universally) treated as case‐insensitive too, so - // we use a case‐insensitive match here. + // Email address domains are inherently case‐insensitive, and the + // local‐parts are generally (although not universally) treated + // as case‐insensitive too, so we use a case‐insensitive match + // here. let pattern = StringPattern::exact_i(context.user_email); let predicate = RevsetFilterPredicate::AuthorEmail(StringExpression::pattern(pattern)); Ok(RevsetExpression::filter(predicate)) @@ -2055,8 +2056,8 @@ fn sort_intersection_by_key( expression: &Arc>, mut get_key: impl FnMut(&RevsetExpression) -> T, ) -> TransformedExpression { - // We only want to compute the key for `expression` once instead of computing it - // on every iteration. + // We only want to compute the key for `expression` once instead of + // computing it on every iteration. fn sort_intersection_helper( base: &Arc>, expression: &Arc>, @@ -2350,9 +2351,9 @@ fn fold_heads_range( fn to_filtered_range( expression: &Arc>, ) -> Option> { - // If the first expression is `ancestors(x)`, then we already know the range - // must be `none()..x`, since any roots would've been moved to the left by an - // earlier pass. + // If the first expression is `ancestors(x)`, then we already know the + // range must be `none()..x`, since any roots would've been + // moved to the left by an earlier pass. if let Ok(heads_and_parents_range) = ancestors_to_heads_and_parents_range(expression) { return Some(FilteredRange { roots: RevsetExpression::none(), @@ -2367,8 +2368,9 @@ fn fold_heads_range( if let Ok(roots) = ancestors_to_heads(complement) { Some(FilteredRange::new(roots)) } else { - // If the first expression is a non-ancestors negation, we still want to use - // `HeadsRange` since `~x` is equivalent to `::visible_heads() ~ x`. + // If the first expression is a non-ancestors negation, we + // still want to use `HeadsRange` since + // `~x` is equivalent to `::visible_heads() ~ x`. Some(FilteredRange::new(RevsetExpression::none()).add_filter(expression)) } } @@ -2437,7 +2439,8 @@ fn to_difference_range( }; let roots = ancestors_to_heads(complement).ok()?; // ::heads & ~(::roots) -> roots..heads - // ::heads & ~(::roots-) -> ::heads & ~ancestors(roots, 1..) -> roots-..heads + // ::heads & ~(::roots-) -> ::heads & ~ancestors(roots, 1..) -> + // roots-..heads Some(Arc::new(RevsetExpression::Range { roots, heads: heads.clone(), @@ -3237,7 +3240,8 @@ impl VisibilityResolutionContext<'_> { count: *count, }, RevsetExpression::Filter(_) | RevsetExpression::AsFilter(_) => { - // Top-level filter without intersection: e.g. "~author(_)" is represented as + // Top-level filter without intersection: e.g. "~author(_)" is + // represented as // `AsFilter(NotIn(Filter(Author(_))))`. ResolvedExpression::FilterWithin { candidates: self.resolve_all().into(), @@ -4806,8 +4810,9 @@ mod tests { let settings = insta_settings(); let _guard = settings.bind_to_scope(); - // Check that transform_expression_bottom_up() never rewrites enum variant - // (e.g. Range -> DagRange) nor reorders arguments unintentionally. + // Check that transform_expression_bottom_up() never rewrites enum + // variant (e.g. Range -> DagRange) nor reorders arguments + // unintentionally. insta::assert_debug_snapshot!( optimize(parse("parents(bookmarks() & all())")?), @r#" @@ -4979,7 +4984,8 @@ mod tests { } } - // transform_expression_bottom_up() should not recreate tree unnecessarily. + // transform_expression_bottom_up() should not recreate tree + // unnecessarily. let parsed = parse("foo-")?; let optimized = optimize(parsed.clone()); assert!(Arc::ptr_eq(&parsed, &optimized)); @@ -5076,7 +5082,8 @@ mod tests { ) "#); - // Binary difference operation should go through the same optimization passes. + // Binary difference operation should go through the same optimization + // passes. insta::assert_debug_snapshot!( optimize(parse("all() ~ foo")?), @r#"NotIn(CommitRef(Symbol("foo")))"#); @@ -5208,8 +5215,8 @@ mod tests { ) "#); - // Negated ancestors can be combined into a range regardless of intersection - // grouping order and intervening expressions. + // Negated ancestors can be combined into a range regardless of + // intersection grouping order and intervening expressions. insta::assert_debug_snapshot!(optimize(parse("foo ~ ::a & (::b & bar & ::c) & (baz ~ ::d)")?), @r#" Intersection( Intersection( @@ -5311,7 +5318,8 @@ mod tests { // '~empty()' -> '~~file(*)' -> 'file(*)' insta::assert_debug_snapshot!(optimize(parse("~empty()")?), @"Filter(File(All))"); - // '& baz' can be moved into the filter node, and form a difference node. + // '& baz' can be moved into the filter node, and form a difference + // node. insta::assert_debug_snapshot!( optimize(parse("(author_name(foo) & ~bar) & baz")?), @r#" Intersection( @@ -5960,9 +5968,9 @@ mod tests { } "#); - // TODO: Inner Descendants can be folded into DagRange. Perhaps, we can rewrite - // 'x::y' to 'x:: & ::y' first, so the common substitution rule can handle both - // 'x+::y' and 'x+ & ::y'. + // TODO: Inner Descendants can be folded into DagRange. Perhaps, we can + // rewrite 'x::y' to 'x:: & ::y' first, so the common + // substitution rule can handle both 'x+::y' and 'x+ & ::y'. insta::assert_debug_snapshot!(optimize(parse("(foo++)::bar")?), @r#" DagRange { roots: Descendants { @@ -6097,8 +6105,8 @@ mod tests { let settings = insta_settings(); let _guard = settings.bind_to_scope(); - // Negated ancestors and ancestors should be moved to the left, and other - // negations should be moved to the right. + // Negated ancestors and ancestors should be moved to the left, and + // other negations should be moved to the right. insta::assert_debug_snapshot!(optimize(parse("~a & ::b & ~::c & d ~ e & f & ::g & ~::h")?), @r#" Difference( Difference( @@ -6154,8 +6162,9 @@ mod tests { filter: All, } "#); - // It might be better to use `roots: Root`, but it would require adding a - // special case for `~root()`, and this should be similar in performance. + // It might be better to use `roots: Root`, but it would require adding + // a special case for `~root()`, and this should be similar in + // performance. insta::assert_debug_snapshot!(optimize(parse("heads(..)")?), @" HeadsRange { roots: None, @@ -6481,8 +6490,8 @@ mod tests { assert_eq!(format_symbol("foo\\\"bar"), r#""foo\\\"bar""#); assert_eq!(format_symbol("foo\nbar"), r#""foo\nbar""#); - // Some characters don't technically need escaping, but we escape them for - // clarity + // Some characters don't technically need escaping, but we escape them + // for clarity assert_eq!(format_symbol("foo\"bar"), r#""foo\"bar""#); assert_eq!(format_symbol("foo\\bar"), r#""foo\\bar""#); assert_eq!(format_symbol("foo\\\"bar"), r#""foo\\\"bar""#); diff --git a/lib/src/revset_parser.rs b/lib/src/revset_parser.rs index 163f6f2b585..a6c8c22d09a 100644 --- a/lib/src/revset_parser.rs +++ b/lib/src/revset_parser.rs @@ -1570,7 +1570,8 @@ mod tests { assert_eq!(parse_normalized("x|y&z"), parse_normalized("x|(y&z)")); assert_eq!(parse_normalized("x|y~z"), parse_normalized("x|(y~z)")); assert_eq!(parse_normalized("::&.."), parse_normalized("(::)&(..)")); - // Parse repeated "ancestors"/"descendants"/"dag range"/"range" operators + // Parse repeated "ancestors"/"descendants"/"dag range"/"range" + // operators assert_eq!( parse_into_kind("::foo::"), Err(RevsetParseErrorKind::SyntaxError) @@ -1639,8 +1640,8 @@ mod tests { parse_into_kind("::.."), Err(RevsetParseErrorKind::SyntaxError) ); - // Parse combinations of "parents"/"children" operators and the range operators. - // The former bind more strongly. + // Parse combinations of "parents"/"children" operators and the range + // operators. The former bind more strongly. assert_eq!(parse_normalized("foo-+"), parse_normalized("(foo-)+")); assert_eq!(parse_normalized("foo-::"), parse_normalized("(foo-)::")); assert_eq!(parse_normalized("::foo+"), parse_normalized("::(foo+)")); @@ -1730,7 +1731,8 @@ mod tests { parse_normalized("b|c") ); - // Infinite recursion, where the top-level error isn't of RecursiveAlias kind. + // Infinite recursion, where the top-level error isn't of RecursiveAlias + // kind. assert_eq!( *with_aliases([("A", "A")]).parse("A").unwrap_err().kind, RevsetParseErrorKind::InAliasExpansion("A".to_owned()) @@ -1792,7 +1794,8 @@ mod tests { parse_normalized("a") ); - // Infinite recursion, where the top-level error isn't of RecursiveAlias kind. + // Infinite recursion, where the top-level error isn't of RecursiveAlias + // kind. assert_eq!( *with_aliases([("P:x", "Q:x"), ("Q:x", "R:x"), ("R:x", "P:x")]) .parse("P:a") @@ -1921,7 +1924,8 @@ mod tests { } ); - // Infinite recursion, where the top-level error isn't of RecursiveAlias kind. + // Infinite recursion, where the top-level error isn't of RecursiveAlias + // kind. assert_eq!( *with_aliases([("F(x)", "G(x)"), ("G(x)", "H(x)"), ("H(x)", "F(x)")]) .parse("F(a)") diff --git a/lib/src/rewrite.rs b/lib/src/rewrite.rs index 7b777c88085..9af13b593a8 100644 --- a/lib/src/rewrite.rs +++ b/lib/src/rewrite.rs @@ -192,8 +192,8 @@ pub async fn restore_tree( let mut diff_stream = source.diff_stream(destination, matcher); let mut paths = Vec::new(); while let Some(entry) = diff_stream.next().await { - // TODO: We should be able to not traverse deeper in the diff if the matcher - // matches an entire subtree. + // TODO: We should be able to not traverse deeper in the diff if the + // matcher matches an entire subtree. paths.push(entry.path); } let matcher = FilesMatcher::new(paths); @@ -208,7 +208,8 @@ pub async fn restore_tree( let mut builder = MergedTreeBuilder::new(labeled_empty_tree); for (path, value) in tree.entries_matching(&matcher) { // TODO: if https://github.com/jj-vcs/jj/issues/4152 is implemented, we will need - // to expand resolved conflicts into `Merge::repeated(value, num_sides)`. + // to expand resolved conflicts into `Merge::repeated(value, + // num_sides)`. builder.set_or_remove(path, value?); } builder.write_tree().await @@ -216,8 +217,8 @@ pub async fn restore_tree( const RESTORE_BASE_LABEL: &str = "base files for restore"; - // To avoid confusion between the destination tree and the base tree, we add a - // prefix to the conflict labels of the base tree. + // To avoid confusion between the destination tree and the base tree, we add + // a prefix to the conflict labels of the base tree. let base_labels = ConflictLabels::from_merge(destination.labels().as_merge().map(|label| { if label.is_empty() || label.starts_with(RESTORE_BASE_LABEL) { label.clone() @@ -226,17 +227,17 @@ pub async fn restore_tree( } })); - // Merging the trees this way ensures that when restoring a conflicted file into - // a conflicted commit, we preserve the labels of both commits even if the - // commits had different conflict labels. The labels we add here for - // non-conflicted trees will generally not be visible to users since they will - // always be removed during simplification when materializing any individual - // file. However, they could be useful in the future if we add a command which - // shows the labels for all the sides of a conflicted commit, and they are also - // useful for debugging. - // TODO: using a merge is required for retaining conflict labels when restoring - // from/into conflicted trees, but maybe we could optimize the case where both - // trees are already resolved. + // Merging the trees this way ensures that when restoring a conflicted file + // into a conflicted commit, we preserve the labels of both commits even + // if the commits had different conflict labels. The labels we add here + // for non-conflicted trees will generally not be visible to users since + // they will always be removed during simplification when materializing + // any individual file. However, they could be useful in the future if + // we add a command which shows the labels for all the sides of a + // conflicted commit, and they are also useful for debugging. + // TODO: using a merge is required for retaining conflict labels when + // restoring from/into conflicted trees, but maybe we could optimize the + // case where both trees are already resolved. MergedTree::merge(Merge::from_vec(vec![ ( destination.clone(), @@ -419,8 +420,8 @@ impl<'repo> CommitRewriter<'repo> { .await?, ) }; - // Ensure we don't abandon commits with multiple parents (merge commits), even - // if they're empty. + // Ensure we don't abandon commits with multiple parents (merge + // commits), even if they're empty. if let [parent] = &new_parents[..] { let should_abandon = match empty { EmptyBehavior::Keep => false, @@ -469,7 +470,8 @@ pub async fn rebase_commit_with_options( mut rewriter: CommitRewriter<'_>, options: &RebaseOptions, ) -> BackendResult { - // If specified, don't create commit where one parent is an ancestor of another. + // If specified, don't create commit where one parent is an ancestor of + // another. if options.simplify_ancestor_merge { rewriter .simplify_ancestor_merge() @@ -721,8 +723,9 @@ pub async fn compute_move_commits( .map(|id| repo.store().get_commit_async(id)), ) .await?; - // We don't have to compute the internal parents for the connected target set, - // since the connected target set is the same as the target set. + // We don't have to compute the internal parents for the connected + // target set, since the connected target set is the + // same as the target set. connected_target_commits_internal_parents = HashMap::new(); target_roots = root_ids.iter().cloned().collect(); } @@ -745,8 +748,8 @@ pub async fn compute_move_commits( target_commits_external_parents.insert(commit.id().clone(), new_parents); } - // If the new parents include a commit in the target set, replace it with the - // commit's ancestors which are outside the set. + // If the new parents include a commit in the target set, replace it with + // the commit's ancestors which are outside the set. // e.g. `jj rebase -r A --before A` let new_parent_ids: Vec<_> = loc .new_parent_ids @@ -760,8 +763,8 @@ pub async fn compute_move_commits( }) .collect(); - // If the new children include a commit in the target set, replace it with the - // commit's descendants which are outside the set. + // If the new children include a commit in the target set, replace it with + // the commit's descendants which are outside the set. // e.g. `jj rebase -r A --after A` let new_children: Vec<_> = if loc .new_child_ids @@ -782,12 +785,13 @@ pub async fn compute_move_commits( .await .map_err(|err| err.into_backend_error())?; - // For all commits in the target set, compute its transitive descendant commits - // which are outside of the target set by up to 1 generation. + // For all commits in the target set, compute its transitive descendant + // commits which are outside of the target set by up to 1 + // generation. let mut target_commit_external_descendants: HashMap> = HashMap::new(); - // Iterate through all descendants of the target set, going through children - // before parents. + // Iterate through all descendants of the target set, going through + // children before parents. for commit in &target_commits_descendants { if !target_commit_external_descendants.contains_key(commit.id()) { let children = if target_commit_ids.contains(commit.id()) { @@ -836,11 +840,11 @@ pub async fn compute_move_commits( .await? }; - // Compute the parents of the new children, which will include the heads of the - // target set. + // Compute the parents of the new children, which will include the heads of + // the target set. let new_children_parents: HashMap<_, _> = if !new_children.is_empty() { - // Compute the heads of the target set, which will be used as the parents of - // `new_children`. + // Compute the heads of the target set, which will be used as the + // parents of `new_children`. let target_heads = compute_commits_heads(&target_commit_ids, &connected_target_commits); new_children @@ -848,7 +852,8 @@ pub async fn compute_move_commits( .map(|child_commit| { let mut new_child_parent_ids = IndexSet::new(); for old_child_parent_id in child_commit.parent_ids() { - // Replace target commits with their parents outside the target set. + // Replace target commits with their parents outside the + // target set. let old_child_parent_ids = if let Some(parents) = target_commits_external_parents.get(old_child_parent_id) { @@ -857,9 +862,11 @@ pub async fn compute_move_commits( vec![old_child_parent_id] }; - // If the original parents of the new children are the new parents of the - // `target_heads`, replace them with the target heads since we are "inserting" - // the target commits in between the new parents and the new children. + // If the original parents of the new children are the new + // parents of the `target_heads`, + // replace them with the target heads since we are + // "inserting" the target commits in + // between the new parents and the new children. for id in old_child_parent_ids { if new_parent_ids.contains(id) { new_child_parent_ids.extend(target_heads.clone()); @@ -869,8 +876,8 @@ pub async fn compute_move_commits( } } - // If not already present, add `target_heads` as parents of the new child - // commit. + // If not already present, add `target_heads` as parents of the + // new child commit. new_child_parent_ids.extend(target_heads.clone()); ( @@ -883,8 +890,8 @@ pub async fn compute_move_commits( HashMap::new() }; - // Compute the set of commits to visit, which includes the target commits, the - // new children commits (if any), and their descendants. + // Compute the set of commits to visit, which includes the target commits, + // the new children commits (if any), and their descendants. let mut roots = target_roots.iter().cloned().collect_vec(); roots.extend(new_children.iter().ids().cloned()); @@ -894,63 +901,64 @@ pub async fn compute_move_commits( let commit_new_parents_entries = try_join_all(descendants.iter().map(async |commit| -> BackendResult<_> { let commit_id = commit.id(); - let new_parent_ids = - if let Some(new_child_parents) = new_children_parents.get(commit_id) { - // New child of the rebased target commits. - new_child_parents.clone() - } else if target_commit_ids.contains(commit_id) { - // Commit is in the target set. - if target_roots.contains(commit_id) { - // If the commit is a root of the target set, it should be rebased onto the - // new destination. - new_parent_ids.clone() - } else { - // Otherwise: - // 1. Keep parents which are within the target set. - // 2. Replace parents which are outside the target set but are part of the - // connected target set with their ancestor commits which are in the - // target set. - // 3. Keep other parents outside the target set if they are not descendants - // of the new children of the target set. - let mut new_parents = vec![]; - for parent_id in commit.parent_ids() { - if target_commit_ids.contains(parent_id) { - new_parents.push(parent_id.clone()); - } else if let Some(parents) = - connected_target_commits_internal_parents.get(parent_id) - { - new_parents.extend(parents.iter().cloned()); - } else if !fallible_any(&new_children, async |child| { - repo.index().is_ancestor(child.id(), parent_id).await - }) - .await - // TODO: indexing error shouldn't be a "BackendError" - .map_err(|err| BackendError::Other(err.into()))? - { - new_parents.push(parent_id.clone()); - } - } - new_parents - } - } else if commit - .parent_ids() - .iter() - .any(|id| target_commits_external_parents.contains_key(id)) - { - // Commits outside the target set should have references to commits inside the - // set replaced. + let new_parent_ids = if let Some(new_child_parents) = + new_children_parents.get(commit_id) + { + // New child of the rebased target commits. + new_child_parents.clone() + } else if target_commit_ids.contains(commit_id) { + // Commit is in the target set. + if target_roots.contains(commit_id) { + // If the commit is a root of the target set, it should be + // rebased onto the new destination. + new_parent_ids.clone() + } else { + // Otherwise: + // 1. Keep parents which are within the target set. + // 2. Replace parents which are outside the target set but + // are part of the connected target set with their + // ancestor commits which are in the target set. + // 3. Keep other parents outside the target set if they are + // not descendants of the new children of the target set. let mut new_parents = vec![]; - for parent in commit.parent_ids() { - if let Some(parents) = target_commits_external_parents.get(parent) { + for parent_id in commit.parent_ids() { + if target_commit_ids.contains(parent_id) { + new_parents.push(parent_id.clone()); + } else if let Some(parents) = + connected_target_commits_internal_parents.get(parent_id) + { new_parents.extend(parents.iter().cloned()); - } else { - new_parents.push(parent.clone()); + } else if !fallible_any(&new_children, async |child| { + repo.index().is_ancestor(child.id(), parent_id).await + }) + .await + // TODO: indexing error shouldn't be a "BackendError" + .map_err(|err| BackendError::Other(err.into()))? + { + new_parents.push(parent_id.clone()); } } new_parents - } else { - commit.parent_ids().iter().cloned().collect_vec() - }; + } + } else if commit + .parent_ids() + .iter() + .any(|id| target_commits_external_parents.contains_key(id)) + { + // Commits outside the target set should have references to + // commits inside the set replaced. + let mut new_parents = vec![]; + for parent in commit.parent_ids() { + if let Some(parents) = target_commits_external_parents.get(parent) { + new_parents.extend(parents.iter().cloned()); + } else { + new_parents.push(parent.clone()); + } + } + new_parents + } else { + commit.parent_ids().iter().cloned().collect_vec() + }; Ok((commit.id().clone(), new_parent_ids)) })) .await?; @@ -1085,9 +1093,9 @@ pub async fn duplicate_commits( // Commits in the target set should only have other commits in the set as // parents, except the roots of the set, which persist their original // parents. - // If a commit in the target set has a parent which is not in the set, but has - // an ancestor which is in the set, then the commit will have that ancestor - // as a parent instead. + // If a commit in the target set has a parent which is not in the set, but + // has an ancestor which is in the set, then the commit will have that + // ancestor as a parent instead. let target_commits_internal_parents = { let mut target_commits_internal_parents = compute_internal_parents_within(&target_commit_ids, &connected_target_commits); @@ -1165,18 +1173,19 @@ pub async fn duplicate_commits( if children_commit_ids_set.contains(rewriter.old_commit().id()) { let mut child_new_parent_ids = IndexSet::new(); for old_parent_id in rewriter.old_commit().parent_ids() { - // If the original parents of the new children are the new parents of - // `target_head_ids`, replace them with `target_head_ids` since we are - // "inserting" the target commits in between the new parents and the new - // children. + // If the original parents of the new children are the new + // parents of `target_head_ids`, replace + // them with `target_head_ids` since we are + // "inserting" the target commits in between the new parents + // and the new children. if parent_commit_ids.contains(old_parent_id) { child_new_parent_ids.extend(target_head_ids.clone()); } else { child_new_parent_ids.insert(old_parent_id.clone()); } } - // If not already present, add `target_head_ids` as parents of the new child - // commit. + // If not already present, add `target_head_ids` as parents of + // the new child commit. child_new_parent_ids.extend(target_head_ids.clone()); rewriter.set_new_parents(child_new_parent_ids.into_iter().collect()); } @@ -1262,8 +1271,8 @@ fn compute_internal_parents_within( ) -> HashMap> { let mut internal_parents: HashMap> = HashMap::new(); for commit in graph_commits.iter().rev() { - // The roots of the set will not have any parents found in `internal_parents`, - // and will be stored as an empty vector. + // The roots of the set will not have any parents found in + // `internal_parents`, and will be stored as an empty vector. let mut new_parents = IndexSet::new(); for old_parent in commit.parent_ids() { if target_commit_ids.contains(old_parent) { @@ -1380,14 +1389,16 @@ pub async fn squash_commits<'repo>( for source in sources { let abandon = !keep_emptied && source.is_full_selection(); if !abandon && source.is_empty_selection() { - // Nothing selected from this commit. If it's abandoned (i.e. already empty), we - // still include it so `jj squash` can be used for abandoning an empty commit in + // Nothing selected from this commit. If it's abandoned (i.e. + // already empty), we still include it so `jj squash` + // can be used for abandoning an empty commit in // the middle of a stack. continue; } - // TODO: Do we want to optimize the case of moving to the parent commit (`jj - // squash -r`)? The source tree will be unchanged in that case. + // TODO: Do we want to optimize the case of moving to the parent commit + // (`jj squash -r`)? The source tree will be unchanged in that + // case. source_commits.push(SourceCommit { commit: source, diff: source @@ -1435,10 +1446,10 @@ pub async fn squash_commits<'repo>( // TODO: indexing error shouldn't be a "BackendError" .map_err(|err| BackendError::Other(err.into()))? { - // If we're moving changes to a descendant, first rebase descendants onto the - // rewritten sources. Otherwise it will likely already have the content - // changes we're moving, so applying them will have no effect and the - // changes will disappear. + // If we're moving changes to a descendant, first rebase descendants + // onto the rewritten sources. Otherwise it will likely already + // have the content changes we're moving, so applying them will + // have no effect and the changes will disappear. let immutable = RevsetExpression::none(); let options = RebaseOptions::default(); repo.rebase_descendants_with_options(&immutable, &options, |old_commit, rebased_commit| { @@ -1534,8 +1545,9 @@ pub async fn find_duplicate_divergent_commits( MoveCommitsTarget::Roots(root_ids) => root_ids, }; - // We only care about divergent changes which are new ancestors of the rebased - // commits, not ones which were already ancestors of the rebased commits. + // We only care about divergent changes which are new ancestors of the + // rebased commits, not ones which were already ancestors of the rebased + // commits. let is_new_ancestor = RevsetExpression::commits(target_root_ids.clone()) .range(&RevsetExpression::commits(new_parent_ids.to_owned())) .evaluate(repo) @@ -1543,10 +1555,11 @@ pub async fn find_duplicate_divergent_commits( .containing_fn(); let mut duplicate_divergent = Vec::new(); - // Checking every pair of commits between these two sets could be expensive if - // there are several commits with the same change ID. However, it should be - // uncommon to have more than a couple commits with the same change ID being - // rebased at the same time, so it should be good enough in practice. + // Checking every pair of commits between these two sets could be expensive + // if there are several commits with the same change ID. However, it + // should be uncommon to have more than a couple commits with the same + // change ID being rebased at the same time, so it should be good enough + // in practice. for (target_commit, ancestor_candidates) in divergent_changes { for ancestor_candidate_id in ancestor_candidates { if !is_new_ancestor(&ancestor_candidate_id) @@ -1563,8 +1576,9 @@ pub async fn find_duplicate_divergent_commits( let new_tree = rebase_to_dest_parent(repo, slice::from_ref(target_commit), &ancestor_candidate) .await?; - // Check whether the rebased commit would have the same tree as the existing - // commit if they had the same parents. If so, we can skip this rebased commit. + // Check whether the rebased commit would have the same tree as the + // existing commit if they had the same parents. If so, + // we can skip this rebased commit. if new_tree.tree_ids() == ancestor_candidate.tree_ids() { duplicate_divergent.push(target_commit.clone()); break; diff --git a/lib/src/secure_config.rs b/lib/src/secure_config.rs index 495e3d428f4..c3e1b071539 100644 --- a/lib/src/secure_config.rs +++ b/lib/src/secure_config.rs @@ -191,7 +191,8 @@ impl SecureConfig { fs::write(&config_path, content).context(&config_path)?; } - // Write the config ID atomically. A half-formed config ID would be very bad. + // Write the config ID atomically. A half-formed config ID would be very + // bad. atomic_write( &self.repo_dir.join(self.config_id_name), config_id.as_bytes(), @@ -308,9 +309,10 @@ impl SecureConfig { // I considered making this readonly, but that would prevent you from // updating the config with old versions of jj. // In the future, we consider something a little more robust, where as - // the non-legacy config changes, we propagate that to the legacy config. - // However, it seems a little overkill, considering it only affects windows - // users who use multiple versions of jj at once, and only for a year. + // the non-legacy config changes, we propagate that to the legacy + // config. However, it seems a little overkill, considering it + // only affects windows users who use multiple versions of jj at + // once, and only for a year. let mut new_content = CONTENT_PREFIX.as_bytes().to_vec(); new_content.extend_from_slice(content); fs::write(&legacy_config, new_content).context(&legacy_config)?; @@ -571,8 +573,8 @@ mod tests { Ok(()) } - // This feature works on windows as well, it just isn't easy to replicate with a - // test. + // This feature works on windows as well, it just isn't easy to replicate + // with a test. #[cfg(unix)] #[test] fn test_repo_aliased() -> TestResult { diff --git a/lib/src/settings.rs b/lib/src/settings.rs index 1e35a892ba8..8b415845fc2 100644 --- a/lib/src/settings.rs +++ b/lib/src/settings.rs @@ -377,8 +377,8 @@ fn parse_human_byte_size(v: &str) -> Result { prefix as u32 + 1 } }; - // A string consisting only of base 10 digits is either a valid u64 or really - // huge. + // A string consisting only of base 10 digits is either a valid u64 or + // really huge. let factor = digits.parse::().unwrap_or(u64::MAX); Ok(factor.saturating_mul(1024u64.saturating_pow(exponent))) } diff --git a/lib/src/simple_backend.rs b/lib/src/simple_backend.rs index 1d86b102bb3..57dbdb6917e 100644 --- a/lib/src/simple_backend.rs +++ b/lib/src/simple_backend.rs @@ -373,8 +373,9 @@ pub fn commit_to_proto(commit: &Commit) -> crate::protos::simple_store::Commit { } fn commit_from_proto(mut proto: crate::protos::simple_store::Commit) -> Commit { - // Note how .take() sets the secure_sig field to None before we encode the data. - // Needs to be done first since proto is partially moved a bunch below + // Note how .take() sets the secure_sig field to None before we encode the + // data. Needs to be done first since proto is partially moved a bunch + // below let secure_sig = proto.secure_sig.take().map(|sig| SecureSig { data: proto.encode_to_vec(), sig, diff --git a/lib/src/simple_op_heads_store.rs b/lib/src/simple_op_heads_store.rs index 560236de6aa..96f2e67e114 100644 --- a/lib/src/simple_op_heads_store.rs +++ b/lib/src/simple_op_heads_store.rs @@ -86,9 +86,10 @@ impl SimpleOpHeadsStore { std::fs::remove_file(&path) .or_else(|err| { if err.kind() == io::ErrorKind::NotFound { - // It's fine if the old head was not found. It probably means - // that we're on a distributed file system where the locking - // doesn't work. We'll probably end up with two current + // It's fine if the old head was not found. It probably + // means that we're on a distributed + // file system where the locking doesn't + // work. We'll probably end up with two current // heads. We'll detect that next time we load the view. Ok(()) } else { diff --git a/lib/src/simple_op_store.rs b/lib/src/simple_op_store.rs index 3ce07035cab..e52d0519ea9 100644 --- a/lib/src/simple_op_store.rs +++ b/lib/src/simple_op_store.rs @@ -198,8 +198,8 @@ impl OpStore for SimpleOpStore { let mut operation = operation_from_proto(proto).map_err(|err| to_read_error(err.into(), id))?; if operation.parents.is_empty() { - // Repos created before we had the root operation will have an operation without - // parents. + // Repos created before we had the root operation will have an + // operation without parents. operation.parents.push(self.root_operation_id.clone()); } Ok(operation) @@ -607,8 +607,8 @@ fn view_to_proto(view: &View) -> crate::protos::simple_op_store::View { fn view_from_proto(proto: crate::protos::simple_op_store::View) -> Result { // TODO: validate commit id length? - // For compatibility with old repos before we had support for multiple working - // copies + // For compatibility with old repos before we had support for multiple + // working copies let mut wc_commit_ids = BTreeMap::new(); #[expect(deprecated)] if !proto.wc_commit_id.is_empty() { @@ -920,8 +920,8 @@ fn ref_target_to_proto_legacy( fn ref_target_from_proto( maybe_proto: Option, ) -> RefTarget { - // TODO: Delete legacy format handling when we decide to drop support for views - // saved by jj <= 0.8. + // TODO: Delete legacy format handling when we decide to drop support for + // views saved by jj <= 0.8. let Some(proto) = maybe_proto else { // Legacy absent id return RefTarget::absent(); diff --git a/lib/src/ssh_signing.rs b/lib/src/ssh_signing.rs index ae2b83ed4bf..5d1ecfe3bf8 100644 --- a/lib/src/ssh_signing.rs +++ b/lib/src/ssh_signing.rs @@ -186,8 +186,9 @@ impl SshBackend { .arg("-s") .arg(signature_file_path); - // We can't use the existing run_command helper here as `-Y find-principals` - // will return a non-0 exit code if no principals are found. + // We can't use the existing run_command helper here as `-Y + // find-principals` will return a non-0 exit code if no + // principals are found. // // In this case we don't want to error out, just return None. tracing::info!(?command, "running SSH signing command"); @@ -223,11 +224,11 @@ impl SigningBackend for SshBackend { return Err(SshError::MissingKey.into()); }; - // The ssh-keygen `-f` flag expects to be given a file which contains either a - // private or public key. + // The ssh-keygen `-f` flag expects to be given a file which contains + // either a private or public key. // - // As it expects a file and we might have an inlined public key instead, we need - // to ensure it is written to a file first. + // As it expects a file and we might have an inlined public key instead, + // we need to ensure it is written to a file first. let pub_key_path = ensure_key_as_file(key)?; let mut command = self.create_command(); diff --git a/lib/src/stacked_table.rs b/lib/src/stacked_table.rs index a25ea9e90ff..92e6b3cd46a 100644 --- a/lib/src/stacked_table.rs +++ b/lib/src/stacked_table.rs @@ -321,8 +321,9 @@ impl MutableTable { loop { match maybe_parent_file { Some(parent_file) => { - // TODO: We should probably also squash if the parent file has less than N - // commits, regardless of how many (few) are in `self`. + // TODO: We should probably also squash if the parent file + // has less than N commits, regardless + // of how many (few) are in `self`. if 2 * num_new_entries < parent_file.num_local_entries { squashed = Self::incremental(parent_file); break; @@ -527,13 +528,15 @@ impl TableStore { } else if tables.len() == 1 { Ok(tables.pop().unwrap()) } else { - // There are multiple heads. We take a lock, then check if there are still - // multiple heads (it's likely that another process was in the process of - // deleting on of them). If there are still multiple heads, we attempt to - // merge all the tables into one. We then save that table and record the new - // head. Note that the locking isn't necessary for correctness; we - // take the lock only to avoid other concurrent processes from doing - // the same work (and producing another set of divergent heads). + // There are multiple heads. We take a lock, then check if there are + // still multiple heads (it's likely that another + // process was in the process of deleting on of them). + // If there are still multiple heads, we attempt to + // merge all the tables into one. We then save that table and record + // the new head. Note that the locking isn't necessary + // for correctness; we take the lock only to avoid other + // concurrent processes from doing the same work (and + // producing another set of divergent heads). let (table, _) = self.get_head_locked()?; Ok(table) } @@ -763,8 +766,9 @@ mod tests { assert_eq!(mut_table2.get_value(b"abc"), Some(b"value1".as_slice())); assert_eq!(mut_table2.get_value(b"abd"), Some(b"value 2".as_slice())); assert_eq!(mut_table2.get_value(b"abe"), Some(b"value 4".as_slice())); - // The caller shouldn't write two values for the same key, so it's undefined - // which wins, but let's test how it currently behaves. + // The caller shouldn't write two values for the same key, so it's + // undefined which wins, but let's test how it currently + // behaves. assert_eq!(mut_table2.get_value(b"mmm"), Some(b"side 1".as_slice())); assert_eq!(mut_table2.get_value(b"yyy"), Some(b"val5".as_slice())); assert_eq!(mut_table2.get_value(b"zzz"), Some(b"val3".as_slice())); @@ -801,8 +805,8 @@ mod tests { assert_eq!(merged_table.get_value(b"abc"), Some(b"value1".as_slice())); assert_eq!(merged_table.get_value(b"abd"), Some(b"value 2".as_slice())); assert_eq!(merged_table.get_value(b"abe"), Some(b"value 4".as_slice())); - // The caller shouldn't write two values for the same key, so it's undefined - // which wins. + // The caller shouldn't write two values for the same key, so it's + // undefined which wins. let value_mmm = merged_table.get_value(b"mmm"); assert!(value_mmm == Some(b"side 1".as_slice()) || value_mmm == Some(b"side 2".as_slice())); assert_eq!(merged_table.get_value(b"yyy"), Some(b"val5".as_slice())); @@ -813,9 +817,10 @@ mod tests { #[test] fn stacked_table_multi_head_squashed_preserves_head_marker() -> TestResult { - // When the newer segment is small enough to squash into a full table, the - // two head markers are not physically parent/child linked. Merging them - // still yields a table whose name matches one of the inputs. + // When the newer segment is small enough to squash into a full table, + // the two head markers are not physically parent/child linked. + // Merging them still yields a table whose name matches one of + // the inputs. let temp_dir = new_temp_dir(); let store = TableStore::init(temp_dir.path().to_path_buf(), 3); @@ -876,7 +881,8 @@ mod tests { base_table.name() ); - // Simulate stale parent marker still present alongside the child marker. + // Simulate stale parent marker still present alongside the child + // marker. store.add_head(&base_table)?; assert_eq!(store.get_head_tables()?.len(), 2); diff --git a/lib/src/trailer.rs b/lib/src/trailer.rs index 8902c96f10c..2a23b698388 100644 --- a/lib/src/trailer.rs +++ b/lib/src/trailer.rs @@ -90,8 +90,9 @@ pub fn parse_trailers(body: &str) -> Result, TrailerParseError> { fn parse_trailers_impl(body: &str) -> (Vec, bool, bool, Option) { // a trailer always comes at the end of a message; we can split the message // by newline, but we need to immediately reverse the order of the lines - // to ensure we parse the trailer in an unambiguous manner; this avoids cases - // where a colon in the body of the message is mistaken for a trailer + // to ensure we parse the trailer in an unambiguous manner; this avoids + // cases where a colon in the body of the message is mistaken for a + // trailer let lines = body.trim_ascii_end().lines().rev(); let trailer_re = regex::Regex::new(r"^([a-zA-Z0-9-]+) *: *(.*)$").expect("Trailer regex should be valid"); diff --git a/lib/src/tree.rs b/lib/src/tree.rs index 2ccef674c1d..2b4f300d21e 100644 --- a/lib/src/tree.rs +++ b/lib/src/tree.rs @@ -212,7 +212,8 @@ impl Iterator for TreeEntriesIterator<'_> { if let Some((path, value)) = top.entries.pop() { match value { TreeValue::Tree(id) => { - // TODO: Handle the other cases (specific files and trees) + // TODO: Handle the other cases (specific files and + // trees) if self.matcher.visit(&path).is_nothing() { continue; } diff --git a/lib/src/tree_builder.rs b/lib/src/tree_builder.rs index ca1cbcd0e2e..dea3bfecf41 100644 --- a/lib/src/tree_builder.rs +++ b/lib/src/tree_builder.rs @@ -98,8 +98,8 @@ impl TreeBuilder { } } - // Write trees in reverse lexicographical order, starting with trees without - // children. + // Write trees in reverse lexicographical order, starting with trees + // without children. // TODO: Writing trees concurrently should help on high-latency backends let store = &self.store; while let Some((dir, cur_entries)) = trees_to_write.pop_last() { @@ -118,7 +118,8 @@ impl TreeBuilder { parent_entries.insert(basename.to_owned(), TreeValue::Tree(tree.id().clone())); } } else { - // We're writing the root tree. Write it even if empty. Return its id. + // We're writing the root tree. Write it even if empty. Return + // its id. assert!(trees_to_write.is_empty()); let data = backend::Tree::from_sorted_entries(cur_entries.into_iter().collect()); let written_tree = store.write_tree(&dir, data).await?; diff --git a/lib/src/tree_merge.rs b/lib/src/tree_merge.rs index 27e92a9b914..b75dd944ada 100644 --- a/lib/src/tree_merge.rs +++ b/lib/src/tree_merge.rs @@ -221,7 +221,8 @@ impl TreeMerger { assert!(self.unstarted_work.is_empty()); return Ok(tree); } - // Propagate the write to the parent tree, replacing empty trees by `None`. + // Propagate the write to the parent tree, replacing empty + // trees by `None`. let new_value = tree.map(|tree| { (tree.id() != self.store.empty_tree_id()) .then(|| TreeValue::Tree(tree.id().clone())) @@ -247,8 +248,8 @@ impl TreeMerger { } fn process_tree(&mut self, dir: RepoPathBuf, tree: Merge) { - // First resolve trivial merges (those that we don't need to load any more data - // for) + // First resolve trivial merges (those that we don't need to load any + // more data for) let same_change = self.store.merge_options().same_change; let mut resolved = vec![]; let mut non_trivial = vec![]; @@ -276,9 +277,9 @@ impl TreeMerger { if value.is_tree() { self.enqueue_tree_read(path, value); } else { - // TODO: If it's e.g. a dir/file conflict, there's no need to try to - // resolve it as a file. We should mark them to - // `unmerged_tree.conflicts` instead. + // TODO: If it's e.g. a dir/file conflict, there's no need to + // try to resolve it as a file. We should mark + // them to `unmerged_tree.conflicts` instead. self.enqueue_file_merge(path, value); } } @@ -300,8 +301,9 @@ impl TreeMerger { fn enqueue_tree_write(&mut self, dir: RepoPathBuf, backend_trees: Merge) { let work_fut = write_trees(self.store.clone(), dir.clone(), backend_trees) .map(|result| TreeMergerWorkOutput::WrittenTrees { dir, result }); - // Bypass the `unstarted_work` queue because writing trees usually results in - // saving memory (each tree gets replaced by a `TreeValue::Tree`) + // Bypass the `unstarted_work` queue because writing trees usually + // results in saving memory (each tree gets replaced by a + // `TreeValue::Tree`) self.work.push(Box::pin(work_fut)); } @@ -321,8 +323,9 @@ impl TreeMerger { let tree = self.trees_to_resolve.get_mut(dir).unwrap(); let same_change = self.store.merge_options().same_change; tree.mark_completed(basename.to_owned(), value, same_change); - // If all entries in this tree have been processed (either resolved or still a - // conflict), schedule the writing of the tree(s) to the backend. + // If all entries in this tree have been processed (either resolved or + // still a conflict), schedule the writing of the tree(s) to the + // backend. if tree.pending_lookup.is_empty() { let tree = self.trees_to_resolve.remove(dir).unwrap(); self.enqueue_tree_write(dir.to_owned(), tree.into_backend_trees()); @@ -394,8 +397,8 @@ async fn try_resolve_file_values>( let simplified = values .map(|value| value.as_ref().map(Borrow::borrow)) .simplify(); - // No fast path for simplified.is_resolved(). If it could be resolved, it would - // have been caught by values.resolve_trivial() above. + // No fast path for simplified.is_resolved(). If it could be resolved, it + // would have been caught by values.resolve_trivial() above. if let Some(resolved) = try_resolve_file_conflict(store, path, &simplified).await? { Ok(Some(Merge::normal(resolved))) } else { @@ -459,8 +462,8 @@ async fn try_resolve_file_conflict( return Ok(None); }; if let Some(&resolved_file_id) = file_id_conflict.resolve_trivial(options.same_change) { - // Don't bother reading the file contents if the conflict can be trivially - // resolved. + // Don't bother reading the file contents if the conflict can be + // trivially resolved. return Ok(Some(TreeValue::File { id: resolved_file_id.clone(), executable, @@ -472,8 +475,8 @@ async fn try_resolve_file_conflict( // terms which only differ in executable bits. Simplify the conflict further // for two reasons: // 1. Avoid reading unchanged file contents - // 2. The simplified conflict can sometimes be resolved when the unsimplfied one - // cannot + // 2. The simplified conflict can sometimes be resolved when the unsimplfied + // one cannot let file_id_conflict = file_id_conflict.simplify(); let contents = file_id_conflict diff --git a/lib/src/view.rs b/lib/src/view.rs index db1972f1de1..4846502a8ff 100644 --- a/lib/src/view.rs +++ b/lib/src/view.rs @@ -255,7 +255,8 @@ impl View { bookmark_matcher: &StringMatcher, remote_matcher: &StringMatcher, ) -> impl Iterator, &RemoteRef)> { - // Use kmerge instead of flat_map for consistency with all_remote_bookmarks(). + // Use kmerge instead of flat_map for consistency with + // all_remote_bookmarks(). remote_matcher .filter_btree_map_as_deref(&self.data.remote_views) .map(|(remote, remote_view)| { @@ -332,8 +333,8 @@ impl View { bookmark_matcher: &'b StringMatcher, remote_name: &RemoteName, ) -> impl Iterator)> + use<'a, 'b> { - // Change remote_name to StringMatcher if needed, but merge-join adapter won't - // be usable. + // Change remote_name to StringMatcher if needed, but merge-join adapter + // won't be usable. let maybe_remote_view = self.data.remote_views.get(remote_name); refs::iter_named_local_remote_refs( bookmark_matcher.filter_btree_map_as_deref(&self.data.local_bookmarks), @@ -469,7 +470,8 @@ impl View { tag_matcher: &StringMatcher, remote_matcher: &StringMatcher, ) -> impl Iterator, &RemoteRef)> { - // Use kmerge instead of flat_map for consistency with all_remote_tags(). + // Use kmerge instead of flat_map for consistency with + // all_remote_tags(). remote_matcher .filter_btree_map_as_deref(&self.data.remote_views) .map(|(remote, remote_view)| { @@ -541,8 +543,8 @@ impl View { tag_matcher: &'b StringMatcher, remote_name: &RemoteName, ) -> impl Iterator)> + use<'a, 'b> { - // Change remote_name to StringMatcher if needed, but merge-join adapter won't - // be usable. + // Change remote_name to StringMatcher if needed, but merge-join adapter + // won't be usable. let maybe_remote_view = self.data.remote_views.get(remote_name); refs::iter_named_local_remote_refs( tag_matcher.filter_btree_map_as_deref(&self.data.local_tags), diff --git a/lib/src/working_copy.rs b/lib/src/working_copy.rs index 0d4317c19d2..2939b7132ad 100644 --- a/lib/src/working_copy.rs +++ b/lib/src/working_copy.rs @@ -139,9 +139,9 @@ pub trait LockedWorkingCopy: Any + Send { /// Updates the patterns that decide which paths from the current tree /// should be checked out in the working copy. // TODO: Use a different error type here so we can include a - // `SparseNotSupported` variants for working copies that don't support sparse - // checkouts (e.g. because they use a virtual file system so there's no reason - // to use sparse). + // `SparseNotSupported` variants for working copies that don't support + // sparse checkouts (e.g. because they use a virtual file system so + // there's no reason to use sparse). async fn set_sparse_patterns( &mut self, new_sparse_patterns: Vec, @@ -376,15 +376,18 @@ impl WorkingCopyFreshness { let ancestor_ops = op_walk::closest_common_ancestors([wc_operation.clone()], [repo_operation.clone()]) .await?; - // TODO: test all operations instead of using only a single common operation + // TODO: test all operations instead of using only a single common + // operation let ancestor_op = ancestor_ops.into_iter().next().unwrap(); if ancestor_op.id() == repo_operation.id() { - // The working copy was updated since we loaded the repo. The repo must be - // reloaded at the working copy's operation. + // The working copy was updated since we loaded the repo. The + // repo must be reloaded at the working copy's + // operation. Ok(Self::Updated(Box::new(wc_operation))) } else if ancestor_op.id() == wc_operation.id() { - // The working copy was not updated when some repo operation committed, - // meaning that it's stale compared to the repo view. + // The working copy was not updated when some repo operation + // committed, meaning that it's stale compared + // to the repo view. if locked_wc.old_tree().tree_ids_and_labels() == wc_commit.tree().tree_ids_and_labels() { diff --git a/lib/src/workspace.rs b/lib/src/workspace.rs index ae061e49a10..9a5fe836e52 100644 --- a/lib/src/workspace.rs +++ b/lib/src/workspace.rs @@ -264,10 +264,11 @@ impl Workspace { let backend_initializer = |settings: &UserSettings, store_path: &Path| -> Result, _> { - // If the git repo is inside the workspace, use a relative path to it so the - // whole workspace can be moved without breaking. - // TODO: Clean up path normalization. store_path is canonicalized by - // ReadonlyRepo::init(). workspace_root will be canonicalized by + // If the git repo is inside the workspace, use a relative path to + // it so the whole workspace can be moved without + // breaking. TODO: Clean up path normalization. + // store_path is canonicalized by ReadonlyRepo::init(). + // workspace_root will be canonicalized by // Workspace::new(), but it's not yet here. let store_relative_git_repo_path = match ( dunce::canonicalize(workspace_root), @@ -460,10 +461,10 @@ impl Workspace { commit: &Commit, ) -> Result { let mut locked_ws = self.start_working_copy_mutation().await?; - // Check if the current working-copy commit has changed on disk compared to what - // the caller expected. It's safe to check out another commit - // regardless, but it's probably not what the caller wanted, so we let - // them know. + // Check if the current working-copy commit has changed on disk compared + // to what the caller expected. It's safe to check out another + // commit regardless, but it's probably not what the caller + // wanted, so we let them know. if let Some(old_tree) = old_tree && old_tree.tree_ids_and_labels() != locked_ws.locked_wc().old_tree().tree_ids_and_labels() @@ -573,8 +574,9 @@ impl DefaultWorkspaceLoader { )); } let mut repo_dir = jj_dir.join("repo"); - // If .jj/repo is a file, then we interpret its contents as a relative path to - // the actual repo directory (typically in another workspace). + // If .jj/repo is a file, then we interpret its contents as a relative + // path to the actual repo directory (typically in another + // workspace). if repo_dir.is_file() { let buf = fs::read(&repo_dir).context(&repo_dir)?; let repo_path = diff --git a/lib/tests/test_bad_locking.rs b/lib/tests/test_bad_locking.rs index 708051f29dc..7baa31391f6 100644 --- a/lib/tests/test_bad_locking.rs +++ b/lib/tests/test_bad_locking.rs @@ -58,8 +58,8 @@ fn merge_directories(left: &Path, base: &Path, right: &Path, output: &Path) { } } } - // Walk the base and find files removed in the right side, then remove them in - // the output + // Walk the base and find files removed in the right side, then remove them + // in the output if base.exists() { for entry in std::fs::read_dir(base).unwrap() { let path = entry.unwrap().path(); @@ -74,8 +74,8 @@ fn merge_directories(left: &Path, base: &Path, right: &Path, output: &Path) { } } } - // Walk the right side and find files added in the right side, then add them in - // the output + // Walk the right side and find files added in the right side, then add them + // in the output if right.exists() { for entry in std::fs::read_dir(right).unwrap() { let path = entry.unwrap().path(); @@ -86,8 +86,9 @@ fn merge_directories(left: &Path, base: &Path, right: &Path, output: &Path) { if child_right.is_dir() { sub_dirs.push(base_name.to_os_string()); } else if !child_base.exists() { - // This overwrites the left side if that's been written. That's fine, since the - // point of the test is that it should be okay for either side to win. + // This overwrites the left side if that's been written. That's + // fine, since the point of the test is that it + // should be okay for either side to win. std::fs::copy(&child_right, child_output).unwrap(); } } @@ -105,8 +106,8 @@ fn merge_directories(left: &Path, base: &Path, right: &Path, output: &Path) { #[test_case(TestRepoBackend::Simple; "simple backend")] #[test_case(TestRepoBackend::Git; "git backend")] fn test_bad_locking_children(backend: TestRepoBackend) -> TestResult { - // Test that two new commits created on separate machines are both visible (not - // lost due to lack of locking) + // Test that two new commits created on separate machines are both visible + // (not lost due to lack of locking) let settings = testutils::user_settings(); let test_workspace = TestWorkspace::init_with_backend_and_settings(backend, &settings); let repo = &test_workspace.repo; @@ -144,8 +145,8 @@ fn test_bad_locking_children(backend: TestRepoBackend) -> TestResult { let child2 = write_random_commit_with_parents(machine2_tx.repo_mut(), &[&initial]); machine2_tx.commit("test").block_on()?; - // Simulate that the distributed file system now has received the changes from - // both machines + // Simulate that the distributed file system now has received the changes + // from both machines let merged_path = test_workspace.root_dir().join("merged"); merge_directories(&machine1_root, workspace_root, &machine2_root, &merged_path); let merged_workspace = Workspace::load( @@ -178,10 +179,10 @@ fn test_bad_locking_interrupted(backend: TestRepoBackend) -> TestResult { let initial = write_random_commit(tx.repo_mut()); let repo = tx.commit("test").block_on()?; - // Simulate a crash that resulted in the old op-head left in place. We simulate - // it somewhat hackily by copying the .jj/op_heads/ directory before the - // operation and then copying that back afterwards, leaving the existing - // op-head(s) in place. + // Simulate a crash that resulted in the old op-head left in place. We + // simulate it somewhat hackily by copying the .jj/op_heads/ directory + // before the operation and then copying that back afterwards, leaving + // the existing op-head(s) in place. let op_heads_dir = test_workspace.repo_path().join("op_heads"); let backup_path = test_workspace.root_dir().join("backup"); copy_directory(&op_heads_dir, &backup_path); @@ -193,8 +194,8 @@ fn test_bad_locking_interrupted(backend: TestRepoBackend) -> TestResult { // Reload the repo and check that only the new head is present. let reloaded_repo = test_env.load_repo_at_head(&settings, test_workspace.repo_path()); assert_eq!(reloaded_repo.op_id(), &op_id); - // Reload once more to make sure that the .jj/op_heads/ directory was updated - // correctly. + // Reload once more to make sure that the .jj/op_heads/ directory was + // updated correctly. let reloaded_repo = test_env.load_repo_at_head(&settings, test_workspace.repo_path()); assert_eq!(reloaded_repo.op_id(), &op_id); Ok(()) diff --git a/lib/tests/test_bisect.rs b/lib/tests/test_bisect.rs index 6d8e2400477..91e2b04a7b2 100644 --- a/lib/tests/test_bisect.rs +++ b/lib/tests/test_bisect.rs @@ -153,9 +153,11 @@ fn test_bisect_linear() { } ); - // commit2 is the first bad commit; its parent and child commits were skipped + // commit2 is the first bad commit; its parent and child commits were + // skipped // * commit1 is a possibly_bad commit: it's between a bad and a good commit - // * commit3 is NOT a possibly_bad commit: it's implicitly bad due to commit2 + // * commit3 is NOT a possibly_bad commit: it's implicitly bad due to + // commit2 let expected_tests = [ (commit3.id(), Evaluation::Skip), (commit2.id(), Evaluation::Bad), @@ -172,8 +174,8 @@ fn test_bisect_linear() { ); // Commit 7 is the first bad commit but commits before 6 were skipped - // TODO: Avoid testing every commit near first skipped commit. Test e.g. commit - // 1 and commit 5 once we see that commit 3 was indeterminate. + // TODO: Avoid testing every commit near first skipped commit. Test e.g. + // commit 1 and commit 5 once we see that commit 3 was indeterminate. let expected_tests = [ (commit3.id(), Evaluation::Skip), (commit2.id(), Evaluation::Skip), diff --git a/lib/tests/test_commit_builder.rs b/lib/tests/test_commit_builder.rs index a2f50703c18..7976384a2de 100644 --- a/lib/tests/test_commit_builder.rs +++ b/lib/tests/test_commit_builder.rs @@ -182,8 +182,8 @@ fn test_rewrite(backend: TestRepoBackend) -> TestResult { let rewrite_settings = UserSettings::from_config(config)?; let repo = test_env.load_repo_at_head(&rewrite_settings, test_repo.repo_path()); let store = repo.store(); - // We have a new store instance, so we need to associate the old tree with the - // new store instance. + // We have a new store instance, so we need to associate the old tree with + // the new store instance. let (tree_ids, labels) = rewritten_tree.into_tree_ids_and_labels(); let rewritten_tree = MergedTree::new(store.clone(), tree_ids, labels); let initial_commit = store.get_commit(initial_commit.id())?; diff --git a/lib/tests/test_commit_concurrent.rs b/lib/tests/test_commit_concurrent.rs index 3a0d1dae835..a2614e9a2f3 100644 --- a/lib/tests/test_commit_concurrent.rs +++ b/lib/tests/test_commit_concurrent.rs @@ -74,8 +74,8 @@ fn test_commit_parallel(backend: TestRepoBackend) -> TestResult { } }); let repo = repo.reload_at_head().block_on()?; - // One commit per thread plus the commit from the initial working-copy on top of - // the root commit + // One commit per thread plus the commit from the initial working-copy on + // top of the root commit assert_eq!(repo.view().heads().len(), num_threads + 1); // One additional operation for the root operation, one for checking out the @@ -87,8 +87,8 @@ fn test_commit_parallel(backend: TestRepoBackend) -> TestResult { #[test_case(TestRepoBackend::Simple ; "simple backend")] #[test_case(TestRepoBackend::Git ; "git backend")] fn test_commit_parallel_instances(backend: TestRepoBackend) -> TestResult { - // Like the test above but creates a new repo instance for every thread, which - // makes it behave very similar to separate processes. + // Like the test above but creates a new repo instance for every thread, + // which makes it behave very similar to separate processes. let settings = testutils::user_settings(); let test_workspace = TestWorkspace::init_with_backend_and_settings(backend, &settings); let test_env = &test_workspace.env; @@ -105,8 +105,8 @@ fn test_commit_parallel_instances(backend: TestRepoBackend) -> TestResult { }); } }); - // One commit per thread plus the commit from the initial working-copy commit on - // top of the root commit + // One commit per thread plus the commit from the initial working-copy + // commit on top of the root commit let repo = test_env.load_repo_at_head(&settings, test_workspace.repo_path()); assert_eq!(repo.view().heads().len(), num_threads + 1); diff --git a/lib/tests/test_conflicts.rs b/lib/tests/test_conflicts.rs index 7214106c0c8..6f628c3782a 100644 --- a/lib/tests/test_conflicts.rs +++ b/lib/tests/test_conflicts.rs @@ -80,8 +80,8 @@ fn test_materialize_conflict_basic() { "}, ); - // The left side should come first. The diff should be use the smaller (right) - // side, and the left side should be a snapshot. + // The left side should come first. The diff should be use the smaller + // (right) side, and the left side should be a snapshot. let conflict = Merge::from_removes_adds( vec![Some(base_id.clone())], vec![Some(left_id.clone()), Some(right_id.clone())], @@ -105,8 +105,8 @@ fn test_materialize_conflict_basic() { line 5 " ); - // Swap the positive terms in the conflict. The diff should still use the right - // side, but now the right side should come first. + // Swap the positive terms in the conflict. The diff should still use the + // right side, but now the right side should come first. let conflict = Merge::from_removes_adds( vec![Some(base_id.clone())], vec![Some(right_id.clone()), Some(left_id.clone())], @@ -669,8 +669,8 @@ fn test_materialize_conflict_no_newlines_at_eof() { >>>>>>> conflict 1 of 1 ends[EOF] " ); - // The conflict markers are parsed with the trailing newline, but it is removed - // by `update_from_content` + // The conflict markers are parsed with the trailing newline, but it is + // removed by `update_from_content` insta::assert_debug_snapshot!( parse_conflict( materialized.as_bytes(), @@ -827,8 +827,8 @@ fn test_materialize_conflict_two_forward_diffs() { Some(c_id.clone()), ], ); - // The materialized conflict should still have exactly one snapshot despite our - // attempted temptation. + // The materialized conflict should still have exactly one snapshot despite + // our attempted temptation. insta::assert_snapshot!( &materialize_conflict_string(store, path, &conflict, ConflictMarkerStyle::Diff), @r" @@ -1177,8 +1177,8 @@ fn test_parse_conflict_simple() { ) "# ); - // The conflict markers are longer than the originally materialized markers, but - // we allow them to parse anyway + // The conflict markers are longer than the originally materialized markers, + // but we allow them to parse anyway insta::assert_debug_snapshot!( parse_conflict(indoc! {b" line 1 @@ -1402,8 +1402,9 @@ fn test_parse_conflict_crlf_markers() { #[test] fn test_parse_conflict_diff_stripped_whitespace() { - // Should be able to parse conflict even if diff contains empty line (without - // even a leading space, which is sometimes stripped by text editors) + // Should be able to parse conflict even if diff contains empty line + // (without even a leading space, which is sometimes stripped by text + // editors) insta::assert_debug_snapshot!( parse_conflict( indoc! {b" @@ -1765,8 +1766,8 @@ fn test_update_conflict_from_content() -> TestResult { vec![Some(left_file_id.clone()), Some(right_file_id.clone())], ); - // If the content is unchanged compared to the materialized value, we get the - // old conflict id back. + // If the content is unchanged compared to the materialized value, we get + // the old conflict id back. let materialized = materialize_conflict_string(store, path, &conflict, ConflictMarkerStyle::Diff); let parse = |content| { @@ -1816,8 +1817,8 @@ fn test_update_conflict_from_content_modify_delete() -> TestResult { let conflict = Merge::from_removes_adds(vec![Some(before_file_id)], vec![Some(after_file_id), None]); - // If the content is unchanged compared to the materialized value, we get the - // old conflict id back. + // If the content is unchanged compared to the materialized value, we get + // the old conflict id back. let materialized = materialize_conflict_string(store, path, &conflict, ConflictMarkerStyle::Diff); let parse = |content| { @@ -1870,8 +1871,8 @@ fn test_update_conflict_from_content_simplified_conflict() -> TestResult { ); let simplified_conflict = conflict.simplify(); - // If the content is unchanged compared to the materialized value, we get the - // old conflict id back. + // If the content is unchanged compared to the materialized value, we get + // the old conflict id back. let materialized = materialize_conflict_string(store, path, &simplified_conflict, ConflictMarkerStyle::Diff); let parse = |content| { @@ -2018,8 +2019,8 @@ fn test_update_conflict_from_content_with_long_markers() -> TestResult { }; assert_eq!(parse(&conflict, materialized.as_bytes()), conflict); - // Test resolving the conflict, leaving some fake conflict markers which should - // not be parsed since they are too short + // Test resolving the conflict, leaving some fake conflict markers which + // should not be parsed since they are too short let resolved_file_contents = indoc! {" <<<<<<<<<<<< not a real conflict! ++++++++++++ @@ -2036,7 +2037,8 @@ fn test_update_conflict_from_content_with_long_markers() -> TestResult { Merge::normal(resolved_file_id) ); - // Resolve one of the conflicts, decreasing the minimum conflict marker length + // Resolve one of the conflicts, decreasing the minimum conflict marker + // length let new_conflict_contents = indoc! {" <<<<<<<<<<<<<<<< conflict 1 of 2 ++++++++++++++++ side #1 diff --git a/lib/tests/test_default_revset_graph_iterator.rs b/lib/tests/test_default_revset_graph_iterator.rs index 386281ed434..737acd48c3e 100644 --- a/lib/tests/test_default_revset_graph_iterator.rs +++ b/lib/tests/test_default_revset_graph_iterator.rs @@ -95,8 +95,8 @@ fn test_graph_iterator_virtual_octopus(skip_transitive_edges: bool, padding: u32 let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Tests that merges outside the set can result in more parent edges than there - // was in the input: + // Tests that merges outside the set can result in more parent edges than + // there was in the input: // // F // |\ @@ -194,8 +194,8 @@ fn test_graph_iterator_multiple_missing(skip_transitive_edges: bool, padding: u3 let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Tests that we get missing edges to "a" and "c" and not just one missing edge - // to the root. + // Tests that we get missing edges to "a" and "c" and not just one missing + // edge to the root. // F // / \ F // d e => /|\ @@ -239,9 +239,9 @@ fn test_graph_iterator_edge_to_ancestor(skip_transitive_edges: bool, padding: u3 let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Tests that we get both an edge from F to D and to D's ancestor C if we keep - // transitive edges and only the edge from F to D if we skip transitive - // edges: + // Tests that we get both an edge from F to D and to D's ancestor C if we + // keep transitive edges and only the edge from F to D if we skip + // transitive edges: // F F // |\ |\ // D e D : diff --git a/lib/tests/test_eol.rs b/lib/tests/test_eol.rs index 9f3d09dd47b..fdca35c2b08 100644 --- a/lib/tests/test_eol.rs +++ b/lib/tests/test_eol.rs @@ -109,10 +109,10 @@ fn test_eol_conversion_snapshot( }: Config, ) -> Vec { // This test creates snapshots with different working-copy.eol-conversion - // configurations, where proper EOL conversion should apply before writing files - // back to the store. Then files are checked out with - // working-copy.eol-conversion = "none", which won't touch the EOLs, so that we - // can tell whether the exact EOLs written to the store are expected. + // configurations, where proper EOL conversion should apply before writing + // files back to the store. Then files are checked out with + // working-copy.eol-conversion = "none", which won't touch the EOLs, so that + // we can tell whether the exact EOLs written to the store are expected. let extra_setting = format!("{extra_setting}\n"); let user_settings = base_user_settings_with_extra_configs(&extra_setting); @@ -191,8 +191,8 @@ fn test_eol_conversion_snapshot( // checkout the snapshot with the given setting, and return the content of the // file. fn create_conflict_snapshot_and_read(extra_setting: &str) -> Vec { - // Use the working-copy.eol-conversion = "none" setting to write files to the - // store as is. + // Use the working-copy.eol-conversion = "none" setting to write files to + // the store as is. let no_eol_conversion_settings = base_user_settings_with_extra_configs("working-copy.eol-conversion = \"none\"\n"); let mut test_workspace = TestWorkspace::init_with_backend_and_settings( @@ -249,8 +249,8 @@ fn create_conflict_snapshot_and_read(extra_setting: &str) -> Vec { .block_on() .unwrap(); let merge_commit = commit_with_tree(test_workspace.repo.store(), tree); - // Append new texts to the file with conflicts to make sure the last line is not - // conflict markers. + // Append new texts to the file with conflicts to make sure the last line is + // not conflict markers. test_workspace .workspace .check_out(test_workspace.repo.op_id().clone(), None, &merge_commit) @@ -276,8 +276,8 @@ fn create_conflict_snapshot_and_read(extra_setting: &str) -> Vec { // Create the new merge commit with the conflict file appended. let merge_commit = commit_with_tree(test_workspace.repo.store(), tree); - // Reload the Workspace with the working-copy.eol-conversion = "none" setting to - // check the EOL of the file written to the store previously. + // Reload the Workspace with the working-copy.eol-conversion = "none" + // setting to check the EOL of the file written to the store previously. test_workspace.workspace = Workspace::load( &no_eol_conversion_settings, test_workspace.workspace.workspace_root(), @@ -285,8 +285,8 @@ fn create_conflict_snapshot_and_read(extra_setting: &str) -> Vec { &default_working_copy_factories(), ) .expect("Failed to reload the workspace"); - // Checkout the empty commit to clear the directory, so that the test file will - // be recreated. + // Checkout the empty commit to clear the directory, so that the test file + // will be recreated. test_workspace .workspace .check_out( @@ -344,9 +344,9 @@ fn test_eol_conversion_input_snapshot_conflicts() -> TestResult { #[test] fn test_eol_conversion_none_snapshot_conflicts() -> TestResult { let contents = create_conflict_snapshot_and_read(r#"working-copy.eol-conversion = "none""#); - // We only check the last line, because it is only guaranteed that the last line - // is not the conflict markers. The conflict markers in the store are supposed - // to use the LF EOL. + // We only check the last line, because it is only guaranteed that the last + // line is not the conflict markers. The conflict markers in the store + // are supposed to use the LF EOL. let line = contents.lines_with_terminator().next_back().unwrap(); assert!( line.ends_with(b"\r\n"), @@ -401,7 +401,8 @@ fn test_eol_conversion_update_conflicts( }: UpdateConflictsTestConfig, ) -> TestResult { // Create a conflict commit with 2 given contents on one file, checkout that - // conflict with the given EOL conversion settings, and test if the EOL matches. + // conflict with the given EOL conversion settings, and test if the EOL + // matches. let extra_setting = format!("{extra_setting}\n"); let user_settings = base_user_settings_with_extra_configs(&extra_setting); @@ -516,15 +517,15 @@ fn test_eol_conversion_checkout( file_content, }: Config, ) -> Vec { - // This test checks in files with working-copy.eol-conversion = "none", so that - // the store stores files as is. Then we use jj to check out those files with - // different working-copy.eol-conversion configurations to verify if the EOLs - // are converted as expected. + // This test checks in files with working-copy.eol-conversion = "none", so + // that the store stores files as is. Then we use jj to check out those + // files with different working-copy.eol-conversion configurations to + // verify if the EOLs are converted as expected. let no_eol_conversion_settings = base_user_settings_with_extra_configs("working-copy.eol-conversion = \"none\"\n"); - // Use the working-copy.eol-conversion = "none" setting, so that the input files - // are stored as is. + // Use the working-copy.eol-conversion = "none" setting, so that the input + // files are stored as is. let mut test_workspace = TestWorkspace::init_with_backend_and_settings( TestRepoBackend::Git, &no_eol_conversion_settings, @@ -573,19 +574,19 @@ fn test_eol_conversion_checkout( .store() .get_commit(commit.id()) .expect("Failed to find the commit with the test file"); - // Check out the commit with the test file. TreeState::update should update the - // EOL accordingly. + // Check out the commit with the test file. TreeState::update should update + // the EOL accordingly. test_workspace .workspace .check_out(test_workspace.repo.op_id().clone(), None, &commit) .block_on() .unwrap(); - // When we take a snapshot now, the tree may not be clean, because the EOL our - // snapshot creates may not align with what is currently used in store. e.g. - // with working-copy.eol-conversion = "input-output", the test-eol-file may have - // CRLF line endings in the store, but the snapshot will change the EOL to LF, - // hence the diff. + // When we take a snapshot now, the tree may not be clean, because the EOL + // our snapshot creates may not align with what is currently used in + // store. e.g. with working-copy.eol-conversion = "input-output", the + // test-eol-file may have CRLF line endings in the store, but the + // snapshot will change the EOL to LF, hence the diff. assert!(std::fs::exists(&file_disk_path).unwrap()); std::fs::read(&file_disk_path).unwrap() diff --git a/lib/tests/test_fix.rs b/lib/tests/test_fix.rs index 98b3264cca9..c8e04b5667c 100644 --- a/lib/tests/test_fix.rs +++ b/lib/tests/test_fix.rs @@ -1265,8 +1265,8 @@ fn test_fix_renamed_file() -> TestResult { .store() .get_commit(summary.rewrites.get(&c2).unwrap())?; - // Since we are not using copy tracking right now, we are doing the diff against - // an empty tree. Thus, we format the whole file. + // Since we are not using copy tracking right now, we are doing the diff + // against an empty tree. Thus, we format the whole file. let expected_tree = create_tree(repo, &[(path_b, "Formatted\n")]); assert_tree_eq!(new_c2.tree(), expected_tree); Ok(()) diff --git a/lib/tests/test_git.rs b/lib/tests/test_git.rs index 5fa59a8a9da..741c15f44dd 100644 --- a/lib/tests/test_git.rs +++ b/lib/tests/test_git.rs @@ -628,10 +628,11 @@ fn test_import_refs_reimport_git_head_without_ref() -> TestResult { // Move HEAD to commit2 (by e.g. `git checkout` command) testutils::git::set_head_to_id(&git_repo, git_id(&commit2)); - // Reimport HEAD, which doesn't abandon the old HEAD branch because jj thinks it - // would be moved by `git checkout` command. This isn't always true because the - // detached HEAD commit could be rewritten by e.g. `git commit --amend` command, - // but it should be safer than abandoning old checkout branch. + // Reimport HEAD, which doesn't abandon the old HEAD branch because jj + // thinks it would be moved by `git checkout` command. This isn't always + // true because the detached HEAD commit could be rewritten by e.g. `git + // commit --amend` command, but it should be safer than abandoning old + // checkout branch. import_head(tx.repo_mut(), &test_workspace.workspace)?; git::import_refs(tx.repo_mut(), &import_options).block_on()?; tx.repo_mut().rebase_descendants().block_on()?; @@ -1349,7 +1350,8 @@ fn test_import_refs_reimport_remote_tags_deleted() -> TestResult { #[test] fn test_import_refs_reimport_git_head_with_fixed_ref() -> TestResult { - // Simulate external `git checkout` in colocated workspace, from named bookmark. + // Simulate external `git checkout` in colocated workspace, from named + // bookmark. let test_workspace = TestWorkspace::init_colocated_git(); let repo = &test_workspace.repo; let git_repo = get_git_repo(repo); @@ -1388,8 +1390,9 @@ fn test_import_refs_reimport_git_head_with_fixed_ref() -> TestResult { #[test] fn test_import_refs_reimport_all_from_root_removed() -> TestResult { - // Test that if a chain of commits all the way from the root gets unreferenced, - // we abandon the whole stack, but not including the root commit. + // Test that if a chain of commits all the way from the root gets + // unreferenced, we abandon the whole stack, but not including the root + // commit. let test_repo = TestRepo::init_with_backend(TestRepoBackend::Git); let repo = &test_repo.repo; let git_repo = get_git_repo(repo); @@ -2251,8 +2254,8 @@ fn test_import_some_refs() -> TestResult { }; assert_eq!(*view.heads(), expected_heads); - // Check that bookmarks feature[1-4] have been locally imported and are known to - // be present on origin as well. + // Check that bookmarks feature[1-4] have been locally imported and are + // known to be present on origin as well. assert_eq!(view.bookmarks().count(), 4); let commit_feat1_remote_ref = RemoteRef { target: RefTarget::normal(jj_id(commit_feat1)), @@ -2323,8 +2326,9 @@ fn test_import_some_refs() -> TestResult { ); assert!(!view.heads().contains(&jj_id(commit_ign))); - // Delete bookmark feature1, feature3 and feature4 in git repository and import - // bookmark feature2 only. That should have no impact on the jj repository. + // Delete bookmark feature1, feature3 and feature4 in git repository and + // import bookmark feature2 only. That should have no impact on the jj + // repository. delete_git_ref(&git_repo, "refs/remotes/origin/feature1"); delete_git_ref(&git_repo, "refs/remotes/origin/feature3"); delete_git_ref(&git_repo, "refs/remotes/origin/feature4"); @@ -2336,8 +2340,8 @@ fn test_import_some_refs() -> TestResult { tx.repo_mut().rebase_descendants().block_on()?; let repo = tx.commit("test").block_on()?; - // feature2 and feature4 will still be heads, and all four bookmarks should be - // present. + // feature2 and feature4 will still be heads, and all four bookmarks should + // be present. let view = repo.view(); assert_eq!(view.bookmarks().count(), 4); assert_eq!(*view.heads(), expected_heads); @@ -2544,8 +2548,8 @@ fn test_import_refs_detached_head() -> TestResult { let git_repo = get_git_repo(repo); let import_options = default_import_options(); let commit1 = empty_git_commit(&git_repo, "refs/heads/main", &[]); - // Delete the reference. Check that the detached HEAD commit still gets added to - // the set of heads + // Delete the reference. Check that the detached HEAD commit still gets + // added to the set of heads git_repo.find_reference("refs/heads/main")?.delete()?; testutils::git::set_head_to_id(&git_repo, commit1); @@ -2627,8 +2631,8 @@ fn test_import_export_head_bare_and_worktree() -> TestResult { #[test] fn test_export_refs_no_detach() -> TestResult { - // When exporting the bookmark that's current checked out, don't detach HEAD if - // the target already matches + // When exporting the bookmark that's current checked out, don't detach HEAD + // if the target already matches let test_workspace = TestWorkspace::init_colocated_git(); let repo = &test_workspace.repo; let git_repo = get_git_repo(repo); @@ -2975,7 +2979,8 @@ fn test_export_refs_current_tag_changed() -> TestResult { #[test_case(false; "without moved placeholder ref")] #[test_case(true; "with moved placeholder ref")] fn test_export_refs_unborn_git_bookmark(move_placeholder_ref: bool) -> TestResult { - // Can export to an empty Git repo (we can handle Git's "unborn bookmark" state) + // Can export to an empty Git repo (we can handle Git's "unborn bookmark" + // state) let test_workspace = TestWorkspace::init_colocated_git(); let repo = &test_workspace.repo; let git_repo = get_git_repo(repo); @@ -3024,9 +3029,9 @@ fn test_export_refs_unborn_git_bookmark(move_placeholder_ref: bool) -> TestResul #[test] fn test_export_import_sequence() -> TestResult { - // Import a bookmark pointing to A, modify it in jj to point to B, export it, - // modify it in git to point to C, then import it again. There should be no - // conflict. + // Import a bookmark pointing to A, modify it in jj to point to B, export + // it, modify it in git to point to C, then import it again. There + // should be no conflict. let test_data = GitRepoData::create(); let import_options = default_import_options(); let git_repo = test_data.git_repo; @@ -3084,8 +3089,8 @@ fn test_export_import_sequence() -> TestResult { #[test] fn test_import_export_non_tracking_bookmark() -> TestResult { - // Import a remote tracking bookmark and export it. We should not create a git - // bookmark. + // Import a remote tracking bookmark and export it. We should not create a + // git bookmark. let test_data = GitRepoData::create(); let git_repo = test_data.git_repo; let commit_main_t0 = empty_git_commit(&git_repo, "refs/remotes/origin/main", &[]); @@ -3124,8 +3129,8 @@ fn test_import_export_non_tracking_bookmark() -> TestResult { RefTarget::absent_ref() ); - // Reimport with auto-track-bookmarks on. Local bookmark shouldn't be created - // for the known bookmark "main". + // Reimport with auto-track-bookmarks on. Local bookmark shouldn't be + // created for the known bookmark "main". let commit_main_t1 = empty_git_commit(&git_repo, "refs/remotes/origin/main", &[commit_main_t0]); let commit_feat_t1 = empty_git_commit(&git_repo, "refs/remotes/origin/feat", &[]); git::import_refs(mut_repo, &auto_track_import_options()).block_on()?; @@ -3158,7 +3163,8 @@ fn test_import_export_non_tracking_bookmark() -> TestResult { }, ); - // Reimport with auto-track-bookmarks off. Tracking bookmark should be imported. + // Reimport with auto-track-bookmarks off. Tracking bookmark should be + // imported. let commit_main_t2 = empty_git_commit(&git_repo, "refs/remotes/origin/main", &[commit_main_t1]); let commit_feat_t2 = empty_git_commit(&git_repo, "refs/remotes/origin/feat", &[commit_feat_t1]); git::import_refs(mut_repo, &default_import_options()).block_on()?; @@ -3211,8 +3217,8 @@ fn test_export_conflicts() -> TestResult { assert!(stats.failed_bookmarks.is_empty()); assert!(stats.failed_tags.is_empty()); - // Create a conflict and export. It should not be exported, but other changes - // should be. + // Create a conflict and export. It should not be exported, but other + // changes should be. mut_repo.set_local_bookmark_target("main".as_ref(), RefTarget::normal(commit_b.id().clone())); let conflict_target = RefTarget::from_legacy_form( [commit_a.id().clone()], @@ -3300,8 +3306,8 @@ fn test_export_partial_failure() -> TestResult { // Branch named HEAD is disallowed by Git CLI mut_repo.set_local_bookmark_target("HEAD".as_ref(), target.clone()); mut_repo.set_local_bookmark_target("main".as_ref(), target.clone()); - // `main/sub` will conflict with `main` in Git, at least when using loose ref - // storage + // `main/sub` will conflict with `main` in Git, at least when using loose + // ref storage mut_repo.set_local_bookmark_target("main/sub".as_ref(), target.clone()); // Non-git remote tags are ignored since there are no remote tags in Git mut_repo.set_remote_tag( @@ -3344,7 +3350,8 @@ fn test_export_partial_failure() -> TestResult { FailedRefExportReason::InvalidGitName ); - // The `main` bookmark should have succeeded but the other should have failed + // The `main` bookmark should have succeeded but the other should have + // failed assert!(git_repo.find_reference("refs/heads/").is_err()); assert!(git_repo.find_reference("refs/heads/HEAD").is_err()); assert_eq!( @@ -3447,7 +3454,8 @@ fn test_export_partial_failure() -> TestResult { #[test] fn test_export_reexport_transitions() -> TestResult { - // Test exporting after making changes on the jj side, or the git side, or both + // Test exporting after making changes on the jj side, or the git side, or + // both let test_data = GitRepoData::create(); let git_repo = test_data.git_repo; let mut tx = test_data.repo.start_transaction(); @@ -3455,11 +3463,12 @@ fn test_export_reexport_transitions() -> TestResult { let commit_a = write_random_commit(mut_repo); let commit_b = write_random_commit(mut_repo); let commit_c = write_random_commit(mut_repo); - // Create a few bookmarks whose names indicate how they change in jj in git. The - // first letter represents the bookmark's target in the last export. The second - // letter represents the bookmark's target in jj. The third letter represents - // the bookmark's target in git. "X" means that the bookmark doesn't exist. - // "A", "B", or "C" means that the bookmark points to that commit. + // Create a few bookmarks whose names indicate how they change in jj in git. + // The first letter represents the bookmark's target in the last export. + // The second letter represents the bookmark's target in jj. The third + // letter represents the bookmark's target in git. "X" means that the + // bookmark doesn't exist. "A", "B", or "C" means that the bookmark + // points to that commit. // // AAB: Branch modified in git // AAX: Branch deleted in git @@ -3529,8 +3538,8 @@ fn test_export_reexport_transitions() -> TestResult { "", )?; - // TODO: The bookmarks that we made conflicting changes to should have failed to - // export. They should have been unchanged in git and in + // TODO: The bookmarks that we made conflicting changes to should have + // failed to export. They should have been unchanged in git and in // mut_repo.view().git_refs(). let stats = git::export_refs(mut_repo)?; assert_eq!( @@ -3876,7 +3885,8 @@ fn test_reset_head_with_index_no_conflict() -> TestResult { reset_head(mut_repo, &test_workspace.workspace, &wc_commit)?; // Git index should contain all files from the tree. - // `Mode(DIR | SYMLINK)` actually means `MODE(COMMIT)`, as in a git submodule. + // `Mode(DIR | SYMLINK)` actually means `MODE(COMMIT)`, as in a git + // submodule. insta::assert_snapshot!(get_index_state(workspace_root), @" Unconflicted some/dir/commit Mode(DIR | SYMLINK) Unconflicted some/dir/executable-file Mode(FILE | FILE_EXECUTABLE) @@ -3951,9 +3961,9 @@ fn test_reset_head_with_index_merge_conflict() -> TestResult { .new_commit(vec![base_commit.id().clone()], right_tree.clone()) .write_unwrap(); - // Create working copy commit with resolution of conflict by taking the right - // tree. This shouldn't affect the index, since the index is based on the parent - // commit. + // Create working copy commit with resolution of conflict by taking the + // right tree. This shouldn't affect the index, since the index is based + // on the parent commit. let wc_commit = mut_repo .new_commit( vec![left_commit.id().clone(), right_commit.id().clone()], @@ -3965,7 +3975,8 @@ fn test_reset_head_with_index_merge_conflict() -> TestResult { reset_head(mut_repo, &test_workspace.workspace, &wc_commit)?; // Index should contain conflicted files from merge of parent commits. - // `Mode(DIR | SYMLINK)` actually means `MODE(COMMIT)`, as in a git submodule. + // `Mode(DIR | SYMLINK)` actually means `MODE(COMMIT)`, as in a git + // submodule. insta::assert_snapshot!(get_index_state(workspace_root), @" Base some/dir/commit Mode(DIR | SYMLINK) Ours some/dir/commit Mode(DIR | SYMLINK) @@ -4172,8 +4183,8 @@ fn test_init() -> TestResult { ReadonlyRepo::default_submodule_store_initializer(), ) .block_on()?; - // The refs were *not* imported -- it's the caller's responsibility to import - // any refs they care about. + // The refs were *not* imported -- it's the caller's responsibility to + // import any refs they care about. assert!(!repo.view().heads().contains(&jj_id(initial_git_commit))); Ok(()) } @@ -4402,9 +4413,9 @@ fn test_fetch_no_default_branch() -> TestResult { "refs/heads/main", &[initial_git_commit], ); - // It's actually not enough to have a detached HEAD, it also needs to point to a - // commit without a bookmark (that's possibly a bug in Git *and* libgit2), so - // we point it to initial_git_commit. + // It's actually not enough to have a detached HEAD, it also needs to point + // to a commit without a bookmark (that's possibly a bug in Git *and* + // libgit2), so we point it to initial_git_commit. testutils::git::set_head_to_id(&test_data.origin_repo, initial_git_commit); let mut fetcher = GitFetch::new(tx.repo_mut(), subprocess_options, &import_options)?; @@ -4593,8 +4604,8 @@ fn test_load_default_fetch_bookmarks_invalid_configuration() -> TestResult { let git_repo = get_git_repo(&test_repo.repo); let config = git_repo.config_snapshot().clone(); - // These refspecs are already rejected by gix, but we want to assert the error - // reporting here + // These refspecs are already rejected by gix, but we want to assert the + // error reporting here std::fs::OpenOptions::new() .append(true) .open( @@ -5980,16 +5991,17 @@ fn test_push_updates_unexpectedly_moved_sideways_on_remote() -> TestResult { let temp_dir = testutils::new_temp_dir(); let setup = set_up_push_repos(&settings, &temp_dir); - // The main bookmark is actually at `main_commit` on the remote. If we expect - // it to be at `sideways_commit`, it unexpectedly moved sideways from our - // perspective. + // The main bookmark is actually at `main_commit` on the remote. If we + // expect it to be at `sideways_commit`, it unexpectedly moved sideways + // from our perspective. // // We cannot delete it or move it anywhere else. However, "moving" it to the // same place it already is is OK, following the behavior in // `test_merge_ref_targets`. // - // For each test, we check that the push succeeds if and only if the bookmark - // conflict `jj git fetch` would generate resolves to the push destination. + // For each test, we check that the push succeeds if and only if the + // bookmark conflict `jj git fetch` would generate resolves to the push + // destination. let attempt_push_expecting_sideways = |target: Option<&Commit>| { let subprocess_options = GitSubprocessOptions::from_settings(&settings).unwrap(); @@ -6073,8 +6085,9 @@ fn test_push_updates_unexpectedly_moved_forward_on_remote() -> TestResult { // actual location is the descendant of the expected location, and the new // location is the descendant of that. // - // For each test, we check that the push succeeds if and only if the bookmark - // conflict `jj git fetch` would generate resolves to the push destination. + // For each test, we check that the push succeeds if and only if the + // bookmark conflict `jj git fetch` would generate resolves to the push + // destination. let attempt_push_expecting_parent = |target: Option<&Commit>| { let subprocess_options = GitSubprocessOptions::from_settings(&settings).unwrap(); @@ -6105,11 +6118,12 @@ fn test_push_updates_unexpectedly_moved_forward_on_remote() -> TestResult { ["refs/heads/main"].map(GitRefNameBuf::from) ); - // Here, the local bookmark hasn't moved from `parent_of_main_commit`, but it - // moved to `main` on the remote. So, the conflict resolves to `main`. + // Here, the local bookmark hasn't moved from `parent_of_main_commit`, but + // it moved to `main` on the remote. So, the conflict resolves to + // `main`. // - // `jj` should not actually attempt a push in this case, but if it did, the push - // should fail. + // `jj` should not actually attempt a push in this case, but if it did, the + // push should fail. assert_eq!( push_status_rejected_references(attempt_push_expecting_parent(Some( &setup.parent_of_main_commit @@ -6133,14 +6147,15 @@ fn test_push_updates_unexpectedly_exists_on_remote() -> TestResult { let temp_dir = testutils::new_temp_dir(); let setup = set_up_push_repos(&settings, &temp_dir); - // The main bookmark is actually at `main_commit` on the remote. In this test, - // we expect it to not exist on the remote at all. + // The main bookmark is actually at `main_commit` on the remote. In this + // test, we expect it to not exist on the remote at all. // // We cannot move the bookmark backwards or sideways, but we *can* move it // forward (as a special case). // - // For each test, we check that the push succeeds if and only if the bookmark - // conflict `jj git fetch` would generate resolves to the push destination. + // For each test, we check that the push succeeds if and only if the + // bookmark conflict `jj git fetch` would generate resolves to the push + // destination. let attempt_push_expecting_absence = |target: Option<&Commit>| { let subprocess_options = GitSubprocessOptions::from_settings(&settings).unwrap(); @@ -6326,8 +6341,9 @@ fn test_bulk_update_extra_on_import_refs() -> TestResult { tx.commit("test").block_on().unwrap() }; - // Extra metadata table shouldn't be created per read_commit() call. The number - // of the table files should be way smaller than the number of the heads. + // Extra metadata table shouldn't be created per read_commit() call. The + // number of the table files should be way smaller than the number of + // the heads. let mut commit = empty_git_commit(&git_repo, "refs/heads/main", &[]); for _ in 1..10 { commit = empty_git_commit(&git_repo, "refs/heads/main", &[commit]); @@ -6413,8 +6429,9 @@ fn test_concurrent_write_commit() -> TestResult { let test_env = &test_repo.env; let repo = &test_repo.repo; - // Try to create identical commits with different change ids. Timestamp of the - // commits should be adjusted such that each commit has a unique commit id. + // Try to create identical commits with different change ids. Timestamp of + // the commits should be adjusted such that each commit has a unique + // commit id. let num_thread = 8; let (sender, receiver) = mpsc::channel(); thread::scope(|s| { @@ -6532,8 +6549,8 @@ fn test_concurrent_read_write_commit() -> TestResult { pending_commit_ids.rotate_left(i); // start lookup from different place s.spawn(move || { barrier.wait(); - // This loop should finish within a couple of retries, but terminate in case - // it doesn't. + // This loop should finish within a couple of retries, but + // terminate in case it doesn't. for _ in 0..100 { if pending_commit_ids.is_empty() { break; @@ -6546,7 +6563,8 @@ fn test_concurrent_read_write_commit() -> TestResult { .filter_map(|commit_id| { match git_backend.import_head_commits([&commit_id]) { Ok(()) => { - // update index as git::import_refs() would do + // update index as git::import_refs() would + // do let commit = repo.store().get_commit(&commit_id).unwrap(); tx.repo_mut().add_head(&commit).block_on().unwrap(); None @@ -6572,9 +6590,10 @@ fn test_concurrent_read_write_commit() -> TestResult { thread::yield_now(); } if !pending_commit_ids.is_empty() { - // It's not an error if some of the readers couldn't observe the commits. It's - // unlikely, but possible if the git backend had strong negative object cache - // for example. + // It's not an error if some of the readers couldn't observe + // the commits. It's unlikely, but + // possible if the git backend had strong negative object + // cache for example. eprintln!( "reader {i} couldn't observe the following commits: \ {pending_commit_ids:#?}" diff --git a/lib/tests/test_git_backend.rs b/lib/tests/test_git_backend.rs index aedadcd1e1b..59ad9111f43 100644 --- a/lib/tests/test_git_backend.rs +++ b/lib/tests/test_git_backend.rs @@ -428,7 +428,8 @@ fn test_jj_trees_header_with_one_tree() -> TestResult { let git_commit_id = gix::ObjectId::from_bytes_or_panic(commit.id().as_bytes()); let git_commit = git_repo.find_commit(git_commit_id)?; - // Add `jj:trees` with a single tree which is different from the Git commit tree + // Add `jj:trees` with a single tree which is different from the Git commit + // tree let mut new_commit: gix::objs::Commit = git_commit.decode()?.try_into()?; new_commit.extra_headers = vec![( JJ_TREES_COMMIT_HEADER.into(), @@ -438,8 +439,8 @@ fn test_jj_trees_header_with_one_tree() -> TestResult { let new_commit_id = CommitId::from_bytes(new_commit_id.as_bytes()); // Import new commit into `jj` repo. This should fail, because allowing a - // non-conflicted commit to have a different tree in `jj` than in Git could be - // used to hide malicious code. + // non-conflicted commit to have a different tree in `jj` than in Git could + // be used to hide malicious code. insta::assert_debug_snapshot!(git_backend.import_head_commits(std::slice::from_ref(&new_commit_id)), @r#" Err( ReadObject { @@ -465,9 +466,10 @@ fn test_conflict_headers_roundtrip() -> TestResult { let tree_6 = create_single_tree(&repo, &[(repo_path("file"), "fff")]); let tree_7 = create_single_tree(&repo, &[(repo_path("file"), "ggg")]); - // This creates a Git commit header with leading and trailing newlines to ensure - // that it can still be parsed correctly. The resulting `jj:conflict-labels` - // header value will look like `\nbase 1\nside 2\n\nside 3\n\n\n`. + // This creates a Git commit header with leading and trailing newlines to + // ensure that it can still be parsed correctly. The resulting + // `jj:conflict-labels` header value will look like `\nbase 1\nside + // 2\n\nside 3\n\n\n`. let merged_tree = MergedTree::new( repo.store().clone(), Merge::from_vec(vec![ diff --git a/lib/tests/test_gpg.rs b/lib/tests/test_gpg.rs index 7238a8f104a..094ad8fc140 100644 --- a/lib/tests/test_gpg.rs +++ b/lib/tests/test_gpg.rs @@ -474,7 +474,8 @@ fn gpgsm_invalid_signature() -> TestResult { Err(SignError::InvalidSignatureFormat) ); - // Large data: gpgsm command will exit early because the signature is invalid. + // Large data: gpgsm command will exit early because the signature is + // invalid. assert_matches!( backend.verify(&b"a".repeat(100 * 1024), signature), Err(SignError::InvalidSignatureFormat) diff --git a/lib/tests/test_id_prefix.rs b/lib/tests/test_id_prefix.rs index e6a8b113a50..7350d42e4d1 100644 --- a/lib/tests/test_id_prefix.rs +++ b/lib/tests/test_id_prefix.rs @@ -228,8 +228,8 @@ fn test_id_prefix() -> TestResult { SingleMatch(vec![commits[2].id().clone()]) ); - // Single commit in revset. Length 0 is unambiguous, but we pretend 1 digit is - // needed. + // Single commit in revset. Length 0 is unambiguous, but we pretend 1 digit + // is needed. // --------------------------------------------------------------------------------------------- let expression = RevsetExpression::commit(root_commit_id.clone()); let context = context.disambiguate_within(expression); @@ -376,9 +376,9 @@ fn test_id_prefix_divergent() -> TestResult { // - We find both commits with the same change id, even though // `third_commit_divergent_with_second` is not in the short prefix set // (#2476). - // - The short prefix set still works: we do *not* find the first commit and the - // match is not ambiguous, even though the first commit's change id would also - // match the prefix. + // - The short prefix set still works: we do *not* find the first commit and + // the match is not ambiguous, even though the first commit's change id + // would also match the prefix. assert_eq!( resolve_change_prefix(&index, prefix("a")), SingleMatch(vec![ diff --git a/lib/tests/test_index.rs b/lib/tests/test_index.rs index c0cfdc7d530..8395ca9665c 100644 --- a/lib/tests/test_index.rs +++ b/lib/tests/test_index.rs @@ -192,9 +192,10 @@ fn test_index_commits_criss_cross() -> TestResult { let num_generations = 50; - // Create a long chain of criss-crossed merges. If they were traversed without - // keeping track of visited nodes, it would be 2^50 visits, so if this test - // finishes in reasonable time, we know that we don't do a naive traversal. + // Create a long chain of criss-crossed merges. If they were traversed + // without keeping track of visited nodes, it would be 2^50 visits, so + // if this test finishes in reasonable time, we know that we don't do a + // naive traversal. let mut tx = repo.start_transaction(); let mut left_commits = vec![write_random_commit(tx.repo_mut())]; let mut right_commits = vec![write_random_commit(tx.repo_mut())]; @@ -244,8 +245,8 @@ fn test_index_commits_criss_cross() -> TestResult { ); } - // The left and right commits of the same generation should not be ancestors of - // each other + // The left and right commits of the same generation should not be ancestors + // of each other for generation in 0..num_generations { assert!(!is_ancestor( index, @@ -259,8 +260,8 @@ fn test_index_commits_criss_cross() -> TestResult { )); } - // Both sides of earlier generations should be ancestors. Check a few different - // earlier generations. + // Both sides of earlier generations should be ancestors. Check a few + // different earlier generations. for generation in 1..num_generations { for ancestor_side in &[&left_commits, &right_commits] { for descendant_side in &[&left_commits, &right_commits] { @@ -331,8 +332,9 @@ fn test_index_commits_criss_cross() -> TestResult { 2 ); - // RevWalkGenerationRange deduplicates chains by (entry, generation), which may - // be more expensive than RevWalk, but should still finish in reasonable time. + // RevWalkGenerationRange deduplicates chains by (entry, generation), which + // may be more expensive than RevWalk, but should still finish in + // reasonable time. assert_eq!( count_revs( &[left_commits[num_generations - 1].id().clone()], @@ -470,8 +472,8 @@ fn test_index_commits_incremental() -> TestResult { let test_env = &test_repo.env; let repo = &test_repo.repo; - // Create A in one operation, then B and C in another. Check that the index is - // valid after. + // Create A in one operation, then B and C in another. Check that the index + // is valid after. // o C // o B // o A diff --git a/lib/tests/test_load_repo.rs b/lib/tests/test_load_repo.rs index 8f268ae41d7..bffca97252e 100644 --- a/lib/tests/test_load_repo.rs +++ b/lib/tests/test_load_repo.rs @@ -42,8 +42,8 @@ fn test_load_at_operation() -> TestResult { let head_repo = loader.load_at_head().block_on()?; assert!(!head_repo.view().heads().contains(commit.id())); - // If we load the repo at the previous operation, we should see the commit since - // it has not been removed yet + // If we load the repo at the previous operation, we should see the commit + // since it has not been removed yet let loader = RepoLoader::init_from_file_system( &settings, test_repo.repo_path(), diff --git a/lib/tests/test_local_working_copy.rs b/lib/tests/test_local_working_copy.rs index a689d6eef90..19ca2b63503 100644 --- a/lib/tests/test_local_working_copy.rs +++ b/lib/tests/test_local_working_copy.rs @@ -145,9 +145,9 @@ fn test_root() -> TestResult { #[test_case(TestRepoBackend::Simple ; "simple backend")] #[test_case(TestRepoBackend::Git ; "git backend")] fn test_checkout_file_transitions(backend: TestRepoBackend) -> TestResult { - // Tests switching between commits where a certain path is of one type in one - // commit and another type in the other. Includes a "missing" type, so we cover - // additions and removals as well. + // Tests switching between commits where a certain path is of one type in + // one commit and another type in the other. Includes a "missing" type, + // so we cover additions and removals as well. let mut test_workspace = TestWorkspace::init_with_backend(backend); let repo = &test_workspace.repo; @@ -396,8 +396,9 @@ fn test_checkout_file_transitions(backend: TestRepoBackend) -> TestResult { #[test] fn test_checkout_no_op() -> TestResult { - // Check out another commit with the same tree that's already checked out. The - // recorded operation should be updated even though the tree is unchanged. + // Check out another commit with the same tree that's already checked out. + // The recorded operation should be updated even though the tree is + // unchanged. let mut test_workspace = TestWorkspace::init(); let repo = test_workspace.repo.clone(); @@ -734,9 +735,9 @@ fn test_reset() -> TestResult { let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap(); assert!(wc.file_states()?.contains_path(ignored_path)); - // After we reset to the commit without the file, it should still exist on disk, - // but it should not be in the tree state, and it should not get added when we - // commit the working copy (because it's ignored). + // After we reset to the commit without the file, it should still exist on + // disk, but it should not be in the tree state, and it should not get + // added when we commit the working copy (because it's ignored). let mut locked_ws = ws.start_working_copy_mutation().block_on()?; locked_ws .locked_wc() @@ -765,9 +766,9 @@ fn test_reset() -> TestResult { #[test] fn test_checkout_discard() -> TestResult { - // Start a mutation, do a checkout, and then discard the mutation. The working - // copy files should remain changed, but the state files should not be - // written. + // Start a mutation, do a checkout, and then discard the mutation. The + // working copy files should remain changed, but the state files should + // not be written. let mut test_workspace = TestWorkspace::init(); let repo = test_workspace.repo.clone(); let workspace_root = test_workspace.workspace.workspace_root().to_owned(); @@ -808,7 +809,8 @@ fn test_checkout_discard() -> TestResult { assert!(!reloaded_wc.file_states()?.contains_path(file2_path)); drop(locked_ws); - // The change should remain in the working copy, but not in memory and not saved + // The change should remain in the working copy, but not in memory and not + // saved let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap(); assert!(wc.file_states()?.contains_path(file1_path)); assert!(!wc.file_states()?.contains_path(file2_path)); @@ -1068,8 +1070,8 @@ fn test_materialize_snapshot_unchanged_conflicts() -> TestResult { ); let commit_with_labels = commit_with_tree(repo.store(), merged_tree_with_labels.clone()); - // When checking out a commit with the same conflicts but different labels, the - // file should still be updated. + // When checking out a commit with the same conflicts but different labels, + // the file should still be updated. let stats = test_workspace .workspace .check_out(repo.op_id().clone(), None, &commit_with_labels) @@ -1429,8 +1431,8 @@ fn test_snapshot_racy_timestamps() -> TestResult { #[cfg(unix)] #[test] fn test_snapshot_special_file() -> TestResult { - // Tests that we ignore when special files (such as sockets and pipes) exist on - // disk. + // Tests that we ignore when special files (such as sockets and pipes) exist + // on disk. let mut test_workspace = TestWorkspace::init(); let workspace_root = test_workspace.workspace.workspace_root().to_owned(); let ws = &mut test_workspace.workspace; @@ -1642,8 +1644,8 @@ fn test_gitignores_walk() -> TestResult { #[test] fn test_gitignores_in_ignored_dir() -> TestResult { - // Tests that .gitignore files in an ignored directory are ignored, i.e. that - // they cannot override the ignores from the parent + // Tests that .gitignore files in an ignored directory are ignored, i.e. + // that they cannot override the ignores from the parent let mut test_workspace = TestWorkspace::init(); let op_id = test_workspace.repo.op_id().clone(); @@ -1689,8 +1691,8 @@ fn test_gitignores_in_ignored_dir() -> TestResult { #[test] fn test_gitignores_checkout_never_overwrites_ignored() -> TestResult { - // Tests that a .gitignore'd file doesn't get overwritten if check out a commit - // where the file is tracked. + // Tests that a .gitignore'd file doesn't get overwritten if check out a + // commit where the file is tracked. let mut test_workspace = TestWorkspace::init(); let repo = &test_workspace.repo; @@ -1992,7 +1994,8 @@ fn test_git_submodule(gitignore_content: &str) -> TestResult { ); assert_eq!(stats.skipped_files, 0); - // Restore submodule contents (pretend that the user did `git submodule update`) + // Restore submodule contents (pretend that the user did `git submodule + // update`) testutils::write_working_copy_file( &workspace_root, added_submodule_path, @@ -2021,7 +2024,8 @@ fn test_git_submodule(gitignore_content: &str) -> TestResult { let (new_tree, _stats) = test_workspace.snapshot_with_options(&snapshot_options)?; assert_tree_eq!(new_tree, tree_id2); - // Restore submodule contents (pretend that the user did `git submodule update`) + // Restore submodule contents (pretend that the user did `git submodule + // update`) testutils::write_working_copy_file( &workspace_root, added_submodule_path, @@ -3164,7 +3168,8 @@ fn test_always_store_empty_tree() -> TestResult { test_workspace.snapshot()?; let mut buf = Vec::new(); - // Use objects.find as it doesn't short-circuit when asked for the empty tree + // Use objects.find as it doesn't short-circuit when asked for the empty + // tree let (empty_tree, _) = git_repo .objects .find(&empty_tree_id, &mut buf) diff --git a/lib/tests/test_local_working_copy_concurrent.rs b/lib/tests/test_local_working_copy_concurrent.rs index 3c074cb5d28..7370c27a96d 100644 --- a/lib/tests/test_local_working_copy_concurrent.rs +++ b/lib/tests/test_local_working_copy_concurrent.rs @@ -69,7 +69,8 @@ fn test_concurrent_checkout() -> TestResult { .block_on()?; } - // Checking out another tree (via the first workspace instance) should now fail. + // Checking out another tree (via the first workspace instance) should now + // fail. assert_matches!( ws1.check_out(repo.op_id().clone(), Some(&tree1), &commit3) .block_on(), @@ -104,8 +105,8 @@ fn test_checkout_parallel() -> TestResult { trees.push(tree); } - // Create another tree just so we can test the update stats reliably from the - // first update + // Create another tree just so we can test the update stats reliably from + // the first update let tree = create_tree(repo, &[(repo_path("other file"), "contents")]); let commit = commit_with_tree(repo.store(), tree); test_workspace @@ -136,7 +137,8 @@ fn test_checkout_parallel() -> TestResult { .block_on() .unwrap(); let commit = repo.store().get_commit(commit.id()).unwrap(); - // The operation ID is not correct, but that doesn't matter for this test + // The operation ID is not correct, but that doesn't matter for + // this test let stats = workspace .check_out(op_id, None, &commit) .block_on() @@ -144,9 +146,10 @@ fn test_checkout_parallel() -> TestResult { assert_eq!(stats.updated_files, 0); assert_eq!(stats.added_files, 1); assert_eq!(stats.removed_files, 1); - // Check that the working copy contains one of the trees. We may see a - // different tree than the one we just checked out, but since - // write_tree() should take the same lock as check_out(), write_tree() + // Check that the working copy contains one of the trees. We may + // see a different tree than the one we just + // checked out, but since write_tree() should + // take the same lock as check_out(), write_tree() // should never produce a different tree. let mut locked_ws = workspace.start_working_copy_mutation().block_on().unwrap(); let (new_tree, _stats) = locked_ws @@ -184,8 +187,9 @@ fn test_racy_checkout() -> TestResult { std::fs::read(path.to_fs_path_unchecked(&workspace_root))?, b"1".to_vec() ); - // A file written right after checkout (hopefully, from the test's perspective, - // within the file system timestamp granularity) is detected as changed. + // A file written right after checkout (hopefully, from the test's + // perspective, within the file system timestamp granularity) is + // detected as changed. write_working_copy_file(&workspace_root, path, "x"); let modified_tree = test_workspace.snapshot()?; if modified_tree.tree_ids() == tree.tree_ids() { diff --git a/lib/tests/test_local_working_copy_sparse.rs b/lib/tests/test_local_working_copy_sparse.rs index da07c675e1b..9388860383e 100644 --- a/lib/tests/test_local_working_copy_sparse.rs +++ b/lib/tests/test_local_working_copy_sparse.rs @@ -249,8 +249,8 @@ fn test_sparse_commit() -> TestResult { "modified", )?; - // Create a tree from the working copy. Only dir1/file1 should be updated in the - // tree. + // Create a tree from the working copy. Only dir1/file1 should be updated in + // the tree. let modified_tree = test_workspace.snapshot()?; let diff: Vec<_> = tree .diff_stream(&modified_tree, &EverythingMatcher) @@ -271,8 +271,8 @@ fn test_sparse_commit() -> TestResult { .block_on()?; locked_ws.finish(op_id).block_on()?; - // Create a tree from the working copy. Only dir1/file1 and dir2/file1 should be - // updated in the tree. + // Create a tree from the working copy. Only dir1/file1 and dir2/file1 + // should be updated in the tree. let modified_tree = test_workspace.snapshot()?; let diff: Vec<_> = tree .diff_stream(&modified_tree, &EverythingMatcher) @@ -286,7 +286,8 @@ fn test_sparse_commit() -> TestResult { #[test] fn test_sparse_commit_gitignore() -> TestResult { - // Test that (untracked) .gitignore files in parent directories are respected + // Test that (untracked) .gitignore files in parent directories are + // respected let mut test_workspace = TestWorkspace::init(); let repo = &test_workspace.repo; let working_copy_path = test_workspace.workspace.workspace_root().to_owned(); @@ -307,7 +308,8 @@ fn test_sparse_commit_gitignore() -> TestResult { .block_on()?; locked_ws.finish(repo.op_id().clone()).block_on()?; - // Write dir1/file1 and dir1/file2 and a .gitignore saying to ignore dir1/file1 + // Write dir1/file1 and dir1/file2 and a .gitignore saying to ignore + // dir1/file1 std::fs::write(working_copy_path.join(".gitignore"), "dir1/file1")?; std::fs::create_dir(dir1_path.to_fs_path_unchecked(&working_copy_path))?; std::fs::write( @@ -319,8 +321,8 @@ fn test_sparse_commit_gitignore() -> TestResult { "contents", )?; - // Create a tree from the working copy. Only dir1/file2 should be updated in the - // tree because dir1/file1 is ignored. + // Create a tree from the working copy. Only dir1/file2 should be updated in + // the tree because dir1/file1 is ignored. let modified_tree = test_workspace.snapshot()?; let entries = modified_tree.entries().collect_vec(); assert_eq!(entries.len(), 1); diff --git a/lib/tests/test_merged_tree.rs b/lib/tests/test_merged_tree.rs index e61712923fb..6ec25679c1a 100644 --- a/lib/tests/test_merged_tree.rs +++ b/lib/tests/test_merged_tree.rs @@ -203,9 +203,9 @@ fn test_path_value_and_entries() -> TestResult { ), ); // Get file inside file/dir conflict - // There is a conflict in the parent directory, so it is considered to not be a - // directory in the merged tree, making the file hidden until the directory - // conflict has been resolved. + // There is a conflict in the parent directory, so it is considered to not + // be a directory in the merged tree, making the file hidden until the + // directory conflict has been resolved. assert_eq!( merged_tree .path_value(file_dir_conflict_sub_path) @@ -218,8 +218,8 @@ fn test_path_value_and_entries() -> TestResult { .entries() .map(|(path, result)| (path, result.unwrap())) .collect_vec(); - // missing_path, resolved_dir_path, and file_dir_conflict_sub_path should not - // appear + // missing_path, resolved_dir_path, and file_dir_conflict_sub_path should + // not appear let expected_entries = [ resolved_file_path, conflicted_file_path, @@ -360,8 +360,8 @@ fn test_resolve_with_conflict() -> TestResult { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // The trivial conflict should be resolved but the non-trivial should not (and - // cannot) + // The trivial conflict should be resolved but the non-trivial should not + // (and cannot) let trivial_path = repo_path("dir1/trivial"); let conflict_path = repo_path("dir2/file_conflict"); @@ -1296,10 +1296,10 @@ fn test_diff_dir_file() -> TestResult { diff_stream_equals_iter(&left_merged, &right_merged, &matcher); } - // Diff while filtering by `path6` (directory1 -> file1+(directory1-absent)) as - // a file. We don't see the directory at `path6` on the left side, but we - // do see the directory that's included in the conflict with a file on the right - // side. + // Diff while filtering by `path6` (directory1 -> file1+(directory1-absent)) + // as a file. We don't see the directory at `path6` on the left side, + // but we do see the directory that's included in the conflict with a + // file on the right side. { let matcher = FilesMatcher::new([&path6]); let actual_diff: Vec<_> = left_merged @@ -1481,9 +1481,9 @@ fn test_merge_simplify_result() -> TestResult { ); // Although we pass labels here, they don't appear in the final result. The - // "side 1" label is ignored because that side is already conflicted. The "base - // 1" and "side 2" labels are used, but then those sides are removed after - // resolving and simplifying. + // "side 1" label is ignored because that side is already conflicted. The + // "base 1" and "side 2" labels are used, but then those sides are + // removed after resolving and simplifying. let merged = MergedTree::merge(Merge::from_vec(vec![ (side1_merged, "side 1".into()), (base1_merged, "base 1".into()), @@ -1536,10 +1536,11 @@ fn test_merge_simplify_result_with_resolved_labels() -> TestResult { ConflictLabels::from_vec(vec!["side 1".into(), "".into(), "side 2 left".into()]), ); - // Since side 1 is resolved, it will use the provided "side 1" label. Since side - // 2 is conflicted, its existing labels are used instead of the provided "side - // 2" label. Two of the terms from side 2 will be removed after resolving and - // simplifying. One of the terms has an empty label, which should be preserved. + // Since side 1 is resolved, it will use the provided "side 1" label. Since + // side 2 is conflicted, its existing labels are used instead of the + // provided "side 2" label. Two of the terms from side 2 will be removed + // after resolving and simplifying. One of the terms has an empty label, + // which should be preserved. let merged = MergedTree::merge(Merge::from_vec(vec![ (side1_merged, "side 1".into()), (base1_merged, "".into()), @@ -1680,10 +1681,11 @@ fn test_merge_simplify_file_conflict() -> TestResult { .block_on()?; assert_tree_eq!(merged, expected_merged); - // Also test the setup by checking that the unsimplified content conflict cannot - // be resolved. If we later change files::merge() so this no longer fails, it - // probably means that we can delete this whole test (the Merge::simplify() call - // in try_resolve_file_conflict() is just an optimization then). + // Also test the setup by checking that the unsimplified content conflict + // cannot be resolved. If we later change files::merge() so this no + // longer fails, it probably means that we can delete this whole test + // (the Merge::simplify() call in try_resolve_file_conflict() is just an + // optimization then). let text_merge = Merge::from_removes_adds( vec![Merge::from_removes_adds( vec![parent_base_text.as_bytes()], @@ -1772,8 +1774,8 @@ fn test_diff_with_trees_dir_added_removed() -> TestResult { .collect() .block_on(); - // Expecting 3 entries: the root directory, the directory itself, and the file - // inside it. + // Expecting 3 entries: the root directory, the directory itself, and the + // file inside it. assert_eq!(diff.len(), 3); // 1. Change in the root directory @@ -2266,9 +2268,10 @@ fn test_copy_diffstream_symlink_mismatch() -> TestResult { [expected_normal(path, &file_val, &symlink_val)], ); - // N.B.: this case is asymmetric because of copy-history tracking when the right - // side is a file. If we address the TODO in CopyDiffStream::poll_next(), this - // would also be a single `expected_normal` entry. + // N.B.: this case is asymmetric because of copy-history tracking when the + // right side is a file. If we address the TODO in + // CopyDiffStream::poll_next(), this would also be a single + // `expected_normal` entry. assert_eq!( collect_diffs(&right, &left), [ @@ -2600,8 +2603,8 @@ fn test_copy_diffstream_same_path_parent() -> TestResult { let test_repo = testutils::TestRepo::init(); let repo = &test_repo.repo; - // CASE: foo is recreated with a new copy history, descending from the original - // foo + // CASE: foo is recreated with a new copy history, descending from the + // original foo let foo = repo_path("foo.txt"); let foo_history1 = CopyHistory { current_path: foo.to_owned(), @@ -2879,10 +2882,10 @@ fn test_copy_diffstream_merge_twoway() -> TestResult { // // `Backend::get_related_copies()` does not fully specify an ordering // for the list of related CopyHistories. If files X and Y are both copies - // of A, then [X, Y, A] and [Y, X, A] are both valid orderings. We specify that - // the backend should always return the same ordering, so the result is - // deterministic, but the specific ordering chosen depends on the ordering of - // the `CopyId`s involved. + // of A, then [X, Y, A] and [Y, X, A] are both valid orderings. We specify + // that the backend should always return the same ordering, so the + // result is deterministic, but the specific ordering chosen depends on + // the ordering of the `CopyId`s involved. // // The current related-copy-matching in `CopyHistoryDiffStream` is dependent // on the ordering produced by the backend. So, for the case below, we @@ -2893,8 +2896,8 @@ fn test_copy_diffstream_merge_twoway() -> TestResult { // new bar -> bar // // For this particular test case and the related-copies ordering provided by - // the test backend, we end up with a copy from foo to bar, and a "normal" diff - // for foo. + // the test backend, we end up with a copy from foo to bar, and a "normal" + // diff for foo. assert_eq!( collect_diffs(&right, &left), diff --git a/lib/tests/test_mut_repo.rs b/lib/tests/test_mut_repo.rs index a9ec1faaaf9..3fdb7d0f2d8 100644 --- a/lib/tests/test_mut_repo.rs +++ b/lib/tests/test_mut_repo.rs @@ -339,8 +339,8 @@ fn test_edit_previous_empty_non_head() -> TestResult { #[test] fn test_edit_initial() -> TestResult { - // Test that MutableRepo::edit() can be used on the initial working-copy commit - // in a workspace + // Test that MutableRepo::edit() can be used on the initial working-copy + // commit in a workspace let test_repo = TestRepo::init(); let repo = &test_repo.repo; @@ -380,13 +380,13 @@ fn test_edit_hidden_commit() -> TestResult { #[test] fn test_add_head_success() -> TestResult { - // Test that MutableRepo::add_head() adds the head, and that it's still there - // after commit. It should also be indexed. + // Test that MutableRepo::add_head() adds the head, and that it's still + // there after commit. It should also be indexed. let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Create a commit outside of the repo by using a temporary transaction. Then - // add that as a head. + // Create a commit outside of the repo by using a temporary transaction. + // Then add that as a head. let mut tx = repo.start_transaction(); let new_commit = write_random_commit(tx.repo_mut()); drop(tx); @@ -407,8 +407,8 @@ fn test_add_head_success() -> TestResult { #[test] fn test_add_head_ancestor() -> TestResult { - // Test that MutableRepo::add_head() does not add a head if it's an ancestor of - // an existing head. + // Test that MutableRepo::add_head() does not add a head if it's an ancestor + // of an existing head. let test_repo = TestRepo::init(); let repo = &test_repo.repo; @@ -428,8 +428,8 @@ fn test_add_head_ancestor() -> TestResult { #[test] fn test_add_head_not_immediate_child() -> TestResult { - // Test that MutableRepo::add_head() can be used for adding a head that is not - // an immediate child of a current head. + // Test that MutableRepo::add_head() can be used for adding a head that is + // not an immediate child of a current head. let test_repo = TestRepo::init(); let repo = &test_repo.repo; @@ -463,9 +463,9 @@ fn test_add_head_not_immediate_child() -> TestResult { #[test] fn test_remove_head() -> TestResult { - // Test that MutableRepo::remove_head() removes the head, and that it's still - // removed after commit. It should remain in the index, since we otherwise would - // have to reindex everything. + // Test that MutableRepo::remove_head() removes the head, and that it's + // still removed after commit. It should remain in the index, since we + // otherwise would have to reindex everything. let test_repo = TestRepo::init(); let repo = &test_repo.repo; @@ -499,9 +499,9 @@ fn test_remove_head() -> TestResult { #[test] fn test_has_changed() -> TestResult { - // Test that MutableRepo::has_changed() reports changes iff the view has changed - // (e.g. not after setting a bookmark to point to where it was already - // pointing). + // Test that MutableRepo::has_changed() reports changes iff the view has + // changed (e.g. not after setting a bookmark to point to where it was + // already pointing). let test_repo = TestRepo::init(); let repo = &test_repo.repo; let normal_remote_ref = |id: &CommitId| RemoteRef { @@ -573,7 +573,8 @@ fn test_has_changed() -> TestResult { #[test] fn test_rebase_descendants_simple() -> TestResult { - // There are many additional tests of this functionality in `test_rewrite.rs`. + // There are many additional tests of this functionality in + // `test_rewrite.rs`. let test_repo = TestRepo::init(); let repo = &test_repo.repo; @@ -767,8 +768,8 @@ fn test_reparent_descendants() -> TestResult { // "b" and "child_b" have been kept untouched. assert_eq!(commit.id(), &rewritten_id); } else { - // All commits except "b", and "child_b" have been reparented while keeping - // their content. + // All commits except "b", and "child_b" have been reparented while + // keeping their content. assert_ne!(commit.id(), &rewritten_id); let rewritten_commit = repo.store().get_commit(&rewritten_id)?; assert_eq!(commit.tree_ids(), rewritten_commit.tree_ids()); @@ -783,8 +784,8 @@ fn test_reparent_descendants() -> TestResult { #[test] fn test_bookmark_hidden_commit() -> TestResult { - // Test that MutableRepo::set_local_bookmark_target() on a hidden commit makes - // it visible. + // Test that MutableRepo::set_local_bookmark_target() on a hidden commit + // makes it visible. let test_repo = TestRepo::init(); let repo = &test_repo.repo; let root_commit = repo.store().root_commit(); diff --git a/lib/tests/test_operations.rs b/lib/tests/test_operations.rs index fee2240257b..a9d289cd278 100644 --- a/lib/tests/test_operations.rs +++ b/lib/tests/test_operations.rs @@ -120,8 +120,8 @@ fn test_consecutive_operations() -> TestResult { assert_ne!(op_id2, op_id1); assert_eq!(list_dir(&op_heads_dir), vec![op_id2.hex()]); - // Reloading the repo makes no difference (there are no conflicting operations - // to resolve). + // Reloading the repo makes no difference (there are no conflicting + // operations to resolve). let _repo = repo.reload_at_head().block_on()?; assert_eq!(list_dir(&op_heads_dir), vec![op_id2.hex()]); Ok(()) @@ -129,8 +129,9 @@ fn test_consecutive_operations() -> TestResult { #[test] fn test_concurrent_operations() -> TestResult { - // Test that consecutive operations result in multiple op-heads on disk until - // the repo has been reloaded (which currently happens right away). + // Test that consecutive operations result in multiple op-heads on disk + // until the repo has been reloaded (which currently happens right + // away). let test_repo = TestRepo::init(); let repo = &test_repo.repo; @@ -149,8 +150,8 @@ fn test_concurrent_operations() -> TestResult { assert_ne!(op_id1, op_id0); assert_eq!(list_dir(&op_heads_dir), vec![op_id1.hex()]); - // After both transactions have committed, we should have two op-heads on disk, - // since they were run in parallel. + // After both transactions have committed, we should have two op-heads on + // disk, since they were run in parallel. let mut tx2 = repo.start_transaction(); write_random_commit(tx2.repo_mut()); let op_id2 = tx2 @@ -223,7 +224,8 @@ fn test_isolation() -> TestResult { assert_heads(repo.as_ref(), vec![initial.id()]); assert_heads(mut_repo2, vec![rewrite2.id()]); - // The base repo still doesn't see the commits after both transactions commit. + // The base repo still doesn't see the commits after both transactions + // commit. tx2.commit("transaction 2").block_on()?; assert_heads(repo.as_ref(), vec![initial.id()]); // After reload, the base repo sees both rewrites. @@ -799,8 +801,9 @@ fn test_resolve_op_parents_children() -> TestResult { let repo = testutils::commit_transactions(vec![tx1, tx2]); let parent_op_ids = repo.operation().parent_ids(); - // The subexpression that resolves to multiple operations (i.e. the accompanying - // op ids) should be reported, not the full expression provided by the user. + // The subexpression that resolves to multiple operations (i.e. the + // accompanying op ids) should be reported, not the full expression + // provided by the user. let op5_id_hex = repo.operation().id().hex(); let parents_op_str = format!("{op5_id_hex}-"); let error = op_walk::resolve_op_with_repo(&repo, &parents_op_str) diff --git a/lib/tests/test_revset.rs b/lib/tests/test_revset.rs index 68ac646808a..196e49d3a04 100644 --- a/lib/tests/test_revset.rs +++ b/lib/tests/test_revset.rs @@ -811,10 +811,11 @@ fn test_resolve_symbol_bookmarks_only() -> TestResult { ); // Typo of local/remote bookmark name: - // For "local-emote" (without @remote part), "local-remote@mirror"/"@git" aren't - // suggested since they point to the same target as "local-remote". OTOH, - // "local-remote@untracked" is suggested because non-tracking bookmark is - // unrelated to the local bookmark of the same name. + // For "local-emote" (without @remote part), "local-remote@mirror"/"@git" + // aren't suggested since they point to the same target as + // "local-remote". OTOH, "local-remote@untracked" is suggested because + // non-tracking bookmark is unrelated to the local bookmark of the same + // name. insta::assert_debug_snapshot!( resolve_symbol(mut_repo, "local-emote").unwrap_err(), @r#" NoSuchRevision { @@ -863,8 +864,8 @@ fn test_resolve_symbol_bookmarks_only() -> TestResult { ], } "#); - // "local-remote@mirror" shouldn't be omitted just because it points to the same - // target as "local-remote". + // "local-remote@mirror" shouldn't be omitted just because it points to the + // same target as "local-remote". insta::assert_debug_snapshot!( resolve_symbol(mut_repo, "remote@mirror").unwrap_err(), @r#" NoSuchRevision { @@ -1295,8 +1296,8 @@ fn test_evaluate_expression_heads() { vec![commit3.id().clone()] ); - // Heads of a grandparent and a grandchild is the grandchild (unlike Mercurial's - // heads() revset, which would include both) + // Heads of a grandparent and a grandchild is the grandchild (unlike + // Mercurial's heads() revset, which would include both) assert_eq!( resolve_commit_ids( mut_repo, @@ -1594,8 +1595,8 @@ fn test_evaluate_expression_children() { vec![commit1.id().clone()] ); - // Children of all commits in input are returned, including those already in the - // input set + // Children of all commits in input are returned, including those already in + // the input set assert_eq!( resolve_commit_ids(mut_repo, &format!("({} | {})+", commit1.id(), commit2.id())), vec![ @@ -1684,8 +1685,8 @@ fn test_evaluate_expression_ancestors() { vec![root_commit.id().clone()] ); - // Can find ancestors of a specific commit. Commits reachable via multiple paths - // are not repeated. + // Can find ancestors of a specific commit. Commits reachable via multiple + // paths are not repeated. assert_eq!( resolve_commit_ids(mut_repo, &format!("::{}", commit4.id())), vec![ @@ -1697,8 +1698,8 @@ fn test_evaluate_expression_ancestors() { ] ); - // Can find ancestors of parents or parents of ancestors, which may be optimized - // to single query + // Can find ancestors of parents or parents of ancestors, which may be + // optimized to single query assert_eq!( resolve_commit_ids(mut_repo, &format!("::({}-)", commit4.id())), vec![ @@ -1828,7 +1829,8 @@ fn test_evaluate_expression_first_ancestors() { let commit4 = write_random_commit_with_parents(mut_repo, &[&commit2, &commit3]); let commit5 = write_random_commit_with_parents(mut_repo, &[&commit3, &commit4]); - // The first-parent ancestors of the root commit is just the root commit itself + // The first-parent ancestors of the root commit is just the root commit + // itself assert_eq!( resolve_commit_ids(mut_repo, "first_ancestors(root())"), vec![root_commit.id().clone()] @@ -1900,8 +1902,8 @@ fn test_evaluate_expression_range() { let commit3 = write_random_commit_with_parents(mut_repo, &[&commit2]); let commit4 = write_random_commit_with_parents(mut_repo, &[&commit1, &commit3]); - // The range from the root to the root is empty (because the left side of the - // range is exclusive) + // The range from the root to the root is empty (because the left side of + // the range is exclusive) assert_eq!(resolve_commit_ids(mut_repo, "root()..root()"), vec![]); // Linear range @@ -2130,11 +2132,12 @@ fn test_evaluate_expression_reachable() { let mut tx = repo.start_transaction(); let mut_repo = tx.repo_mut(); - // Construct 3 separate subgraphs off the root commit. The creation of subgraphs - // 1 and 2 is interleaved so that their index positions are also interleaved. - // This makes it more likely that the tests will fail if we evaluate the revset - // predicate in the wrong order (e.g. if we check all of subgraph 1 before 2). - // 1 is a chain, 2 is a merge, 3 is a pyramidal monstrosity + // Construct 3 separate subgraphs off the root commit. The creation of + // subgraphs 1 and 2 is interleaved so that their index positions are + // also interleaved. This makes it more likely that the tests will fail + // if we evaluate the revset predicate in the wrong order (e.g. if we + // check all of subgraph 1 before 2). 1 is a chain, 2 is a merge, 3 is a + // pyramidal monstrosity let graph1commit1 = write_random_commit(mut_repo); let graph2commit1 = write_random_commit(mut_repo); let graph2commit2 = write_random_commit(mut_repo); @@ -2153,10 +2156,10 @@ fn test_evaluate_expression_reachable() { let graph3commit7 = write_random_commit_with_parents(mut_repo, &[&graph3commit4, &graph3commit5]); - // Test predicate involving ancestors, which can produce incorrect results if - // evaluated in the wrong order. The first example fails if subgraph 1 is - // evaluated before subgraph 2, and the second example fails if subgraph 2 is - // evaluated before subgraph 1. + // Test predicate involving ancestors, which can produce incorrect results + // if evaluated in the wrong order. The first example fails if subgraph + // 1 is evaluated before subgraph 2, and the second example fails if + // subgraph 2 is evaluated before subgraph 1. assert_eq!( resolve_commit_ids( mut_repo, @@ -2539,8 +2542,8 @@ fn test_evaluate_expression_bookmarks() { vec![] ); assert_eq!(resolve_commit_ids(mut_repo, "bookmarks(ookmark1)"), vec![]); - // Two bookmarks pointing to the same commit does not result in a duplicate in - // the revset + // Two bookmarks pointing to the same commit does not result in a duplicate + // in the revset mut_repo.set_local_bookmark_target( "bookmark3".as_ref(), RefTarget::normal(commit2.id().clone()), @@ -2718,8 +2721,8 @@ fn test_evaluate_expression_remote_bookmarks() { resolve_commit_ids(mut_repo, "untracked_remote_bookmarks(bookmark2)"), vec![] ); - // Two bookmarks pointing to the same commit does not result in a duplicate in - // the revset + // Two bookmarks pointing to the same commit does not result in a duplicate + // in the revset mut_repo.set_remote_bookmark( remote_symbol("bookmark3", "origin"), normal_tracked_remote_ref(commit2.id()), @@ -5248,10 +5251,11 @@ fn test_reverse_graph() -> TestResult { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Tests that merges, forks, direct edges, indirect edges, and "missing" edges - // are correct in reversed graph. "Missing" edges (i.e. edges to commits not - // in the input set) won't be part of the reversed graph. Conversely, there - // won't be missing edges to children not in the input. + // Tests that merges, forks, direct edges, indirect edges, and "missing" + // edges are correct in reversed graph. "Missing" edges (i.e. edges to + // commits not in the input set) won't be part of the reversed graph. + // Conversely, there won't be missing edges to children not in the + // input. // // F // |\ diff --git a/lib/tests/test_rewrite.rs b/lib/tests/test_rewrite.rs index bddf0a39067..88b7bbc7dbd 100644 --- a/lib/tests/test_rewrite.rs +++ b/lib/tests/test_rewrite.rs @@ -305,8 +305,8 @@ fn test_restore_tree_with_conflicts() -> TestResult { ) .block_on()?; - // After simplifying, the result should have path 1 from the left side and path - // 2 from the right side. + // After simplifying, the result should have path 1 from the left side and + // path 2 from the right side. assert_eq!( restored.path_value(path1).block_on()?.simplify(), left.path_value(path1).block_on()?.simplify() @@ -442,8 +442,8 @@ fn test_restore_tree_with_conflicts() -> TestResult { ) .block_on()?; - // After simplifying, the result should have paths 1 and 3 from the right side - // and path 2 from the left side. + // After simplifying, the result should have paths 1 and 3 from the right + // side and path 2 from the left side. assert_eq!( restored.path_value(path1).block_on()?.simplify(), right.path_value(path1).block_on()?.simplify() @@ -490,8 +490,8 @@ fn test_restore_tree_with_conflicts() -> TestResult { ) .block_on()?; - // After simplifying, the result should have paths 1 and 2 from the right side - // and path 3 from the left side. + // After simplifying, the result should have paths 1 and 2 from the right + // side and path 3 from the left side. assert_eq!( restored.path_value(path1).block_on()?.simplify(), right.path_value(path1).block_on()?.simplify() @@ -505,8 +505,8 @@ fn test_restore_tree_with_conflicts() -> TestResult { left.path_value(path3).block_on()?.simplify() ); - // path3 is updated in the existing conflict terms due to `MergedTree::resolve`. - // If we implement https://github.com/jj-vcs/jj/issues/4152, the conflict would + // path3 is updated in the existing conflict terms due to + // `MergedTree::resolve`. If we implement https://github.com/jj-vcs/jj/issues/4152, the conflict would // instead have an extra side showing the diff from the restore. let expected_side1 = create_tree( repo, @@ -583,8 +583,8 @@ fn test_rebase_descendants_forward() { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Commit B was replaced by commit F. Commits C and E should be rebased onto F. - // Commit D does not get rebased because it's an ancestor of the + // Commit B was replaced by commit F. Commits C and E should be rebased onto + // F. Commit D does not get rebased because it's an ancestor of the // destination. Commit G does not get replaced because it's already in // place. // TODO: The above is not what actually happens! The test below shows what @@ -801,8 +801,9 @@ fn test_rebase_descendants_external_merge() { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Commit C was replaced by commit F. Commits E should be rebased. The rebased - // commit E should have F as first parent and commit D as second parent. + // Commit C was replaced by commit F. Commits E should be rebased. The + // rebased commit E should have F as first parent and commit D as second + // parent. // // F // | E @@ -913,8 +914,8 @@ fn test_rebase_descendants_abandon_and_replace() { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Commit B was replaced by commit E. Commit C was abandoned. Commit D should - // get rebased onto commit E. + // Commit B was replaced by commit E. Commit C was abandoned. Commit D + // should get rebased onto commit E. // // D // C @@ -947,8 +948,8 @@ fn test_rebase_descendants_abandon_degenerate_merge_simplify() { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Commit B was abandoned. Commit D should get rebased to have only C as parent - // (not A and C). + // Commit B was abandoned. Commit D should get rebased to have only C as + // parent (not A and C). // // D // |\ @@ -1024,8 +1025,8 @@ fn test_rebase_descendants_abandon_widen_merge() { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Commit E was abandoned. Commit F should get rebased to have B, C, and D as - // parents (in that order). + // Commit E was abandoned. Commit F should get rebased to have B, C, and D + // as parents (in that order). // // F // |\ @@ -1064,8 +1065,8 @@ fn test_rebase_descendants_multiple_sideways() { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Commit B and commit D were both replaced by commit F. Commit C and commit E - // should get rebased onto it. + // Commit B and commit D were both replaced by commit F. Commit C and commit + // E should get rebased onto it. // // C E // B D F @@ -1154,10 +1155,10 @@ fn test_rebase_descendants_divergent_rewrite() { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Commit B was replaced by commit B2. Commit D was replaced by commits D2 and - // D3. Commit F was replaced by commit F2. Commit C should be rebased onto - // B2. Commit E should not be rebased. Commit G should be rebased onto - // commit F2. + // Commit B was replaced by commit B2. Commit D was replaced by commits D2 + // and D3. Commit F was replaced by commit F2. Commit C should be + // rebased onto B2. Commit E should not be rebased. Commit G should be + // rebased onto commit F2. // // G // F @@ -1221,7 +1222,8 @@ fn test_rebase_descendants_hidden() -> TestResult { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Commits B and C are hidden. C is then replaced by D. B should remain hidden. + // Commits B and C are hidden. C is then replaced by D. B should remain + // hidden. // // D // | C @@ -1565,8 +1567,9 @@ fn test_rebase_descendants_basic_bookmark_update_with_non_local_bookmark() -> Te &RefTarget::normal(commit_b.id().clone()) ); - // Commit B is no longer visible even though the remote bookmark points to it. - // (The user can still see it using e.g. the `remote_bookmarks()` revset.) + // Commit B is no longer visible even though the remote bookmark points to + // it. (The user can still see it using e.g. the `remote_bookmarks()` + // revset.) assert_eq!(*tx.repo().view().heads(), hashset! {commit_b2.id().clone()}); Ok(()) } @@ -1643,9 +1646,9 @@ fn test_rebase_descendants_update_bookmarks_after_divergent_rewrite() -> TestRes let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Bookmark "main" points to commit B. B gets rewritten as {B2, B3, B4}, then - // B4 as {B41, B42}. Bookmark main should become a conflict pointing to {B2, - // B3, B41, B42}. + // Bookmark "main" points to commit B. B gets rewritten as {B2, B3, B4}, + // then B4 as {B41, B42}. Bookmark main should become a conflict + // pointing to {B2, B3, B41, B42}. // // C other // C other | B42 main? @@ -1738,9 +1741,10 @@ fn test_rebase_descendants_rewrite_updates_bookmark_conflict() -> TestResult { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Bookmark "main" is a conflict removing commit A and adding commits B and C. - // A gets rewritten as A2 and A3. B gets rewritten as B2 and B2. The bookmark - // should become a conflict removing A and B, and adding B2, B3, C. + // Bookmark "main" is a conflict removing commit A and adding commits B and + // C. A gets rewritten as A2 and A3. B gets rewritten as B2 and B2. The + // bookmark should become a conflict removing A and B, and adding B2, + // B3, C. let mut tx = repo.start_transaction(); let commit_a = write_random_commit(tx.repo_mut()); let commit_b = write_random_commit(tx.repo_mut()); @@ -1812,13 +1816,13 @@ fn test_rebase_descendants_rewrite_resolves_bookmark_conflict() -> TestResult { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Bookmark "main" is a conflict removing ancestor commit A and adding commit B - // and C (maybe it moved forward to B locally and moved forward to C - // remotely). Now B gets rewritten as B2, which is a descendant of C (maybe - // B was automatically rebased on top of the updated remote). That - // would result in a conflict removing A and adding B2 and C. However, since C - // is a descendant of A, and B2 is a descendant of C, the conflict gets - // resolved to B2. + // Bookmark "main" is a conflict removing ancestor commit A and adding + // commit B and C (maybe it moved forward to B locally and moved forward + // to C remotely). Now B gets rewritten as B2, which is a descendant of + // C (maybe B was automatically rebased on top of the updated remote). + // That would result in a conflict removing A and adding B2 and C. + // However, since C is a descendant of A, and B2 is a descendant of C, + // the conflict gets resolved to B2. let mut tx = repo.start_transaction(); let commit_a = write_random_commit(tx.repo_mut()); let commit_b = write_random_commit_with_parents(tx.repo_mut(), &[&commit_a]); @@ -1859,14 +1863,15 @@ fn test_rebase_descendants_bookmark_delete_modify_abandon( let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Bookmark "main" initially points to commit A. One operation rewrites it to - // point to B (child of A). A concurrent operation deletes the bookmark. That - // leaves the bookmark pointing to "0-A+B". We now abandon B. + // Bookmark "main" initially points to commit A. One operation rewrites it + // to point to B (child of A). A concurrent operation deletes the + // bookmark. That leaves the bookmark pointing to "0-A+B". We now + // abandon B. // - // - If delete_abandoned_bookmarks = false, that should result in the bookmark - // pointing to "0-A+A=0". - // - If delete_abandoned_bookmarks = true, that should result in the bookmark - // pointing to "0-A+0=0". + // - If delete_abandoned_bookmarks = false, that should result in the + // bookmark pointing to "0-A+A=0". + // - If delete_abandoned_bookmarks = true, that should result in the + // bookmark pointing to "0-A+0=0". // // In both cases, the bookmark should be deleted. let mut tx = repo.start_transaction(); @@ -1906,10 +1911,10 @@ fn test_rebase_descendants_bookmark_move_forward_abandon( // rewrites it to point to A's children. That leaves the bookmark pointing // to "B-A+C". We now abandon B. // - // - If delete_abandoned_bookmarks = false, that should result in the bookmark - // pointing to "A-A+C=C", so the conflict should be resolved. - // - If delete_abandoned_bookmarks = true, that should result in the bookmark - // pointing to "0-A+C". + // - If delete_abandoned_bookmarks = false, that should result in the + // bookmark pointing to "A-A+C=C", so the conflict should be resolved. + // - If delete_abandoned_bookmarks = true, that should result in the + // bookmark pointing to "0-A+C". let mut tx = repo.start_transaction(); let commit_a = write_random_commit(tx.repo_mut()); let commit_b = write_random_commit_with_parents(tx.repo_mut(), &[&commit_a]); @@ -1960,10 +1965,10 @@ fn test_rebase_descendants_bookmark_move_sideways_abandon( // rewrites it to point to A's siblings. That leaves the bookmark pointing // to "B-A+C". We now abandon B. // - // - If delete_abandoned_bookmarks = false, that should result in the bookmark - // pointing to "A.parent-A+C". - // - If delete_abandoned_bookmarks = true, that should result in the bookmark - // pointing to "0-A+C". + // - If delete_abandoned_bookmarks = false, that should result in the + // bookmark pointing to "A.parent-A+C". + // - If delete_abandoned_bookmarks = true, that should result in the + // bookmark pointing to "0-A+C". let mut tx = repo.start_transaction(); let commit_a = write_random_commit(tx.repo_mut()); let commit_b = write_random_commit(tx.repo_mut()); @@ -2040,8 +2045,8 @@ fn test_rebase_descendants_update_checkout() -> TestResult { tx.repo_mut().rebase_descendants().block_on()?; let repo = tx.commit("test").block_on()?; - // Workspaces 1 and 2 had B checked out, so they get updated to C. Workspace 3 - // had A checked out, so it doesn't get updated. + // Workspaces 1 and 2 had B checked out, so they get updated to C. Workspace + // 3 had A checked out, so it doesn't get updated. assert_eq!(repo.view().get_wc_commit_id(&ws1_name), Some(commit_c.id())); assert_eq!(repo.view().get_wc_commit_id(&ws2_name), Some(commit_c.id())); assert_eq!(repo.view().get_wc_commit_id(&ws3_name), Some(commit_a.id())); @@ -2079,7 +2084,8 @@ fn test_rebase_descendants_update_checkout_abandoned() -> TestResult { let repo = tx.commit("test").block_on()?; // Workspaces 1 and 2 had B checked out, so they get updated to the same new - // commit on top of C. Workspace 3 had A checked out, so it doesn't get updated. + // commit on top of C. Workspace 3 had A checked out, so it doesn't get + // updated. assert_eq!( repo.view().get_wc_commit_id(&ws1_name), repo.view().get_wc_commit_id(&ws2_name) @@ -2097,8 +2103,8 @@ fn test_rebase_descendants_update_checkout_abandoned_merge() -> TestResult { let test_repo = TestRepo::init(); let repo = &test_repo.repo; - // Checked-out merge commit D was abandoned. A new merge commit should become - // checked out. + // Checked-out merge commit D was abandoned. A new merge commit should + // become checked out. // // D // |\ @@ -2226,8 +2232,8 @@ fn test_empty_commit_option(empty_behavior: EmptyBehavior) { // The commit C isn't empty. let new_commit_c = assert_rebased_onto(tx.repo_mut(), &rebase_map, &commit_c, &[commit_bd.id()]); - // D and E are empty, and F is a clean merge with only one child. Thus, F is - // also considered empty. + // D and E are empty, and F is a clean merge with only one child. + // Thus, F is also considered empty. assert_abandoned_with_parent(tx.repo_mut(), &rebase_map, &commit_d, commit_bd.id()); assert_abandoned_with_parent(tx.repo_mut(), &rebase_map, &commit_e, commit_bd.id()); assert_abandoned_with_parent(tx.repo_mut(), &rebase_map, &commit_f, new_commit_c.id()); @@ -2242,9 +2248,9 @@ fn test_empty_commit_option(empty_behavior: EmptyBehavior) { // The changes in D are included in BD, so D is newly empty. assert_abandoned_with_parent(tx.repo_mut(), &rebase_map, &commit_d, commit_bd.id()); - // E was already empty, so F is a merge commit with C and E as parents. - // Although it's empty, we still keep it because we don't want to drop merge - // commits. + // E was already empty, so F is a merge commit with C and E as + // parents. Although it's empty, we still keep it + // because we don't want to drop merge commits. let new_commit_e = assert_rebased_onto(tx.repo_mut(), &rebase_map, &commit_e, &[commit_bd.id()]); let new_commit_f = assert_rebased_onto( diff --git a/lib/tests/test_view.rs b/lib/tests/test_view.rs index 514fa68d44d..48bca399eff 100644 --- a/lib/tests/test_view.rs +++ b/lib/tests/test_view.rs @@ -132,7 +132,8 @@ fn test_merge_views_heads() -> TestResult { #[test] fn test_merge_views_checkout() -> TestResult { - // Tests merging of the view's checkout (by performing divergent operations). + // Tests merging of the view's checkout (by performing divergent + // operations). let test_repo = TestRepo::init(); let repo = &test_repo.repo; @@ -591,8 +592,8 @@ fn test_merge_views_divergent() -> TestResult { #[test_case(false ; "rewrite first")] #[test_case(true ; "add child first")] fn test_merge_views_child_on_rewritten(child_first: bool) -> TestResult { - // We start with just commit A. Operation 1 adds commit B on top. Operation 2 - // rewrites A as A2. + // We start with just commit A. Operation 1 adds commit B on top. Operation + // 2 rewrites A as A2. let test_repo = TestRepo::init(); let mut tx = test_repo.repo.start_transaction(); @@ -634,10 +635,10 @@ fn test_merge_views_child_on_rewritten_divergent( on_rewritten: bool, child_first: bool, ) -> TestResult { - // We start with divergent commits A2 and A3. Operation 1 adds commit B on top - // of A2 or A3. Operation 2 rewrites A2 as A4. The result should be that B - // gets rebased onto A4 if it was based on A2 before, but if it was based on - // A3, it should remain there. + // We start with divergent commits A2 and A3. Operation 1 adds commit B on + // top of A2 or A3. Operation 2 rewrites A2 as A4. The result should be + // that B gets rebased onto A4 if it was based on A2 before, but if it + // was based on A3, it should remain there. let test_repo = TestRepo::init(); let mut tx = test_repo.repo.start_transaction(); @@ -666,7 +667,8 @@ fn test_merge_views_child_on_rewritten_divergent( }; if on_rewritten { - // A3 should remain as a head. The other head should be B2 (B rebased onto A4). + // A3 should remain as a head. The other head should be B2 (B rebased + // onto A4). let mut heads = repo.view().heads().clone(); assert_eq!(heads.len(), 2); assert!(heads.remove(commit_a3.id())); @@ -687,8 +689,8 @@ fn test_merge_views_child_on_rewritten_divergent( #[test_case(false ; "abandon first")] #[test_case(true ; "add child first")] fn test_merge_views_child_on_abandoned(child_first: bool) -> TestResult { - // We start with commit B on top of commit A. Operation 1 adds commit C on top. - // Operation 2 abandons B. + // We start with commit B on top of commit A. Operation 1 adds commit C on + // top. Operation 2 abandons B. let test_repo = TestRepo::init(); let mut tx = test_repo.repo.start_transaction(); @@ -794,10 +796,11 @@ fn test_merge_three_operations() -> TestResult { #[test_case(false ; "operation C first")] #[test_case(true ; "operation B first")] fn test_merge_views_criss_cross(op_b_first: bool) -> TestResult { - // Consider the operation log below, where D and E are both merges of B and C. - // When merging F and E, if we pick C as common ancestor, we will get divergence - // because the working-copy commit was rewritten from K to L in operation E (but - // actually in operation B) and it was rewritten from K to M in operation F. + // Consider the operation log below, where D and E are both merges of B and + // C. When merging F and E, if we pick C as common ancestor, we will get + // divergence because the working-copy commit was rewritten from K to L + // in operation E (but actually in operation B) and it was rewritten + // from K to M in operation F. // // F wc: M // | diff --git a/lib/tests/test_workspace.rs b/lib/tests/test_workspace.rs index b159ac39f58..16ca18c1fbf 100644 --- a/lib/tests/test_workspace.rs +++ b/lib/tests/test_workspace.rs @@ -31,7 +31,8 @@ fn test_load_bad_path() { let settings = testutils::user_settings(); let test_env = TestEnvironment::init(); let workspace_root = test_env.root().to_owned(); - // We haven't created a repo in the workspace_root, so it should fail to load. + // We haven't created a repo in the workspace_root, so it should fail to + // load. let result = Workspace::load( &settings, &workspace_root, diff --git a/lib/testutils/src/git.rs b/lib/testutils/src/git.rs index 8f27529b0cb..986dc82e294 100644 --- a/lib/testutils/src/git.rs +++ b/lib/testutils/src/git.rs @@ -65,8 +65,8 @@ pub fn clone(dest_path: &Path, repo_url: &str, remote_name: Option<&str>) -> gix // gitoxide doesn't write the remote HEAD as a symbolic link, which prevents // `jj` from getting it. // - // This, plus the fact that the code to clone a repo in gitoxide is non-trivial, - // makes it appealing to just spawn a git subprocess + // This, plus the fact that the code to clone a repo in gitoxide is + // non-trivial, makes it appealing to just spawn a git subprocess let output = std::process::Command::new("git") .args(["clone", repo_url, "--origin", remote_name]) .arg(dest_path) diff --git a/lib/testutils/src/lib.rs b/lib/testutils/src/lib.rs index c0baf6db72f..0c3c91100c6 100644 --- a/lib/testutils/src/lib.rs +++ b/lib/testutils/src/lib.rs @@ -116,8 +116,9 @@ pub fn hermetic_git() { HERMETIC_GIT_CONFIGS.len().to_string(), )); for (key, value) in envs { - // SAFETY: This is actually not safe. `getenv` and `setenv` are not thread safe, - // and we can't guarantee that the following call won't have race conditions. + // SAFETY: This is actually not safe. `getenv` and `setenv` are not + // thread safe, and we can't guarantee that the following call + // won't have race conditions. unsafe { env::set_var(key, value) }; } } @@ -904,8 +905,8 @@ pub fn assert_no_forgotten_test_files(test_dir: &Path) { vec![] }; - // Add to that all submodules which are declared in the main test modules via - // `mod`. + // Add to that all submodules which are declared in the main test modules + // via `mod`. let mut test_mods: HashSet<_> = test_bin_mods .iter() .flat_map(|test_mod| { diff --git a/lib/testutils/src/proptest.rs b/lib/testutils/src/proptest.rs index 23ffd5aa77f..9698e07b496 100644 --- a/lib/testutils/src/proptest.rs +++ b/lib/testutils/src/proptest.rs @@ -217,8 +217,8 @@ impl ReferenceStateMachine for WorkingCopyReferenceStateMachine { Transition::SetDirEntry { path, dir_entry } => { assert_ne!(path.as_ref(), RepoPath::root()); let entries = &mut state.entries; - // Remove all entries which are contained within `path` (in case it is a - // pre-existing directory). + // Remove all entries which are contained within `path` (in case + // it is a pre-existing directory). entries.retain(|extant_path, _| !extant_path.starts_with(path)); for new_dir in path.ancestors().skip(1) { entries.remove(new_dir); diff --git a/lib/testutils/src/test_backend.rs b/lib/testutils/src/test_backend.rs index 87bb36bc30e..e15d8fe82b8 100644 --- a/lib/testutils/src/test_backend.rs +++ b/lib/testutils/src/test_backend.rs @@ -320,8 +320,9 @@ impl Backend for TestBackend { source: "".into(), }); } - // Return all copy histories to test that the caller correctly ignores histories - // that are not relevant to the trees they're working with. + // Return all copy histories to test that the caller correctly + // ignores histories that are not relevant to the trees + // they're working with. let mut histories = vec![]; for id in topo_order_reverse( copies.keys().sorted(), @@ -470,8 +471,8 @@ mod tests { .is_err() ); - // Looking up by any id returns the related copies in the same order (children - // before parents) + // Looking up by any id returns the related copies in the same order + // (children before parents) let related = backend.get_related_copies(©1_id).block_on()?; assert_eq!( related, From 87b7340f1aa93fa784ef8951be17a92896334140 Mon Sep 17 00:00:00 2001 From: Mustafa Officewala Date: Sun, 30 Aug 2026 09:39:35 +0530 Subject: [PATCH 2/2] fmt: Reflow comments after `cargo +nightly fmt -all` --- cli/src/cleanup_guard.rs | 4 +- cli/src/cli_util.rs | 64 +++++------ cli/src/commands/debug/tree.rs | 4 +- cli/src/commands/describe.rs | 6 +- cli/src/commands/file/untrack.rs | 4 +- cli/src/commands/fix.rs | 3 +- cli/src/commands/gerrit/upload.rs | 4 +- cli/src/commands/git/init.rs | 7 +- cli/src/commands/log.rs | 8 +- cli/src/commands/new.rs | 9 +- cli/src/commands/operation/diff.rs | 4 +- cli/src/commands/revert.rs | 7 +- cli/src/commands/run.rs | 5 +- cli/src/diff_util.rs | 6 +- cli/src/git_util.rs | 6 +- cli/src/merge_tools/builtin.rs | 21 ++-- cli/src/merge_tools/diff_working_copies.rs | 4 +- cli/src/merge_tools/external.rs | 4 +- cli/src/ui.rs | 5 +- cli/testing/fake-bisector.rs | 3 +- cli/tests/test_config_command.rs | 9 +- cli/tests/test_git_push.rs | 6 +- cli/tests/test_op_revert_command.rs | 9 +- cli/tests/test_resolve_command.rs | 3 +- core/src/dag_walk_async.rs | 3 +- core/src/diff.rs | 21 ++-- core/src/graph.rs | 8 +- core/src/str_util.rs | 17 ++- lib/src/conflicts.rs | 37 +++--- lib/src/converge.rs | 32 +++--- lib/src/copies.rs | 53 ++++----- lib/src/default_index/composite.rs | 3 +- lib/src/default_index/mutable.rs | 3 +- lib/src/default_index/readonly.rs | 4 +- lib/src/default_index/rev_walk.rs | 4 +- lib/src/default_index/revset_engine.rs | 23 ++-- .../default_index/revset_graph_iterator.rs | 8 +- lib/src/diff_presentation/mod.rs | 3 +- lib/src/files.rs | 8 +- lib/src/fix.rs | 28 +++-- lib/src/fsmonitor.rs | 6 +- lib/src/git.rs | 108 +++++++++--------- lib/src/git_backend.rs | 41 +++---- lib/src/graph_dominators.rs | 60 +++++----- lib/src/id_prefix.rs | 14 +-- lib/src/local_working_copy.rs | 49 ++++---- lib/src/lock/unix.rs | 13 +-- lib/src/merged_tree.rs | 16 ++- lib/src/merged_tree_builder.rs | 3 +- lib/src/repo.rs | 41 +++---- lib/src/revset.rs | 3 +- lib/src/rewrite.rs | 35 +++--- lib/src/simple_op_heads_store.rs | 8 +- lib/src/ssh_signing.rs | 4 +- lib/src/stacked_table.rs | 19 ++- lib/src/tree_merge.rs | 4 +- lib/src/working_copy.rs | 6 +- lib/src/workspace.rs | 7 +- lib/tests/test_bad_locking.rs | 4 +- lib/tests/test_git.rs | 14 +-- .../test_local_working_copy_concurrent.rs | 7 +- lib/tests/test_revset.rs | 3 +- lib/tests/test_rewrite.rs | 12 +- lib/tests/test_view.rs | 6 +- 64 files changed, 436 insertions(+), 507 deletions(-) diff --git a/cli/src/cleanup_guard.rs b/cli/src/cleanup_guard.rs index 7797080e002..d6671b66863 100644 --- a/cli/src/cleanup_guard.rs +++ b/cli/src/cleanup_guard.rs @@ -13,8 +13,8 @@ type GuardTable = Slab>; pub fn init() { if let Err(e) = ctrlc::set_handler(|| { // We must hold the lock for the remainder of the process's lifetime to - // avoid a race where a guard is created after we unlock but - // before we exit. + // avoid a race where a guard is created after we unlock but before we + // exit. let guards = &mut *LIVE_GUARDS.lock().unwrap(); if let Err(e) = std::panic::catch_unwind(AssertUnwindSafe(|| { for guard in guards.drain() { diff --git a/cli/src/cli_util.rs b/cli/src/cli_util.rs index 4b535ae4f99..f0f0e8740d7 100644 --- a/cli/src/cli_util.rs +++ b/cli/src/cli_util.rs @@ -503,10 +503,10 @@ impl CommandHelper { } // We detected the working copy was stale and the client is - // configured to auto-update-stale, so let's do - // that now. We need to do it up here, not at a - // lower level (e.g. inside snapshot_working_copy()) to avoid - // recursive locking of the working copy. + // configured to auto-update-stale, so let's do that now. We + // need to do it up here, not at a lower level (e.g. inside + // snapshot_working_copy()) to avoid recursive locking of the + // working copy. let WorkspaceCommandHelper { workspace, env, .. } = workspace_command; self.recover_stale_working_copy_impl(ui, workspace, env, &git_import_export_lock) .await? @@ -647,10 +647,9 @@ impl CommandHelper { workspace_command.check_working_copy_writable()?; // Snapshot the current working copy on top of the last known - // working-copy operation, then merge the - // divergent operations. The wc_commit_id of the - // merged repo wouldn't change because the old one wins, but - // it's probably fine if we picked the new + // working-copy operation, then merge the divergent operations. + // The wc_commit_id of the merged repo wouldn't change because + // the old one wins, but it's probably fine if we picked the new // wc_commit_id. let stale_stats = workspace_command .snapshot_working_copy(ui, git_import_export_lock) @@ -1410,8 +1409,8 @@ impl WorkspaceCommandHelper { .await?; let mut locked_ws = self.workspace.start_working_copy_mutation().await?; // The working copy was presumably updated by the git command that - // updated HEAD, so we just need to reset our working - // copy state to it without updating working copy files. + // updated HEAD, so we just need to reset our working copy state + // to it without updating working copy files. locked_ws.locked_wc().reset(&wc_commit).await?; tx.repo_mut().rebase_descendants().await?; self.user_repo = ReadonlyUserRepo::new( @@ -1682,8 +1681,8 @@ to the current parents may contain changes from multiple commits. .ok() .map(jj_lib::file_util::expand_home_path)?; // The configured path is usually absolute, but if it's - // relative, the "git" command would read the - // file at the work-tree directory. + // relative, the "git" command would read the file at the + // work-tree directory. Some(self.workspace_root().join(path)) } else { xdg_config_home().map(|x| x.join("git").join("ignore")) @@ -2204,8 +2203,7 @@ to the current parents may contain changes from multiple commits. .await .map_err(snapshot_command_error)?; // export_refs() is probably unnecessary because there - // should be no rewritten descendants, - // but it's harmless. + // should be no rewritten descendants, but it's harmless. let stats = jj_lib::git::export_refs(mut_repo).map_err(snapshot_command_error)?; crate::git_util::print_git_export_stats(ui, &stats) @@ -2509,10 +2507,10 @@ to the current parents may contain changes from multiple commits. let old_heads = RevsetExpression::commits(old_view.heads().iter().cloned().collect()); let new_heads = RevsetExpression::commits(new_view.heads().iter().cloned().collect()); // Filter the revsets by conflicts instead of reading all commits and - // doing the filtering here. That way, we can afford to evaluate - // the revset even if there are millions of commits added to the - // repo, assuming the revset engine can efficiently skip - // non-conflicting commits. Filter out empty commits mostly so + // doing the filtering here. That way, we can afford to evaluate the + // revset even if there are millions of commits added to the repo, + // assuming the revset engine can efficiently skip non-conflicting + // commits. Filter out empty commits mostly so // `jj new ` doesn't result in a message about new // conflicts. let conflicts = RevsetExpression::filter(RevsetFilterPredicate::HasConflict) @@ -2553,8 +2551,8 @@ to the current parents may contain changes from multiple commits. if !resolved_conflicts_by_change_id.is_empty() { // TODO: Report resolved and abandoned numbers separately. However, // that involves resolving the change_id among the visible commits - // in the new repo, which isn't currently supported by - // Google's revset engine. + // in the new repo, which isn't currently supported by Google's + // revset engine. let num_resolved: usize = resolved_conflicts_by_change_id .values() .map(|commits| commits.len()) @@ -2578,17 +2576,17 @@ to the current parents may contain changes from multiple commits. } // Hint that the user might want to `jj new` to the first conflict - // commit to resolve conflicts. Only show the hints if there - // were any new or resolved conflicts, and only if there are - // still some conflicts. + // commit to resolve conflicts. Only show the hints if there were any + // new or resolved conflicts, and only if there are still some + // conflicts. if !(added_conflict_commits.is_empty() || resolved_conflicts_by_change_id.is_empty() && new_conflicts_by_change_id.is_empty()) { // If the user just resolved some conflict and squashed them in, - // there won't be any new conflicts. Clarify to them - // that there are still some other conflicts to resolve. - // (We don't mention conflicts in commits that weren't affected by - // the operation, however.) + // there won't be any new conflicts. Clarify to them that there are + // still some other conflicts to resolve. (We don't mention + // conflicts in commits that weren't affected by the operation, + // however.) if new_conflicts_by_change_id.is_empty() { writeln!( fmt, @@ -2868,8 +2866,8 @@ impl WorkspaceCommandTransaction<'_> { writeln!(ui.status(), "Rebased {num_rebased} descendant commits.")?; } // Acquire git import/export lock before finishing the transaction to - // ensure Git HEAD export happens atomically with the - // transaction commit. + // ensure Git HEAD export happens atomically with the transaction + // commit. let git_import_export_lock = helper.lock_git_import_export()?; helper .finish_transaction(ui, tx, description, &git_import_export_lock) @@ -3172,8 +3170,9 @@ pub fn print_conflicted_paths( ); } // TODO: We might decide it's OK for `jj resolve` to ignore special - // files in the `removes` of a conflict (see e.g. https://github.com/jj-vcs/jj/pull/978). In - // that case, `conflict.removes` should be removed below. + // files in the `removes` of a conflict (see e.g. + // https://github.com/jj-vcs/jj/pull/978). In that case, + // `conflict.removes` should be removed below. for term in itertools::chain(conflict.removes(), conflict.adds()).flatten() { seen_objects.insert( match term { @@ -3669,8 +3668,7 @@ pub async fn compute_commit_location( ) .await?; // Not using `RevsetExpression::parents` here to persist the - // order of parents specified in - // `before_commits`. + // order of parents specified in `before_commits`. let new_parent_ids = before_commits .iter() .flat_map(|commit| commit.parent_ids()) diff --git a/cli/src/commands/debug/tree.rs b/cli/src/commands/debug/tree.rs index a678a67caa7..300031fddb2 100644 --- a/cli/src/commands/debug/tree.rs +++ b/cli/src/commands/debug/tree.rs @@ -66,8 +66,8 @@ pub async fn cmd_debug_tree( let store = workspace_command.repo().store(); let tree = store.get_tree(dir, &tree_id).await?; // We can't use `MergedTree` here, since it only supports iterating - // from the root, but we support a `--dir` option to - // read trees at any path. + // from the root, but we support a `--dir` option to read trees at + // any path. Box::new( tree.entries_matching(matcher.as_ref()) .map(|(path, value)| (path, Ok(Merge::normal(value)))), diff --git a/cli/src/commands/describe.rs b/cli/src/commands/describe.rs index fca54c5715c..e4b886e6fc6 100644 --- a/cli/src/commands/describe.rs +++ b/cli/src/commands/describe.rs @@ -155,9 +155,9 @@ pub(crate) async fn cmd_describe( for commit_builder in &mut commit_builders { // The first trailer would become the first line of the description. // Also, a commit with no description is treated in a special way in - // jujutsu: it can be discarded as soon as it's no - // longer the working copy. Adding a trailer to an empty - // description would break that logic. + // jujutsu: it can be discarded as soon as it's no longer the + // working copy. Adding a trailer to an empty description would + // break that logic. if use_editor || !commit_builder.description().is_empty() { let temp_commit = commit_builder.write_hidden().await?; let new_description = add_trailers_with_template(&trailer_template, &temp_commit)?; diff --git a/cli/src/commands/file/untrack.rs b/cli/src/commands/file/untrack.rs index 0040ef06cec..ad9081ef61d 100644 --- a/cli/src/commands/file/untrack.rs +++ b/cli/src/commands/file/untrack.rs @@ -98,8 +98,8 @@ Make sure they're ignored, then try again.", )); } else { // This means there were some concurrent changes made in the working - // copy. We don't want to mix those in, so reset the - // working copy again. + // copy. We don't want to mix those in, so reset the working copy + // again. locked_ws.locked_wc().reset(&new_commit).await?; } } diff --git a/cli/src/commands/fix.rs b/cli/src/commands/fix.rs index 525182ce041..eb119af59ad 100644 --- a/cli/src/commands/fix.rs +++ b/cli/src/commands/fix.rs @@ -337,8 +337,7 @@ async fn fix_one_file( compute_regions_to_format(base_content.as_deref(), &prev_content); if ranges.is_empty() && !tool_config.run_tool_if_zero_line_ranges { // Don't run the tool if there are no line ranges to format and - // the tool is configured to not run in that - // case. + // the tool is configured to not run in that case. return prev_content; } diff --git a/cli/src/commands/gerrit/upload.rs b/cli/src/commands/gerrit/upload.rs index 2b65d96ecda..b7d2c357383 100644 --- a/cli/src/commands/gerrit/upload.rs +++ b/cli/src/commands/gerrit/upload.rs @@ -582,8 +582,8 @@ pub async fn cmd_gerrit_upload( } else { // Gerrit change id is 40 chars, jj change id is 32, so we need // padding. To be consistent with - // `format_gerrit_change_id_trailer``, we pad with - // 6a6a6964 (hex of "jjid"). + // `format_gerrit_change_id_trailer``, we pad with 6a6a6964 (hex of + // "jjid"). let gerrit_change_id = format!("I{}6a6a6964", original_commit.change_id().hex()); let change_id_trailer = diff --git a/cli/src/commands/git/init.rs b/cli/src/commands/git/init.rs index a47e12403fa..d4a4a70b57e 100644 --- a/cli/src/commands/git/init.rs +++ b/cli/src/commands/git/init.rs @@ -332,10 +332,9 @@ pub fn maybe_set_repository_level_trunk_alias( .map_err(internal_error)? { // Found a HEAD reference for this remote. Even if we can't parse - // it, we should stop here and not try other remotes - // because it doesn't really make sense if "origin" were - // to be set as the default if we know "upstream" - // exists. + // it, we should stop here and not try other remotes because it + // doesn't really make sense if "origin" were to be set as the + // default if we know "upstream" exists. if let Some(reference_name) = reference.target().try_name() && let Some((GitRefKind::Bookmark, symbol)) = str::from_utf8(reference_name.as_bstr()) diff --git a/cli/src/commands/log.rs b/cli/src/commands/log.rs index 0d6d8547338..e4b1d2a34db 100644 --- a/cli/src/commands/log.rs +++ b/cli/src/commands/log.rs @@ -240,8 +240,7 @@ pub(crate) async fn cmd_log( let forward_stream = topo_order.stream(); // The input to TopoGroupedGraph shouldn't be truncated because - // the prioritized commit must exist in the - // input set. + // the prioritized commit must exist in the input set. let forward_stream = forward_stream.take(args.limit.unwrap_or(usize::MAX)); if args.reversed { let nodes: Vec<_> = forward_stream.collect().await; @@ -255,9 +254,8 @@ pub(crate) async fn cmd_log( // The graph is keyed by (CommitId, is_synthetic) let mut graphlog_edges = vec![]; // TODO: Should we update revset.stream_graph() to yield a - // `has_missing` flag instead of all the missing - // edges since we don't care about where they - // point here anyway? + // `has_missing` flag instead of all the missing edges since we + // don't care about where they point here anyway? let mut missing_edge_id = None; let mut elided_targets = vec![]; for edge in edges { diff --git a/cli/src/commands/new.rs b/cli/src/commands/new.rs index 12ac7b4bd84..6576503e689 100644 --- a/cli/src/commands/new.rs +++ b/cli/src/commands/new.rs @@ -228,9 +228,9 @@ pub(crate) async fn cmd_new( if !description.is_empty() { // The first trailer would become the first line of the description. // Also, a commit with no description is treated in a special way in - // jujutsu: it can be discarded as soon as it's no longer the - // working copy. Adding a trailer to an empty description would - // break that logic. + // jujutsu: it can be discarded as soon as it's no longer the working + // copy. Adding a trailer to an empty description would break that + // logic. commit_builder.set_description(&description); let description = add_trailers(ui, &tx, &commit_builder).await?; commit_builder.set_description(&description); @@ -248,8 +248,7 @@ pub(crate) async fn cmd_new( let mut new_parent_ids = IndexSet::new(); // If the original parents of the children commits are the parents of // the new commit, replace them with the new commit since we are - // "inserting" the new commit in between the parents and the - // children. + // "inserting" the new commit in between the parents and the children. for old_parent_id in child_commit.parent_ids() { if parent_commit_ids_set.contains(old_parent_id) { new_parent_ids.insert(new_commit.id().clone()); diff --git a/cli/src/commands/operation/diff.rs b/cli/src/commands/operation/diff.rs index 67a5d32948b..76e24c85dd7 100644 --- a/cli/src/commands/operation/diff.rs +++ b/cli/src/commands/operation/diff.rs @@ -397,8 +397,8 @@ pub async fn show_op_diff( with_content_format .write(formatter, async |formatter| { // Usually, there is at most one working copy changed per - // operation, so we put the working copy - // name in the heading. + // operation, so we put the working copy name in the + // heading. write!(formatter, "Changed working copy ")?; write!(formatter.labeled("working_copies"), "{}@", name.as_symbol())?; writeln!(formatter, ":")?; diff --git a/cli/src/commands/revert.rs b/cli/src/commands/revert.rs index cc7b949cd9c..4023c6bf8ae 100644 --- a/cli/src/commands/revert.rs +++ b/cli/src/commands/revert.rs @@ -202,10 +202,9 @@ pub(crate) async fn cmd_revert( let mut child_new_parent_ids = IndexSet::new(); for old_parent_id in rewriter.old_commit().parent_ids() { // If the original parents of the new children are the new - // parents of `target_head_ids`, replace - // them with `new_head_ids` since we are - // "inserting" the new commits in between the new parents - // and the new children. + // parents of `target_head_ids`, replace them with + // `new_head_ids` since we are "inserting" the new commits + // in between the new parents and the new children. if original_parent_commit_ids.contains(old_parent_id) { child_new_parent_ids.extend(new_head_ids.clone()); } else { diff --git a/cli/src/commands/run.rs b/cli/src/commands/run.rs index 46d620f7813..f0ab44d396a 100644 --- a/cli/src/commands/run.rs +++ b/cli/src/commands/run.rs @@ -524,9 +524,8 @@ async fn rewrite_commit( if !output.status.success() { // Remove non-ignored untracked files left by the command. Ignored paths // are absent from `untracked_paths` and survive for build-artifact - // reuse. This keeps the slot free of stale files that would - // cause silent `skipped_files` collisions in the next - // `check_out`. + // reuse. This keeps the slot free of stale files that would cause + // silent `skipped_files` collisions in the next `check_out`. for path in stats.untracked_paths.keys() { let abs = path.to_fs_path_unchecked(&working_copy_dir); if let Err(err) = fs::remove_file(&abs) diff --git a/cli/src/diff_util.rs b/cli/src/diff_util.rs index cf257b7c72f..9f2db55ceb0 100644 --- a/cli/src/diff_util.rs +++ b/cli/src/diff_util.rs @@ -2157,9 +2157,9 @@ pub fn show_diff_stats( if let Some((added, removed)) = stat.added_removed { let bar_length = ((added + removed) as f64 * factor) as usize; // If neither adds nor removes are present, bar length should be - // zero. If only one is present, bar length should be at - // least 1. If both are present, bar length should be at - // least 2. + // zero. + // If only one is present, bar length should be at least 1. + // If both are present, bar length should be at least 2. // // Fractional space after scaling is given to whichever of // adds/removes is smaller, to show at least one tick diff --git a/cli/src/git_util.rs b/cli/src/git_util.rs index 293c7a01302..d25c9acfd38 100644 --- a/cli/src/git_util.rs +++ b/cli/src/git_util.rs @@ -76,9 +76,9 @@ pub fn is_colocated_git_workspace(workspace: &Workspace) -> Result Result { // Git appears to turn URL-like source to absolute path if local git // directory exits, and fails because '$PWD/https' is unsupported - // protocol. Since it would be tedious to copy the exact git (or - // libgit2) behavior, we simply let gix parse the input as URL, - // rcp-like, or local path. + // protocol. Since it would be tedious to copy the exact git (or libgit2) + // behavior, we simply let gix parse the input as URL, rcp-like, or local + // path. let mut url = gix::url::parse(source).map_err(cli_error)?; url.canonicalize(cwd).map_err(user_error)?; // As of gix 0.68.0, the canonicalized path uses platform-native directory diff --git a/cli/src/merge_tools/builtin.rs b/cli/src/merge_tools/builtin.rs index 50d5ffa63af..32e3e6174ca 100644 --- a/cli/src/merge_tools/builtin.rs +++ b/cli/src/merge_tools/builtin.rs @@ -1019,11 +1019,11 @@ mod tests { create_right_tree: impl FnOnce(&Arc, &RepoPath, bool) -> MergedTree, ) { // In this test, we create 2 trees that consist of only one file under - // the same path. The executable bits are the same. Either of - // the left tree and the right tree can be resolved or have - // conflicts. Regardless of whether the file is resolved or have - // conflicts, the file has the same executable bit in both - // trees, so we don't expect a file mode section in the diff. + // the same path. The executable bits are the same. Either of the left + // tree and the right tree can be resolved or have conflicts. + // Regardless of whether the file is resolved or have conflicts, the + // file has the same executable bit in both trees, so we don't expect + // a file mode section in the diff. let test_repo = TestRepo::init(); let store = test_repo.repo.store(); @@ -1928,8 +1928,8 @@ mod tests { "#); let no_changes_tree = apply_diff(store, &left_tree, &right_tree, &changed_files, &files); // TODO: we should ensure that `jj diffedit` preserves labels when - // restoring a conflict. It also should work when restoring - // conflicts of differing arities. + // restoring a conflict. It also should work when restoring conflicts + // of differing arities. let left_tree_without_labels = MergedTree::new( left_tree.store().clone(), left_tree.tree_ids().clone(), @@ -2342,8 +2342,7 @@ mod tests { } if !did_file_exist && is_anything_selected { // File was created, so if any changes are selected, - // then so must the file - // mode change. + // then so must the file mode change. file.sections[0].set_checked(true); } } @@ -2392,8 +2391,8 @@ mod tests { file.old_path = None; // Only keep sections which weren't selected previously. For - // text files, transform additions which have - // already been applied into `Unchanged` hunks. + // text files, transform additions which have already been + // applied into `Unchanged` hunks. file.sections = std::mem::take(&mut file.sections) .into_iter() .flat_map(|sec| { diff --git a/cli/src/merge_tools/diff_working_copies.rs b/cli/src/merge_tools/diff_working_copies.rs index 1741a2c4502..816f17564be 100644 --- a/cli/src/merge_tools/diff_working_copies.rs +++ b/cli/src/merge_tools/diff_working_copies.rs @@ -274,8 +274,8 @@ diff editing in mind and be a little inaccurate. .write_all(instructions.as_bytes()) .map_err(ExternalToolError::SetUpDir)?; // Note that some diff tools might not show this message and delete - // the contents of the output dir instead. Meld does - // show this message. + // the contents of the output dir instead. Meld does show this + // message. output_instructions_file .write_all( b"\ diff --git a/cli/src/merge_tools/external.rs b/cli/src/merge_tools/external.rs index 4f90c33f5e9..dc2974263c9 100644 --- a/cli/src/merge_tools/external.rs +++ b/cli/src/merge_tools/external.rs @@ -370,8 +370,8 @@ pub async fn run_mergetool_external( } Err(err) => { // Some conflicts were already resolved, so we should return an - // error with the partially-resolved tree so - // that the caller can save the resolved files. + // error with the partially-resolved tree so that the caller can + // save the resolved files. partial_resolution_error = Some(MergeToolPartialResolutionError { source: err, resolved_count: i, diff --git a/cli/src/ui.rs b/cli/src/ui.rs index 43e98d4cb27..9f006cab58c 100644 --- a/cli/src/ui.rs +++ b/cli/src/ui.rs @@ -122,9 +122,8 @@ impl UiOutput { drop(child_stdin); if let Err(err) = child.wait() { // It's possible (though unlikely) that this write fails, - // but this function gets called so late - // that there's not much we can do about - // it. + // but this function gets called so late that there's not + // much we can do about it. writeln!( ui.warning_default(), "Failed to wait on pager: {err}", diff --git a/cli/testing/fake-bisector.rs b/cli/testing/fake-bisector.rs index 725d3003124..d78794fad68 100644 --- a/cli/testing/fake-bisector.rs +++ b/cli/testing/fake-bisector.rs @@ -51,8 +51,7 @@ fn main() { let mut instructions = edit_script.split('\0').collect_vec(); if let Some(pos) = instructions.iter().position(|&i| i == "next invocation\n") { // Overwrite the edit script. The next time `fake-bisector` is called, - // it will only see the part after the `next invocation` - // command. + // it will only see the part after the `next invocation` command. fs::write(&edit_script_path, instructions[pos + 1..].join("\0")).unwrap(); instructions.truncate(pos); } diff --git a/cli/tests/test_config_command.rs b/cli/tests/test_config_command.rs index a0d891b9777..41d7c1bc410 100644 --- a/cli/tests/test_config_command.rs +++ b/cli/tests/test_config_command.rs @@ -1349,11 +1349,10 @@ fn test_config_get_yields_values_consistent_with_schema_defaults() -> TestResult let output_doc = toml_edit::Document::parse(format!("test={}", output.stdout.normalized())) .unwrap_or_else(|_| { // Unfortunately for this test, `config get` is "lossy" and does - // not print quoted strings. This means that - // e.g. `false` and `"false"` are not - // distinguishable. If value couldn't be parsed, it's probably a - // string, so let's parse its Debug string - // instead. + // not print quoted strings. This means that e.g. `false` and + // `"false"` are not distinguishable. If value couldn't be + // parsed, it's probably a string, so let's parse its Debug + // string instead. toml_edit::Document::parse(format!("test={:?}", output.stdout.normalized().trim())) .unwrap() }); diff --git a/cli/tests/test_git_push.rs b/cli/tests/test_git_push.rs index 1447d6fe8a2..eb4a15f31ac 100644 --- a/cli/tests/test_git_push.rs +++ b/cli/tests/test_git_push.rs @@ -2425,11 +2425,9 @@ fn test_git_push_tracked_vs_all() { // All bookmarks are still untracked. // - --all tries to push bookmark1, but fails because a bookmark with the - // same - // name exist on the remote. + // same name exist on the remote. // - --all succeeds in pushing bookmark3, since there is no bookmark of the - // same - // name on the remote. + // same name on the remote. // - It does not try to push bookmark2. // // TODO: Not trying to push bookmark2 could be considered correct, or diff --git a/cli/tests/test_op_revert_command.rs b/cli/tests/test_op_revert_command.rs index 03b7229b71a..be38c393b5c 100644 --- a/cli/tests/test_op_revert_command.rs +++ b/cli/tests/test_op_revert_command.rs @@ -227,8 +227,9 @@ fn test_git_push_revert_with_import() { "); // PROBLEM: inserting this import changes the outcome compared to previous - // test TODO: decide if this is the better behavior, and whether import - // of remote-tracking bookmarks should happen on every operation. + // test + // TODO: decide if this is the better behavior, and whether import of + // remote-tracking bookmarks should happen on every operation. work_dir.run_jj(["git", "import"]).success(); // | jj refs | jj's | git // | | git | repo @@ -327,8 +328,8 @@ fn test_git_push_revert_colocated() { test_env.advance_test_rng_seed_to_multiple_of(100_000); work_dir.run_jj(["describe", "-m", "CC"]).success(); work_dir.run_jj(["git", "fetch"]).success(); - // We have the same conflict as `test_git_push_revert`. TODO: why did we get - // the same result in a seemingly different way? + // We have the same conflict as `test_git_push_revert`. + // TODO: why did we get the same result in a seemingly different way? insta::assert_snapshot!(get_bookmark_output(&work_dir), @" main (conflicted): - qpvuntsm/2 3a44d6c5 (hidden) (empty) AA diff --git a/cli/tests/test_resolve_command.rs b/cli/tests/test_resolve_command.rs index afe513b4e71..32c7669a0d9 100644 --- a/cli/tests/test_resolve_command.rs +++ b/cli/tests/test_resolve_command.rs @@ -765,7 +765,8 @@ fn test_simplify_conflict_sides() -> TestResult { let work_dir = test_env.work_dir("repo"); // Creates a 4-sided conflict, with fileA and fileB having different - // conflicts: fileA: A - B + C - B + B - B + B + // conflicts: + // fileA: A - B + C - B + B - B + B // fileB: A - A + A - A + B - C + D create_commit_with_files( &work_dir, diff --git a/core/src/dag_walk_async.rs b/core/src/dag_walk_async.rs index b27d9a82ca5..2c622bf81f0 100644 --- a/core/src/dag_walk_async.rs +++ b/core/src/dag_walk_async.rs @@ -1507,8 +1507,7 @@ mod tests { fn test_closest_common_nodes_many_paths() { // One side has very many possible paths due to repeated forking and // merging. We must not walk the exponential number of paths - // between A and MN when finding common ancestors between MN and - // B. + // between A and MN when finding common ancestors between MN and B. // // MN // |\ diff --git a/core/src/diff.rs b/core/src/diff.rs index efc0741d2b2..dc2be42c055 100644 --- a/core/src/diff.rs +++ b/core/src/diff.rs @@ -392,8 +392,8 @@ fn find_lcs(input: &[usize]) -> Vec<(usize, usize)> { global_longest = len; global_longest_right_pos = right_pos; // If this is the longest chain globally so far, we - // cannot find a longer one by - // using a previous value, so break early. + // cannot find a longer one by using a previous value, + // so break early. break; } } @@ -814,9 +814,9 @@ impl<'input> ContentDiff<'input> { for window in self.unchanged_regions.windows(2) { let [previous, current]: &[_; 2] = window.try_into().unwrap(); // For the changed region between the previous region and the - // current one, create a new Diff instance. Then adjust - // the start positions and offsets to be valid in the - // context of the larger Diff instance (`self`). + // current one, create a new Diff instance. Then adjust the start + // positions and offsets to be valid in the context of the larger + // Diff instance (`self`). let refined_diff = ContentDiff::for_tokenizer( self.hunk_between(previous, current), &tokenizer, @@ -1601,12 +1601,11 @@ mod tests { #[test] fn test_diff_real_case_write_fmt() { // This is from src/ui.rs in commit f44d246e3f88 in this repo. It - // highlights the need for recursion into the range at the end: - // after splitting at "Arguments" and "formatter", the region at - // the end has the unique words "write_fmt" and "fmt", but we - // forgot to recurse into that region, so we ended up - // saying that "write_fmt(fmt).unwrap()" was replaced by - // b"write_fmt(fmt)". + // highlights the need for recursion into the range at the end: after + // splitting at "Arguments" and "formatter", the region at the end has + // the unique words "write_fmt" and "fmt", but we forgot to recurse + // into that region, so we ended up saying that + // "write_fmt(fmt).unwrap()" was replaced by b"write_fmt(fmt)". #[rustfmt::skip] assert_eq!( diff([ diff --git a/core/src/graph.rs b/core/src/graph.rs index 34fb4b1ea78..1eeb057eb59 100644 --- a/core/src/graph.rs +++ b/core/src/graph.rs @@ -268,10 +268,10 @@ where let new_head_id = self.new_head_ids.remove(index).unwrap(); // Unmark ancestors of the selected head so they won't contribute to - // future new-head resolution within the newly-unblocked sub - // graph. The sub graph can have many fork points, and the - // corresponding heads should be picked in the fork-point order, - // not in the head appearance order. + // future new-head resolution within the newly-unblocked sub graph. + // The sub graph can have many fork points, and the corresponding + // heads should be picked in the fork-point order, not in the head + // appearance order. to_visit.push(&new_head_id); visited.remove(&new_head_id); while let Some(id) = to_visit.pop() { diff --git a/core/src/str_util.rs b/core/src/str_util.rs index d22967e463f..c793d5996c1 100644 --- a/core/src/str_util.rs +++ b/core/src/str_util.rs @@ -57,8 +57,8 @@ impl GlobPattern { /// Converts this glob pattern to a bytes regex. pub fn to_regex(&self) -> regex::bytes::Regex { // Based on new_regex() in globset. We don't use - // GlobMatcher::is_match(path) because the input string - // shouldn't be normalized as path. + // GlobMatcher::is_match(path) because the input string shouldn't be + // normalized as path. regex::bytes::RegexBuilder::new(self.glob.regex()) .dot_matches_new_line(true) .build() @@ -204,8 +204,8 @@ impl StringPattern { /// This can be used to optimize map lookup by exact key. pub fn as_exact(&self) -> Option<&str> { // TODO: Handle trivial case‐insensitive patterns here? It might make - // people expect they can use case‐insensitive patterns in - // contexts where they generally can’t. + // people expect they can use case‐insensitive patterns in contexts + // where they generally can’t. match self { Self::Exact(literal) => Some(literal), _ => None, @@ -230,8 +230,8 @@ impl StringPattern { /// can't be represented as a glob. pub fn to_glob(&self) -> Option> { // TODO: Handle trivial case‐insensitive patterns here? It might make - // people expect they can use case‐insensitive patterns in - // contexts where they generally can’t. + // people expect they can use case‐insensitive patterns in contexts + // where they generally can’t. match self { Self::Exact(literal) => Some(globset::escape(literal).into()), Self::Substring(needle) => { @@ -264,9 +264,8 @@ impl StringPattern { // standard case‐insensitivity of haystack components (like // internationalized domain names in email addresses). The // availability of normalization and case folding schemes in database - // backends will also need to be considered. A locale‐specific - // case folding scheme would likely not be appropriate for - // Jujutsu. + // backends will also need to be considered. A locale‐specific case + // folding scheme would likely not be appropriate for Jujutsu. // // For some discussion of this topic, see: // diff --git a/lib/src/conflicts.rs b/lib/src/conflicts.rs index f03eaff5bc5..bad89246331 100644 --- a/lib/src/conflicts.rs +++ b/lib/src/conflicts.rs @@ -523,10 +523,9 @@ fn materialize_conflict_hunks( let conflict_info = format!("conflict {conflict_index} of {num_conflicts}"); // If any side doesn't have the ending EOL, we remove the ending EOL - // from the conflict end marker line and "spread" the - // ending EOL to every side as a separator, so that - // contents without an ending EOL won't be concatenated with - // the conflict markers. + // from the conflict end marker line and "spread" the ending EOL to + // every side as a separator, so that contents without an ending EOL + // won't be concatenated with the conflict markers. let all_sides_have_ending_eol = hunk .iter() .all(|content| content.last().is_none_or(|last| *last == b'\n')); @@ -746,9 +745,9 @@ fn materialize_jj_style_conflict( .hunks() .collect_vec(); // If we haven't written a snapshot yet, then we need to decide whether - // to format the current side as a snapshot or a diff. We write - // the current side as a diff unless the next side has a smaller - // diff compared to the current base. + // to format the current side as a snapshot or a diff. We write the + // current side as a diff unless the next side has a smaller diff + // compared to the current base. if !snapshot_written { let right2 = hunk.get_add(add_index + 1).unwrap(); let diff2 = ContentDiff::by_line([&left.contents, &right2.contents]) @@ -756,8 +755,8 @@ fn materialize_jj_style_conflict( .collect_vec(); if diff_size(&diff2) < diff_size(&diff1) { // If the next positive term is a better match, emit the current - // positive term as a snapshot and the next - // positive term as a diff. + // positive term as a snapshot and the next positive term as a + // diff. write_side(right1, output)?; write_diff(left, right2, &diff2, output)?; snapshot_written = true; @@ -871,13 +870,11 @@ pub fn parse_conflict( } if !line.ends_with(b"\n") { // If the conflict end marker doesn't end with an - // EOL, the last EOL on - // every side performs only as a separator, and we - // need to do remove the - // last EOL to retrieve the original contents. That - // separator is the EOL - // which terminates the conflict start marker line, - // so only drop a CR if + // EOL, the last EOL on every side performs only as + // a separator, and we need to do remove the last + // EOL to retrieve the original contents. That + // separator is the EOL which terminates the + // conflict start marker line, so only drop a CR if // that EOL was CRLF. Otherwise the CR belongs to // the contents. for term in &mut hunk { @@ -981,10 +978,10 @@ fn parse_jj_style_conflict_hunk(input: &[u8], expected_marker_len: usize) -> Mer adds.last_mut().unwrap().extend_from_slice(rest); } else if line == b"\n" || line == b"\r\n" { // Some editors strip trailing whitespace, so " \n" might - // become "\n". It would be unfortunate - // if this prevented the conflict from being parsed, so we - // add the empty line to the "remove" - // and "add" as if there was a space in front + // become "\n". It would be unfortunate if this prevented + // the conflict from being parsed, so we add the empty line + // to the "remove" and "add" as if there was a space in + // front removes.last_mut().unwrap().extend_from_slice(line); adds.last_mut().unwrap().extend_from_slice(line); } else { diff --git a/lib/src/converge.rs b/lib/src/converge.rs index 785018ae8f8..0f5759260a6 100644 --- a/lib/src/converge.rs +++ b/lib/src/converge.rs @@ -289,15 +289,14 @@ impl TruncatedEvolutionGraph { to_visit.remove(commit_id); if !seen.insert(commit_id.clone()) { // TODO: think about this some more. Can 2 different operations - // result in the same commit? Maybe the key - // should be (commit-id, operation-id). + // result in the same commit? Maybe the key should be + // (commit-id, operation-id). // Note: currently walk_predecessors returns an error if the - // graph is cyclic, so we shouldn't encounter - // the same commit twice. But in the future we could - // allow cyclic evolution, and if we do there is no reason to - // disallow it here. By continuing we future - // proof this. + // graph is cyclic, so we shouldn't encounter the same commit + // twice. But in the future we could allow cyclic evolution, + // and if we do there is no reason to disallow it here. By + // continuing we future proof this. continue; } let predecessors = entry @@ -335,9 +334,8 @@ impl TruncatedEvolutionGraph { initial_nodes[0].clone() } else { // In graphs with multiple "real" initial nodes we introduce a - // virtual initial node (the root commit) and pretend - // the two or more "real" initial nodes are successors - // of the root commit. + // virtual initial node (the root commit) and pretend the two or + // more "real" initial nodes are successors of the root commit. let root_commit_id = repo.store().root_commit_id().clone(); for initial_node in initial_nodes { edges.push((root_commit_id.clone(), initial_node)); @@ -414,9 +412,8 @@ async fn converge_parents( graph: &TruncatedEvolutionGraph, ) -> Result>, ConvergeError> { // Filter out divergent commits that are descendants of other divergent - // commits (we cannot use the parents of those commits because that - // would introduce cycles when we rebase everything on top of the - // parents). + // commits (we cannot use the parents of those commits because that would + // introduce cycles when we rebase everything on top of the parents). let viable_commits = remove_descendants(graph.repo(), graph.divergent_commit_ids()).await?; let excluded_divergent_commits: HashSet = graph .divergent_commit_ids() @@ -516,9 +513,9 @@ async fn converge_trees( .unwrap() .insert(commit.id().clone(), tree_ids_and_labels.clone()); // Note we only return the tree ids here, not the labels. We do that to - // increase the chances of finding a common dominator value that - // is closer to the divergent commits, ideally one that result - // in a simple merge of the trees later on. + // increase the chances of finding a common dominator value that is + // closer to the divergent commits, ideally one that result in a simple + // merge of the trees later on. Ok(tree_ids_and_labels.tree_ids.clone()) }; @@ -657,8 +654,7 @@ where // as having maximum change-offset and use input-order as the secondary // sorting criterion. By input-order we refer to the order of commits // passed to converge_change. But some commits are not given as input, - // so we use commit timestamp and CommitId as additional sorting - // criteria. + // so we use commit timestamp and CommitId as additional sorting criteria. let resolved_change_targets = truncated_evolution_graph .repo() diff --git a/lib/src/copies.rs b/lib/src/copies.rs index c39097ddf7c..fcd5bd2345e 100644 --- a/lib/src/copies.rs +++ b/lib/src/copies.rs @@ -67,10 +67,10 @@ impl CopyRecords { pub fn add_records(&mut self, copy_records: impl IntoIterator) { for r in copy_records { // The same copy or rename is reported once per parent when diffing - // a merge commit. Identical (source, target) pairs - // describe the same operation, so skip the duplicate - // instead of marking both maps as conflicting, which - // would otherwise drop the copy/rename entirely. + // a merge commit. Identical (source, target) pairs describe the + // same operation, so skip the duplicate instead of marking both + // maps as conflicting, which would otherwise drop the copy/rename + // entirely. let is_duplicate = self .targets .get(&r.target) @@ -418,15 +418,13 @@ impl Stream for CopyHistoryDiffStream<'_> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { // First, check if we have newly-finished futures. If this returns - // Pending, we intentionally fall through to poll - // `self.inner`. + // Pending, we intentionally fall through to poll `self.inner`. if let Poll::Ready(Some(next)) = self.pending.poll_next_unpin(cx) { return Poll::Ready(Some(next)); } // If we didn't have queued results above, we want to check our - // wrapped stream for the next non-copy-matched diff - // entry. + // wrapped stream for the next non-copy-matched diff entry. let next_diff_entry = match ready!(self.inner.poll_next_unpin(cx)) { Some(diff_entry) => diff_entry, None if self.pending.is_empty() => return Poll::Ready(None), @@ -475,30 +473,23 @@ impl Stream for CopyHistoryDiffStream<'_> { (other, Some(f @ TreeValue::File { .. })) => { if let Some(other) = other { // For files with non-matching copy-ids, or for a - // non-file that changes to a - // file, mark the first as deleted and do copy-tracing - // on the second. + // non-file that changes to a file, mark the first as + // deleted and do copy-tracing on the second. // // NOTE[deletion-diff-entry]: this may emit two diff - // entries, where the old - // diffstream would contain only one (even with gix's - // heuristic-based copy - // detection). + // entries, where the old diffstream would contain only + // one (even with gix's heuristic-based copy detection). // // This may be desirable in some cases (such as - // replacing a file X with a - // copy of some other file Y; the deletion entry makes - // it more clear that - // the original X was replaced by a formerly unrelated - // file). It is less - // desirable in cases where the new file shares some - // actual relation to the - // old one. + // replacing a file X with a copy of some other file Y; + // the deletion entry makes it more clear that the + // original X was replaced by a formerly unrelated + // file). It is less desirable in cases where the new + // file shares some actual relation to the old one. // // We plan to improve this in the near future, but for - // now we'll keep the - // simpler implementation since this behavior is not - // visible outside of tests yet. + // now we'll keep the simpler implementation since this + // behavior is not visible outside of tests yet. self.pending .push_back(Box::pin(ready(CopyHistoryTreeDiffEntry { target_path: next_diff_entry.path.clone(), @@ -679,11 +670,11 @@ async fn find_diff_sources_from_copies( // A B // // where D is `file`, C is its parent but is not present in `tree`, but both - // A and B are present, this will find either A or B, not both. Should - // we return both A and B instead? I don't think there's a way to do - // that with the current dag_walk functions. Do we care enough to - // implement something new there that pays more attention to the depth - // in the DAG? Perhaps a variant of closest_common_nodes? + // A and B are present, this will find either A or B, not both. Should we + // return both A and B instead? I don't think there's a way to do that with + // the current dag_walk functions. Do we care enough to implement something + // new there that pays more attention to the depth in the DAG? Perhaps a + // variant of closest_common_nodes? 'parents: for parent_copy_id in &history.parents { let mut absent_ancestors = vec![]; diff --git a/lib/src/default_index/composite.rs b/lib/src/default_index/composite.rs index 526f3dda52e..8111c7143be 100644 --- a/lib/src/default_index/composite.rs +++ b/lib/src/default_index/composite.rs @@ -453,8 +453,7 @@ impl CompositeCommitIndex { // Iterate though the candidates by reverse index position, keeping // track of the ancestors of already-found heads. If a candidate - // is an ancestor of an already-found head, then it can be - // removed. + // is an ancestor of an already-found head, then it can be removed. let mut parents = BinaryHeap::new(); let mut heads = Vec::new(); 'outer: for candidate in candidate_positions { diff --git a/lib/src/default_index/mutable.rs b/lib/src/default_index/mutable.rs index e729d521837..80d0b6ad620 100644 --- a/lib/src/default_index/mutable.rs +++ b/lib/src/default_index/mutable.rs @@ -321,8 +321,7 @@ impl MutableCommitIndexSegment { let mut base_parent_file = None; for parent_file in self.as_composite().ancestor_files_without_local() { // TODO: We should probably also squash if the parent file has less - // than N commits, regardless of how many (few) are in - // `self`. + // than N commits, regardless of how many (few) are in `self`. if 2 * num_new_commits < parent_file.num_local_commits() { base_parent_file = Some(parent_file.clone()); break; diff --git a/lib/src/default_index/readonly.rs b/lib/src/default_index/readonly.rs index 5906d35631c..6ceffa70446 100644 --- a/lib/src/default_index/readonly.rs +++ b/lib/src/default_index/readonly.rs @@ -115,8 +115,8 @@ impl ReadonlyIndexLoadError { Self::UnexpectedVersion { .. } => true, Self::Other { error, .. } => { // If the parent file name field is corrupt, the file wouldn't - // be found. And there's no need to distinguish - // it from an empty file. + // be found. And there's no need to distinguish it from an + // empty file. matches!( error.kind(), io::ErrorKind::NotFound diff --git a/lib/src/default_index/rev_walk.rs b/lib/src/default_index/rev_walk.rs index 67661a84e86..5e8b8ac2140 100644 --- a/lib/src/default_index/rev_walk.rs +++ b/lib/src/default_index/rev_walk.rs @@ -557,8 +557,8 @@ impl RevWalk for RevWalkGenerationRangeImpl Revset for RevsetImpl { if cfg!(feature = "testing") { // Exercise the estimation feature in tests. (If we ever have a // Revset implementation in production code that returns - // estimates, we can probably remove this and rewrite - // the associated tests.) + // estimates, we can probably remove this and rewrite the + // associated tests.) let count = self .positions() .take(10) @@ -843,8 +843,8 @@ impl EvaluationContext<'_> { .any(|parent_pos| root_positions.contains(parent_pos))) }); // TODO: Suppose heads include all visible heads, - // ToPredicateFn version can be - // optimized to only test the predicate() + // ToPredicateFn version can be optimized to only test the + // predicate() Ok(Box::new(FilterRevset { candidates, predicate, @@ -856,9 +856,9 @@ impl EvaluationContext<'_> { positions.reverse(); Ok(Box::new(EagerRevset { positions })) } else { - // For small generation range, it might be better to build a - // reachable map with generation bit - // set, which can be calculated incrementally from roots: + // For small generation range, it might be better to build + // a reachable map with generation bit set, which can be + // calculated incrementally from roots: // reachable[pos] = (reachable[parent_pos] | ...) << 1 let mut positions = builder .descendants_filtered_by_generation( @@ -890,11 +890,10 @@ impl EvaluationContext<'_> { let domain_reps = domain_vec.iter().map(|&pos| sets.find(pos)).collect_vec(); // Identify disjoint sets reachable from sources. Using a - // predicate here can be significantly faster - // for cases like `reachable(filter, X)`, since the filter - // can be checked for only commits in `X` instead of for all - // visible commits, and the difference is - // usually negligible for non-filter revsets. + // predicate here can be significantly faster for cases like + // `reachable(filter, X)`, since the filter can be checked for + // only commits in `X` instead of for all visible commits, and + // the difference is usually negligible for non-filter revsets. let sources_revset = self.evaluate(sources)?; let mut sources_predicate = sources_revset.to_predicate_fn(); let mut set_reps = HashSet::new(); diff --git a/lib/src/default_index/revset_graph_iterator.rs b/lib/src/default_index/revset_graph_iterator.rs index d2576b9ac95..2b1ca8036ab 100644 --- a/lib/src/default_index/revset_graph_iterator.rs +++ b/lib/src/default_index/revset_graph_iterator.rs @@ -232,8 +232,8 @@ impl<'a> RevsetGraphWalk<'a> { Some([CommitGraphEdge::missing(parent_position)].into()) } else { // The parent is not in the input set but it's somewhere in - // the range where we have commits in - // the input set, so continue searching. + // the range where we have commits in the input set, so + // continue searching. stack.push(parent); None } @@ -262,8 +262,8 @@ impl<'a> RevsetGraphWalk<'a> { edges.push(CommitGraphEdge::missing(parent_position)); } else { // The parent is not in the input set but it's somewhere - // in the range where we have - // commits in the input set, so continue searching. + // in the range where we have commits in the input set, + // so continue searching. stack.push(parent); parents_complete = false; } diff --git a/lib/src/diff_presentation/mod.rs b/lib/src/diff_presentation/mod.rs index 6d643990b21..67b627efd5d 100644 --- a/lib/src/diff_presentation/mod.rs +++ b/lib/src/diff_presentation/mod.rs @@ -60,7 +60,8 @@ pub async fn file_content_for_diff( ) -> BackendResult> { // If this is a binary file, don't show the full contents. // Determine whether it's binary by whether the first 8k bytes contain a - // null character; this is the same heuristic used by git as of writing: https://github.com/git/git/blob/eea0e59ffbed6e33d171ace5be13cde9faa41639/xdiff-interface.c#L192-L198 + // null character; this is the same heuristic used by git as of writing: + // https://github.com/git/git/blob/eea0e59ffbed6e33d171ace5be13cde9faa41639/xdiff-interface.c#L192-L198 const PEEK_SIZE: usize = 8000; // TODO: currently we look at the whole file, even though for binary files // we only need to know the file size. To change that we'd have to diff --git a/lib/src/files.rs b/lib/src/files.rs index b227d95562e..1fa24b45616 100644 --- a/lib/src/files.rs +++ b/lib/src/files.rs @@ -948,8 +948,8 @@ mod tests { MergeResult::Conflict(vec![conflict([b"b", b"a", b"a", b"a", b"c"])]) ); // Merge of an unresolved conflict and another branch, where the other - // branch undid the change from one of the inputs to the - // unresolved conflict in the first. + // branch undid the change from one of the inputs to the unresolved + // conflict in the first. assert_eq!( merge_hunks(&conflict([b"b", b"a", b"a", b"b", b"c"])), MergeResult::Resolved(hunk(b"c")) @@ -1027,8 +1027,8 @@ mod tests { // One side changes a line and adds a block after. The other side just // adds the same block. You might expect the last block would be - // deduplicated. However, the changes in the first side can be - // parsed as follows: + // deduplicated. However, the changes in the first side can be parsed + // as follows: // ``` // a { // - p diff --git a/lib/src/fix.rs b/lib/src/fix.rs index 5977396c5bf..87cde32b8b5 100644 --- a/lib/src/fix.rs +++ b/lib/src/fix.rs @@ -244,10 +244,10 @@ pub async fn fix_files( let base_tree = merge_commit_trees(repo_mut, &base_commits).await?; // If --include-unchanged-files, we always fix every matching file in - // the tree. Otherwise, we fix the matching changed files in - // this commit, plus any that were fixed in ancestors, so we - // don't lose those changes. We do this instead of rebasing onto - // those changes, to avoid merge conflicts. + // the tree. Otherwise, we fix the matching changed files in this + // commit, plus any that were fixed in ancestors, so we don't lose + // those changes. We do this instead of rebasing onto those changes, + // to avoid merge conflicts. let diff_base_tree = if include_unchanged_files { &repo_mut.store().empty_merged_tree() } else { @@ -272,11 +272,10 @@ pub async fn fix_files( }; // Deleted files have no file content to fix, and they have no terms - // in `after`, so we don't add any files-to-fix for - // them. For conflicted files in the base commit(s), we - // diff against the first side of the conflict. For conflicted - // files in the current commit, we add all sides of the conflict to - // the files-to-fix. + // in `after`, so we don't add any files-to-fix for them. For + // conflicted files in the base commit(s), we diff against the first + // side of the conflict. For conflicted files in the current commit, + // we add all sides of the conflict to the files-to-fix. let before_file_id = if let Some(Some(TreeValue::File { id: before_id, executable: _, @@ -291,8 +290,8 @@ pub async fn fix_files( for after_term in values.after { // We currently only support fixing the content of normal files, - // so we skip directories and symlinks, and we - // ignore the executable bit. + // so we skip directories and symlinks, and we ignore the + // executable bit. if let Some(TreeValue::File { id, executable: _, @@ -300,8 +299,8 @@ pub async fn fix_files( }) = after_term { // TODO: Skip the file if its content is larger than some - // configured size, preferably without - // actually reading it yet. + // configured size, preferably without actually reading it + // yet. let file_to_fix = FileToFix { file_id: id.clone(), base_file_id: before_file_id.clone(), @@ -434,8 +433,7 @@ pub fn compute_changed_ranges(base: &[u8], current: &[u8]) -> RegionsToFormat { DiffHunkKind::Different => { if line_count > 0 { // We want the diff ranges to be 1-based and inclusive - // [first, last] as this is what most - // formatters expect. + // [first, last] as this is what most formatters expect. ranges.push(LineRange { first: current_line, last: current_line + line_count - 1, diff --git a/lib/src/fsmonitor.rs b/lib/src/fsmonitor.rs index f0740d3a151..3567e63588d 100644 --- a/lib/src/fsmonitor.rs +++ b/lib/src/fsmonitor.rs @@ -249,9 +249,9 @@ pub mod watchman { if is_fresh_instance { // The Watchman documentation states that if it was a fresh // instance, we need to delete any tree entries that didn't - // appear in the returned list of changed files. - // For now, the caller will handle this by - // manually crawling the working copy again. + // appear in the returned list of changed files. For now, the + // caller will handle this by manually crawling the working + // copy again. Ok((clock, None)) } else { let paths = files diff --git a/lib/src/git.rs b/lib/src/git.rs index 98db75cbf92..c7ab23ff624 100644 --- a/lib/src/git.rs +++ b/lib/src/git.rs @@ -716,8 +716,7 @@ async fn import_refs_inner( .await?; } // Remote-tracking branch is the last known state of the branch in the - // remote. It shouldn't diverge even if we had inconsistent - // view. + // remote. It shouldn't diverge even if we had inconsistent view. mut_repo.set_remote_bookmark(symbol, new_remote_ref); } for update in &changed_remote_tags { @@ -1938,22 +1937,21 @@ async fn reset_index( ) -> Result<(), GitResetHeadError> { let parent_tree = wc_commit.parent_tree(repo).await?; // Use the merged parent tree as the Git index, allowing `git diff` to show - // the same changes as `jj diff`. If the merged parent tree has - // conflicts, then the Git index will also be conflicted. + // the same changes as `jj diff`. If the merged parent tree has conflicts, + // then the Git index will also be conflicted. let mut index = if let Some(tree_id) = parent_tree.tree_ids().as_resolved() { if tree_id == repo.store().empty_tree_id() { // If the tree is empty, gix can fail to load the object (since Git - // doesn't require the empty tree to actually be present - // in the object database), so we just use an empty - // index directly. + // doesn't require the empty tree to actually be present in the + // object database), so we just use an empty index directly. gix::index::File::from_state( gix::index::State::new(git_repo.object_hash()), git_repo.index_path(), ) } else { // If the parent tree is resolved, we can use gix's - // `index_from_tree` method. This is more efficient than - // iterating over the tree and adding each entry. + // `index_from_tree` method. This is more efficient than iterating + // over the tree and adding each entry. git_repo .index_from_tree(&gix::ObjectId::from_bytes_or_panic(tree_id.as_bytes())) .map_err(GitResetHeadError::from_git)? @@ -1996,50 +1994,49 @@ fn build_index_from_merged_tree( git_repo.index_path(), ); - let mut push_index_entry = |path: &RepoPath, - maybe_entry: &Option, - stage: gix::index::entry::Stage| { - let Some(entry) = maybe_entry else { - return; - }; + let mut push_index_entry = + |path: &RepoPath, maybe_entry: &Option, stage: gix::index::entry::Stage| { + let Some(entry) = maybe_entry else { + return; + }; - let (id, mode) = match entry { - TreeValue::File { - id, - executable, - copy_id: _, - } => { - if *executable { - (id.as_bytes(), gix::index::entry::Mode::FILE_EXECUTABLE) - } else { - (id.as_bytes(), gix::index::entry::Mode::FILE) + let (id, mode) = match entry { + TreeValue::File { + id, + executable, + copy_id: _, + } => { + if *executable { + (id.as_bytes(), gix::index::entry::Mode::FILE_EXECUTABLE) + } else { + (id.as_bytes(), gix::index::entry::Mode::FILE) + } } - } - TreeValue::Symlink(id) => (id.as_bytes(), gix::index::entry::Mode::SYMLINK), - TreeValue::Tree(_) => { - // This case is only possible if there is a file-directory - // conflict, since `MergedTree::entries` handles - // the recursion otherwise. We only materialize a - // file in the working copy for file-directory conflicts, so we - // don't add the tree to the index here either. - return; - } - TreeValue::GitSubmodule(id) => (id.as_bytes(), gix::index::entry::Mode::COMMIT), - }; + TreeValue::Symlink(id) => (id.as_bytes(), gix::index::entry::Mode::SYMLINK), + TreeValue::Tree(_) => { + // This case is only possible if there is a file-directory + // conflict, since `MergedTree::entries` handles the + // recursion otherwise. We only materialize a file in the + // working copy for file-directory conflicts, so we don't + // add the tree to the index here either. + return; + } + TreeValue::GitSubmodule(id) => (id.as_bytes(), gix::index::entry::Mode::COMMIT), + }; - let path = BStr::new(path.as_internal_file_string()); + let path = BStr::new(path.as_internal_file_string()); - // It is safe to push the entry because we ensure that we only add each - // path to a stage once, and we sort the entries after we finish - // adding them. - index.dangerously_push_entry( - gix::index::entry::Stat::default(), - gix::ObjectId::from_bytes_or_panic(id), - gix::index::entry::Flags::from_stage(stage), - mode, - path, - ); - }; + // It is safe to push the entry because we ensure that we only add + // each path to a stage once, and we sort the entries after we + // finish adding them. + index.dangerously_push_entry( + gix::index::entry::Stat::default(), + gix::ObjectId::from_bytes_or_panic(id), + gix::index::entry::Flags::from_stage(stage), + mode, + path, + ); + }; let mut has_many_sided_conflict = false; @@ -2058,13 +2055,12 @@ fn build_index_from_merged_tree( push_index_entry(&path, right, gix::index::entry::Stage::Theirs); } else { // We can't represent many-sided conflicts in the Git index, so just - // add the first side as staged. This is preferable to - // adding the first 2 sides as a conflict, since some - // tools rely on being able to resolve conflicts using the - // index, which could lead to an incorrect conflict resolution if - // the index didn't contain all of the conflict sides. - // Instead, we add a dummy conflict of a file named - // ".jj-do-not-resolve-this-conflict" to prevent the user from + // add the first side as staged. This is preferable to adding the + // first 2 sides as a conflict, since some tools rely on being able + // to resolve conflicts using the index, which could lead to an + // incorrect conflict resolution if the index didn't contain all of + // the conflict sides. Instead, we add a dummy conflict of a file + // named ".jj-do-not-resolve-this-conflict" to prevent the user from // accidentally committing the conflict markers. has_many_sided_conflict = true; push_index_entry( diff --git a/lib/src/git_backend.rs b/lib/src/git_backend.rs index e4e3fd995ac..4859b3fbcc0 100644 --- a/lib/src/git_backend.rs +++ b/lib/src/git_backend.rs @@ -310,13 +310,13 @@ impl GitBackend { let target_path = store_path.join("git_target"); let git_repo_path = if cfg!(windows) && git_repo_path.is_relative() { // When a repository is created in Windows, format the path with - // *forward slashes* and not backwards slashes. This - // makes it possible to use the same repository under - // Windows Subsystem for Linux. + // *forward slashes* and not backwards slashes. This makes it + // possible to use the same repository under Windows Subsystem for + // Linux. // // This only works for relative paths. If the path is absolute, - // there's not much we can do, and it simply won't work - // inside and outside WSL at the same time. + // there's not much we can do, and it simply won't work inside and + // outside WSL at the same time. file_util::slash_path(git_repo_path) } else { git_repo_path.into() @@ -469,8 +469,7 @@ impl GitBackend { .save_table(mut_table) .map_err(GitBackendError::WriteMetadata)?; // Since the parent table was the head, saved table are likely to be new - // head. If it's not, cache will be reloaded when entry can't be - // found. + // head. If it's not, cache will be reloaded when entry can't be found. *self.cached_extra_metadata.lock().unwrap() = Some(table); Ok(()) } @@ -500,8 +499,7 @@ impl GitBackend { .map_err(|err| BackendError::Other(Box::new(err)))?; // These commits are imported from Git. Make our change ids persist - // (otherwise future write_commit() could reassign new change - // id.) + // (otherwise future write_commit() could reassign new change id.) tracing::debug!( heads_count = head_ids.len(), "import extra metadata entries" @@ -727,7 +725,7 @@ fn commit_from_git_without_root_parent( // If the commit is signed, extract both the signature and the signed data // (which is the commit buffer with the gpgsig header omitted). // We have to re-parse the raw commit data because gix CommitRef does not - // give us the sogned data, only the signature. + // give us the signed data, only the signature. // Ideally, we could use try_to_commit_ref_iter at the beginning of this // function and extract everything from that. For now, this works let secure_sig = commit @@ -1311,9 +1309,9 @@ impl Backend for GitBackend { deserialize_extras(&mut commit, extras); } else { // TODO: Remove this hack and map to ObjectNotFound error if we're - // sure that there are no reachable ancestor commits - // without extras metadata. Git commits imported by jj < - // 0.8.0 might not have extras (#924). https://github.com/jj-vcs/jj/issues/2343 + // sure that there are no reachable ancestor commits without + // extras metadata. Git commits imported by jj < 0.8.0 might not + // have extras (#924). https://github.com/jj-vcs/jj/issues/2343 tracing::info!("unimported Git commit found"); self.import_head_commits([id])?; let table = self.cached_extra_metadata_table()?; @@ -1348,10 +1346,10 @@ impl Backend for GitBackend { for parent_id in &contents.parents { if *parent_id == self.root_commit_id { // Git doesn't have a root commit, so if the parent is the root - // commit, we don't add it to the list of - // parents to write in the Git commit. We also check that - // there are no other parents since Git cannot represent a merge - // between a root commit and another commit. + // commit, we don't add it to the list of parents to write in + // the Git commit. We also check that there are no other parents + // since Git cannot represent a merge between a root commit and + // another commit. if contents.parents.len() > 1 { return Err(BackendError::Unsupported( "The Git backend does not support creating merge commits with the root \ @@ -1407,11 +1405,10 @@ impl Backend for GitBackend { // If two writers write commits of the same id with different metadata, // they will both succeed and the metadata entries will be - // "merged" later. Since metadata entry is keyed by the commit - // id, one of the entries would be lost. To prevent such race - // condition locally, we extend the scope covered by the - // table lock. This is still racy if multiple machines are involved and - // the repository is rsync-ed. + // "merged" later. Since metadata entry is keyed by the commit id, one + // of the entries would be lost. To prevent such race condition locally, + // we extend the scope covered by the table lock. This is still racy if + // multiple machines are involved and the repository is rsync-ed. let (table, table_lock) = self.read_extra_metadata_table_locked()?; let id = loop { let mut commit = gix::objs::Commit { diff --git a/lib/src/graph_dominators.rs b/lib/src/graph_dominators.rs index f5619c484a5..5d5db9dceec 100644 --- a/lib/src/graph_dominators.rs +++ b/lib/src/graph_dominators.rs @@ -297,11 +297,11 @@ where loop { // Each iteration of the loop processes all nodes in reverse - // postorder, trying to improve the immediate dominator - // for each node. The loop continues until we - // have an iteration where no immediate dominator is changed. Note - // that the entries in immediate_dominators are only - // guaranteed to be correct when the loop terminates. + // postorder, trying to improve the immediate dominator for each + // node. The loop continues until we have an iteration where no + // immediate dominator is changed. Note that the entries in + // immediate_dominators are only guaranteed to be correct when the + // loop terminates. let mut changed = false; // Iterate in reverse postorder, skipping the start node. @@ -316,10 +316,9 @@ where } if new_idom == usize::MAX { // This is the first predecessor of u that has been - // processed so far. We use - // it as the starting point for finding the new - // "improved" immediate - // dominator for u. + // processed so far. We use it as the starting point + // for finding the new "improved" immediate dominator + // for u. new_idom = p; } else { // "Intersect" the current new_idom with p's idom. @@ -328,8 +327,8 @@ where } if new_idom == usize::MAX { // None of the predecessors of u have been processed yet. - // That's fine, we will try again of the - // next iteration of the outer loop. + // That's fine, we will try again of the next iteration of + // the outer loop. continue; } if immediate_dominators[u] != new_idom { @@ -346,8 +345,8 @@ where } // At this point we know the immediate dominator of every node, but we - // keep the Option wrapper so that we can use the intersect - // function during find_lowest_common_ancestor. + // keep the Option wrapper so that we can use the intersect function + // during find_lowest_common_ancestor. immediate_dominators } @@ -564,8 +563,8 @@ where } [final_value] => { // Optimization: if all final nodes have the same value, that - // value is the closest common dominator. There - // is no need to build the value flow graph. + // value is the closest common dominator. There is no need to + // build the value flow graph. return Ok(final_value.clone()); } _ => {} @@ -586,21 +585,21 @@ where .map_err(|err| FindDominatorValueError::ValueFnError(err))?; // NOTE: at this point we could compare the cardinality of the value set - // versus the number of nodes: if equal then we know that every - // node has a different value, and it is tempting to conclude - // that the result should be `start_value` (because the shape of - // the value flow graph is identical to the shape of the - // original flow graph). That is not always correct, - // consider this example with start node A and final nodes C and D: + // versus the number of nodes: if equal then we know that every node has + // a different value, and it is tempting to conclude that the result + // should be `start_value` (because the shape of the value flow graph is + // identical to the shape of the original flow graph). That is not + // always correct, consider this example with start node A and final + // nodes C and D: // // A(1) -> B(2) -> C(3) // \--> D(4) // // However, IF start node IS the closest common dominator of the - // original graph (it is not in the example above) then the - // answer would be `start_value`; so IF we knew that to be true - // we could skip building the value flow graph and running the - // dominator algorithm in the value flow graph. + // original graph (it is not in the example above) then the answer + // would be `start_value`; so IF we knew that to be true we could skip + // building the value flow graph and running the dominator algorithm in + // the value flow graph. let value_flow_graph = self.create_value_flow_graph(&value_cache.node_values); let dominator_finder = DominatorFinder::calculate(&value_flow_graph)?; @@ -1600,14 +1599,13 @@ mod tests { "C" | "D" => Ok(2), _ => Err("Unknown node".to_string()), }; - // Todo: the flow_graph is invalid because C and D are not reachable + // TODO: the flow_graph is invalid because C and D are not reachable // from A, so ideally find_dominator_value should return // UnreachableNodesInFlowGraph, but the optimizations in - // find_dominator_value currently cause it to return the start - // value. The best way to fix this is to calculate (and store) - // the post-order in FlowGraph::new, that way we could not possibly - // construct an invalid flow graph. This is not a big concern in - // practice though. + // find_dominator_value currently cause it to return the start value. + // The best way to fix this is to calculate (and store) the post-order + // in FlowGraph::new, that way we could not possibly construct an + // invalid flow graph. This is not a big concern in practice though. assert_eq!( flow_graph .find_dominator_value(&["B", "D"], value_fn) diff --git a/lib/src/id_prefix.rs b/lib/src/id_prefix.rs index b43bba41095..0611cb94c1e 100644 --- a/lib/src/id_prefix.rs +++ b/lib/src/id_prefix.rs @@ -173,8 +173,8 @@ impl IdPrefixIndex<'_> { } PrefixResolution::SingleMatch(id) => { // The disambiguation set may be loaded from a different - // repo, and contain a commit that - // doesn't exist in the current repo. + // repo, and contain a commit that doesn't exist in the + // current repo. if repo.index().has_id(&id).block_on()? { return Ok(PrefixResolution::SingleMatch(id)); } else { @@ -424,9 +424,9 @@ where }; if min_bytes.len() > N { // If the min prefix (including odd byte) is longer than the stored - // short keys, we are sure that min_bytes[..N] does not - // include the odd byte. Use it to take contiguous - // range, then filter by (longer) prefix.matches(). + // short keys, we are sure that min_bytes[..N] does not include the + // odd byte. Use it to take contiguous range, then filter by + // (longer) prefix.matches(). let short_bytes = unwrap_as_short_key(min_bytes); let pos = self.index.partition_point(|(s, _)| s < short_bytes); let range = self.index[pos..] @@ -437,8 +437,8 @@ where collect(range, entry_mapper) } else { // Otherwise, use prefix.matches() to deal with odd byte. Since the - // prefix is covered by short key width, we're sure that - // the matching prefixes are sorted. + // prefix is covered by short key width, we're sure that the + // matching prefixes are sorted. let pos = self.index.partition_point(|(s, _)| &s[..] < min_bytes); let range = self.index[pos..] .iter() diff --git a/lib/src/local_working_copy.rs b/lib/src/local_working_copy.rs index 3aef9284830..0fee38386f1 100644 --- a/lib/src/local_working_copy.rs +++ b/lib/src/local_working_copy.rs @@ -898,9 +898,8 @@ fn reject_reserved_existing_file_identity( })? else { // If the existing disk_path pointed to the reserved path, we would - // have gotten an identity back. Since we got nothing, - // the file does not exist and cannot be a reserved path - // name. + // have gotten an identity back. Since we got nothing, the file does + // not exist and cannot be a reserved path name. continue; }; @@ -1462,8 +1461,7 @@ impl TreeState { .filter_map(|path| RepoPathBuf::from_relative_path(path).ok()) .collect_vec(); // .gitignore changes require rescanning parent - // directories to pick up newly - // unignored files. + // directories to pick up newly unignored files. let gitignore_prefixes = repo_paths .iter() .filter_map(|repo_path| { @@ -1837,8 +1835,8 @@ impl FileSnapshotter<'_> { } Some(current_file_state) => { // If the file's mtime was set at the same time as this state - // file's own mtime, then we don't know if the - // file was modified before or after this state file. + // file's own mtime, then we don't know if the file was modified + // before or after this state file. new_file_state.is_clean(current_file_state) && current_file_state.mtime < self.tree_state.own_mtime } @@ -2096,10 +2094,10 @@ impl TreeState { set_executable(exec_bit, disk_path) .map_err(|err| checkout_error_for_stat_error(err, disk_path))?; // Read the file state from the file descriptor. That way, know that the - // file exists and is of the expected type, and the stat - // information is most likely accurate, except for other - // processes modifying the file concurrently (The mtime is set - // at write time and won't change when we close the file.) + // file exists and is of the expected type, and the stat information is + // most likely accurate, except for other processes modifying the file + // concurrently (The mtime is set at write time and won't change when + // we close the file.) let metadata = file .metadata() .map_err(|err| checkout_error_for_stat_error(err, disk_path))?; @@ -2265,10 +2263,10 @@ impl TreeState { } // This path and the previous one we did work for may have a common - // prefix. We can adjust the "working copy" path to the - // parent directory which we know is already created. If - // there is no common prefix, this will by default use - // RepoPath::root() as the common prefix. + // prefix. We can adjust the "working copy" path to the parent + // directory which we know is already created. If there is no common + // prefix, this will by default use RepoPath::root() as the common + // prefix. let (common_prefix, adjusted_diff_file_path) = path.split_common_prefix(&prev_created_path); @@ -2284,10 +2282,9 @@ impl TreeState { // "foo/bar" // // This results in a common prefix of "foo/bar" with empty - // string for the remainder since its entire - // prefix has already been created. This means - // that we _dont_ need to create its parent dirs - // either. + // string for the remainder since its entire prefix has already + // been created. This means that we _dont_ need to create its + // parent dirs either. path.to_fs_path(self.working_copy_path())? } else { @@ -2295,8 +2292,7 @@ impl TreeState { common_prefix.to_fs_path(self.working_copy_path())?; // Create parent directories no matter if after.is_present(). - // This ensures that the path never traverses - // symlinks. + // This ensures that the path never traverses symlinks. let Some(disk_path) = create_parent_dirs(&adjusted_working_copy_path, adjusted_diff_file_path)? else { @@ -2358,9 +2354,8 @@ impl TreeState { let file_state = match after { MaterializedTreeValue::Absent | MaterializedTreeValue::AccessDenied(_) => { // Reset the previous path to avoid scenarios where this - // path is deleted, then on the next - // iteration recreation is skipped because of this - // optimization. + // path is deleted, then on the next iteration recreation + // is skipped because of this optimization. prev_created_path = RepoPathBuf::root(); let mut parent_dir = disk_path.parent().unwrap(); @@ -2464,9 +2459,9 @@ impl TreeState { && old_tree.labels() != new_tree.labels() { // TODO: it might be better to use an async stream here and - // merge it with the other diff stream, but it - // could be difficult since the diff stream is not - // sorted in the same order as the conflicts iterator. + // merge it with the other diff stream, but it could be + // difficult since the diff stream is not sorted in the same + // order as the conflicts iterator. new_tree .conflicts_matching(matcher) .map(|(path, value)| value.map(|value| (path, value))) diff --git a/lib/src/lock/unix.rs b/lib/src/lock/unix.rs index 68ca084c0c3..97254b889af 100644 --- a/lib/src/lock/unix.rs +++ b/lib/src/lock/unix.rs @@ -72,18 +72,17 @@ impl FileLock { Ok(stat) => { if stat.st_nlink == 0 { // Lockfile was deleted, probably by the previous - // holder's `Drop` impl; - // create a new one so our ownership is visible, - // rather than hidden in an unlinked file. Not - // always necessary, since the previous holder might - // have exited abruptly. + // holder's `Drop` impl; create a new one so our + // ownership is visible, rather than hidden in an + // unlinked file. Not always necessary, since the + // previous holder might have exited abruptly. continue; } } Err(rustix::io::Errno::STALE) => { // The file handle is stale. - // This can happen when using NFS, - // likely caused by a remote deletion of the lockfile. + // This can happen when using NFS, likely caused by a + // remote deletion of the lockfile. // Treat this like a normal lockfile deletion and retry. continue; } diff --git a/lib/src/merged_tree.rs b/lib/src/merged_tree.rs index 3c1471a6600..42b4f83b7a9 100644 --- a/lib/src/merged_tree.rs +++ b/lib/src/merged_tree.rs @@ -151,18 +151,17 @@ impl MergedTree { Merge::resolved(label) } else if self.labels.has_labels() { // If the merge is conflicted and it already has labels, then we - // want to use those labels instead of the provided - // label. This ensures that rebasing conflicted commits - // keeps meaningful labels. + // want to use those labels instead of the provided label. This + // ensures that rebasing conflicted commits keeps meaningful labels. let labels = self.labels.as_merge(); assert_eq!(labels.num_sides(), self.tree_ids.num_sides()); labels.map(|label| label.as_str()) } else { // If the merge is conflicted but it doesn't have labels (e.g. // conflicts created before labels were added), then we - // use empty strings to indicate missing labels. We - // could consider using `label` for all the sides instead, but it - // might be confusing. + // use empty strings to indicate missing labels. We could + // consider using `label` for all the sides instead, but it might + // be confusing. Merge::repeated("", self.tree_ids.num_sides()) } } @@ -581,9 +580,8 @@ impl Iterator for ConflictIterator<'_> { } Ok(None) => { // Otherwise this is a conflict between files, trees, - // etc. If they could - // be automatically resolved, they should have been when - // the top-level tree conflict + // etc. If they could be automatically resolved, they + // should have been when the top-level tree conflict // was written, so we assume that they can't be. return Some((path, Ok(tree_values))); } diff --git a/lib/src/merged_tree_builder.rs b/lib/src/merged_tree_builder.rs index 4e50541ef9c..a96860d1939 100644 --- a/lib/src/merged_tree_builder.rs +++ b/lib/src/merged_tree_builder.rs @@ -106,8 +106,7 @@ impl MergedTreeBuilder { Err(mut values) => { values.pad_to(num_sides, &None); // This path was overridden with a conflicted value. Apply - // each term to its corresponding - // builder. + // each term to its corresponding builder. for (builder, value) in zip(&mut tree_builders, values) { builder.set_or_remove(path.clone(), value); } diff --git a/lib/src/repo.rs b/lib/src/repo.rs index d1c8fac5cd0..8dfe3c59b36 100644 --- a/lib/src/repo.rs +++ b/lib/src/repo.rs @@ -828,8 +828,7 @@ impl RepoLoader { assert!(index <= operations.len()); if index == operations.len() { // We are done processing the operations, but there is more work - // on the stack. Commit the transaction and - // cache the result. + // on the stack. Commit the transaction and cache the result. let tx_description = transaction_description.map_or_else( || format!("merge {} operations", operations.len()), |tx_description| tx_description.to_string(), @@ -845,8 +844,8 @@ impl RepoLoader { let other_op = &operations[index]; // Get the ancestor operations between the operations we have merged - // so far (represented by `tx.parent_ops()`) and the - // next operation to merge (`other_op`). + // so far (represented by `tx.parent_ops()`) and the next operation + // to merge (`other_op`). let ancestor_ops = match closest_common_ancestors .entry((to_operation_ids(tx.parent_ops()), other_op.id().clone())) { @@ -885,12 +884,11 @@ impl RepoLoader { // We have to merge the ancestor ops. // We first push the current state to the stack so that after we - // merge the ancestor ops, we can continue merging the - // rest of the operations. + // merge the ancestor ops, we can continue merging the rest of the + // operations. stack.push((index, operations, tx)); // Then we push the ancestor ops to the stack so that we can merge - // them first. We need to start a separate transaction - // for this. + // them first. We need to start a separate transaction for this. let new_tx = self.load_at(&ancestor_ops[0]).await?.start_transaction(); stack.push((1, ancestor_ops.clone(), new_tx)); } @@ -1362,8 +1360,7 @@ impl MutableRepo { to_visit.iter().map(|commit| commit.id().clone()).collect(); let mut visited = HashSet::new(); // Calculate an order where we rebase parents first, but if the parents - // were rewritten, make sure we rebase the rewritten parent - // first. + // were rewritten, make sure we rebase the rewritten parent first. let store = self.store(); dag_walk_async::topo_order_reverse( to_visit.into_iter().map(Ok), @@ -1471,12 +1468,12 @@ impl MutableRepo { } self.update_rewritten_references(options).await?; // Since we didn't necessarily visit all descendants of rewritten - // commits (e.g. if they were rewritten in the callback), there - // can still be commits left to rebase, so we don't clear - // `parent_mapping` here. TODO: Should we make this stricter? We - // could check that there were no rewrites before this function - // was called, and we can check that only commits in the - // `to_visit` set were added by the callback. Then we + // commits (e.g. if they were rewritten in the callback), there can + // still be commits left to rebase, so we don't clear `parent_mapping` + // here. + // TODO: Should we make this stricter? We could check that there were no + // rewrites before this function was called, and we can check that only + // commits in the `to_visit` set were added by the callback. Then we // could clear `parent_mapping` here and not have to scan it again at // the end of the transaction when we call `rebase_descendants()`. @@ -1991,12 +1988,12 @@ impl MutableRepo { let other_heads = other.heads().iter().cloned().collect_vec(); // HACK: Don't walk long ranges of commits to find rewrites when using - // other custom implementations. The only custom index - // implementation we're currently aware of is Google's. That - // repo has too high commit rate for it to be feasible to walk - // all added and removed commits. TODO: Fix this somehow. Maybe - // a method on `Index` to find rewritten commits - // given `base_heads`, `own_heads` and `other_heads`? + // other custom implementations. The only custom index implementation + // we're currently aware of is Google's. That repo has too high commit + // rate for it to be feasible to walk + // all added and removed commits. + // TODO: Fix this somehow. Maybe a method on `Index` to find rewritten + // commits given `base_heads`, `own_heads` and `other_heads`? if self.is_backed_by_default_index() { self.record_rewrites(&base_heads, &own_heads).await?; self.record_rewrites(&base_heads, &other_heads).await?; diff --git a/lib/src/revset.rs b/lib/src/revset.rs index c3091768cea..3fce21a4027 100644 --- a/lib/src/revset.rs +++ b/lib/src/revset.rs @@ -3241,8 +3241,7 @@ impl VisibilityResolutionContext<'_> { }, RevsetExpression::Filter(_) | RevsetExpression::AsFilter(_) => { // Top-level filter without intersection: e.g. "~author(_)" is - // represented as - // `AsFilter(NotIn(Filter(Author(_))))`. + // represented as `AsFilter(NotIn(Filter(Author(_))))`. ResolvedExpression::FilterWithin { candidates: self.resolve_all().into(), predicate: self.resolve_predicate(expression), diff --git a/lib/src/rewrite.rs b/lib/src/rewrite.rs index 9af13b593a8..df407c21f1e 100644 --- a/lib/src/rewrite.rs +++ b/lib/src/rewrite.rs @@ -207,9 +207,9 @@ pub async fn restore_tree( let labeled_empty_tree = MergedTree::new(tree.store().clone(), empty_tree_ids, labels); let mut builder = MergedTreeBuilder::new(labeled_empty_tree); for (path, value) in tree.entries_matching(&matcher) { - // TODO: if https://github.com/jj-vcs/jj/issues/4152 is implemented, we will need - // to expand resolved conflicts into `Merge::repeated(value, - // num_sides)`. + // TODO: if https://github.com/jj-vcs/jj/issues/4152 is + // implemented, we will need to expand resolved conflicts into + // `Merge::repeated(value, num_sides)`. builder.set_or_remove(path, value?); } builder.write_tree().await @@ -724,8 +724,8 @@ pub async fn compute_move_commits( ) .await?; // We don't have to compute the internal parents for the connected - // target set, since the connected target set is the - // same as the target set. + // target set, since the connected target set is the same as the + // target set. connected_target_commits_internal_parents = HashMap::new(); target_roots = root_ids.iter().cloned().collect(); } @@ -786,8 +786,7 @@ pub async fn compute_move_commits( .map_err(|err| err.into_backend_error())?; // For all commits in the target set, compute its transitive descendant - // commits which are outside of the target set by up to 1 - // generation. + // commits which are outside of the target set by up to 1 generation. let mut target_commit_external_descendants: HashMap> = HashMap::new(); // Iterate through all descendants of the target set, going through @@ -863,10 +862,9 @@ pub async fn compute_move_commits( }; // If the original parents of the new children are the new - // parents of the `target_heads`, - // replace them with the target heads since we are - // "inserting" the target commits in - // between the new parents and the new children. + // parents of the `target_heads`, replace them with the + // target heads since we are "inserting" the target commits + // in between the new parents and the new children. for id in old_child_parent_ids { if new_parent_ids.contains(id) { new_child_parent_ids.extend(target_heads.clone()); @@ -1174,10 +1172,9 @@ pub async fn duplicate_commits( let mut child_new_parent_ids = IndexSet::new(); for old_parent_id in rewriter.old_commit().parent_ids() { // If the original parents of the new children are the new - // parents of `target_head_ids`, replace - // them with `target_head_ids` since we are - // "inserting" the target commits in between the new parents - // and the new children. + // parents of `target_head_ids`, replace them with + // `target_head_ids` since we are "inserting" the target + // commits in between the new parents and the new children. if parent_commit_ids.contains(old_parent_id) { child_new_parent_ids.extend(target_head_ids.clone()); } else { @@ -1390,15 +1387,13 @@ pub async fn squash_commits<'repo>( let abandon = !keep_emptied && source.is_full_selection(); if !abandon && source.is_empty_selection() { // Nothing selected from this commit. If it's abandoned (i.e. - // already empty), we still include it so `jj squash` - // can be used for abandoning an empty commit in - // the middle of a stack. + // already empty), we still include it so `jj squash` can be used + // for abandoning an empty commit in the middle of a stack. continue; } // TODO: Do we want to optimize the case of moving to the parent commit - // (`jj squash -r`)? The source tree will be unchanged in that - // case. + // (`jj squash -r`)? The source tree will be unchanged in that case. source_commits.push(SourceCommit { commit: source, diff: source diff --git a/lib/src/simple_op_heads_store.rs b/lib/src/simple_op_heads_store.rs index 96f2e67e114..4e653b1ab1d 100644 --- a/lib/src/simple_op_heads_store.rs +++ b/lib/src/simple_op_heads_store.rs @@ -87,10 +87,10 @@ impl SimpleOpHeadsStore { .or_else(|err| { if err.kind() == io::ErrorKind::NotFound { // It's fine if the old head was not found. It probably - // means that we're on a distributed - // file system where the locking doesn't - // work. We'll probably end up with two current - // heads. We'll detect that next time we load the view. + // means that we're on a distributed file system where the + // locking doesn't work. We'll probably end up with two + // current heads. We'll detect that next time we load the + // view. Ok(()) } else { Err(err) diff --git a/lib/src/ssh_signing.rs b/lib/src/ssh_signing.rs index 5d1ecfe3bf8..11db5092df2 100644 --- a/lib/src/ssh_signing.rs +++ b/lib/src/ssh_signing.rs @@ -187,8 +187,8 @@ impl SshBackend { .arg(signature_file_path); // We can't use the existing run_command helper here as `-Y - // find-principals` will return a non-0 exit code if no - // principals are found. + // find-principals` will return a non-0 exit code if no principals are + // found. // // In this case we don't want to error out, just return None. tracing::info!(?command, "running SSH signing command"); diff --git a/lib/src/stacked_table.rs b/lib/src/stacked_table.rs index 92e6b3cd46a..ab2ff4005e3 100644 --- a/lib/src/stacked_table.rs +++ b/lib/src/stacked_table.rs @@ -322,8 +322,8 @@ impl MutableTable { match maybe_parent_file { Some(parent_file) => { // TODO: We should probably also squash if the parent file - // has less than N commits, regardless - // of how many (few) are in `self`. + // has less than N commits, regardless of how many (few) + // are in `self`. if 2 * num_new_entries < parent_file.num_local_entries { squashed = Self::incremental(parent_file); break; @@ -529,14 +529,13 @@ impl TableStore { Ok(tables.pop().unwrap()) } else { // There are multiple heads. We take a lock, then check if there are - // still multiple heads (it's likely that another - // process was in the process of deleting on of them). - // If there are still multiple heads, we attempt to - // merge all the tables into one. We then save that table and record - // the new head. Note that the locking isn't necessary - // for correctness; we take the lock only to avoid other - // concurrent processes from doing the same work (and - // producing another set of divergent heads). + // still multiple heads (it's likely that another process was in the + // process of deleting on of them). If there are still multiple + // heads, we attempt to merge all the tables into one. We then save + // that table and record the new head. Note that the locking isn't + // necessary for correctness; we take the lock only to avoid other + // concurrent processes from doing the same work (and producing + // another set of divergent heads). let (table, _) = self.get_head_locked()?; Ok(table) } diff --git a/lib/src/tree_merge.rs b/lib/src/tree_merge.rs index b75dd944ada..cb14f044f04 100644 --- a/lib/src/tree_merge.rs +++ b/lib/src/tree_merge.rs @@ -278,8 +278,8 @@ impl TreeMerger { self.enqueue_tree_read(path, value); } else { // TODO: If it's e.g. a dir/file conflict, there's no need to - // try to resolve it as a file. We should mark - // them to `unmerged_tree.conflicts` instead. + // try to resolve it as a file. We should mark them to + // `unmerged_tree.conflicts` instead. self.enqueue_file_merge(path, value); } } diff --git a/lib/src/working_copy.rs b/lib/src/working_copy.rs index 2939b7132ad..f68e86405fc 100644 --- a/lib/src/working_copy.rs +++ b/lib/src/working_copy.rs @@ -381,13 +381,11 @@ impl WorkingCopyFreshness { let ancestor_op = ancestor_ops.into_iter().next().unwrap(); if ancestor_op.id() == repo_operation.id() { // The working copy was updated since we loaded the repo. The - // repo must be reloaded at the working copy's - // operation. + // repo must be reloaded at the working copy's operation. Ok(Self::Updated(Box::new(wc_operation))) } else if ancestor_op.id() == wc_operation.id() { // The working copy was not updated when some repo operation - // committed, meaning that it's stale compared - // to the repo view. + // committed, meaning that it's stale compared to the repo view. if locked_wc.old_tree().tree_ids_and_labels() == wc_commit.tree().tree_ids_and_labels() { diff --git a/lib/src/workspace.rs b/lib/src/workspace.rs index 9a5fe836e52..e9d06e4bdbe 100644 --- a/lib/src/workspace.rs +++ b/lib/src/workspace.rs @@ -265,10 +265,9 @@ impl Workspace { store_path: &Path| -> Result, _> { // If the git repo is inside the workspace, use a relative path to - // it so the whole workspace can be moved without - // breaking. TODO: Clean up path normalization. - // store_path is canonicalized by ReadonlyRepo::init(). - // workspace_root will be canonicalized by + // it so the whole workspace can be moved without breaking. + // TODO: Clean up path normalization. store_path is canonicalized by + // ReadonlyRepo::init(). workspace_root will be canonicalized by // Workspace::new(), but it's not yet here. let store_relative_git_repo_path = match ( dunce::canonicalize(workspace_root), diff --git a/lib/tests/test_bad_locking.rs b/lib/tests/test_bad_locking.rs index 7baa31391f6..586fd713497 100644 --- a/lib/tests/test_bad_locking.rs +++ b/lib/tests/test_bad_locking.rs @@ -87,8 +87,8 @@ fn merge_directories(left: &Path, base: &Path, right: &Path, output: &Path) { sub_dirs.push(base_name.to_os_string()); } else if !child_base.exists() { // This overwrites the left side if that's been written. That's - // fine, since the point of the test is that it - // should be okay for either side to win. + // fine, since the point of the test is that it should be okay + // for either side to win. std::fs::copy(&child_right, child_output).unwrap(); } } diff --git a/lib/tests/test_git.rs b/lib/tests/test_git.rs index 741c15f44dd..6bb440129c6 100644 --- a/lib/tests/test_git.rs +++ b/lib/tests/test_git.rs @@ -3465,9 +3465,9 @@ fn test_export_reexport_transitions() -> TestResult { let commit_c = write_random_commit(mut_repo); // Create a few bookmarks whose names indicate how they change in jj in git. // The first letter represents the bookmark's target in the last export. - // The second letter represents the bookmark's target in jj. The third - // letter represents the bookmark's target in git. "X" means that the - // bookmark doesn't exist. "A", "B", or "C" means that the bookmark + // The second letter represents the bookmark's target in jj. + // The third letter represents the bookmark's target in git. "X" means that + // the bookmark doesn't exist. "A", "B", or "C" means that the bookmark // points to that commit. // // AAB: Branch modified in git @@ -6119,8 +6119,7 @@ fn test_push_updates_unexpectedly_moved_forward_on_remote() -> TestResult { ); // Here, the local bookmark hasn't moved from `parent_of_main_commit`, but - // it moved to `main` on the remote. So, the conflict resolves to - // `main`. + // it moved to `main` on the remote. So, the conflict resolves to `main`. // // `jj` should not actually attempt a push in this case, but if it did, the // push should fail. @@ -6591,9 +6590,8 @@ fn test_concurrent_read_write_commit() -> TestResult { } if !pending_commit_ids.is_empty() { // It's not an error if some of the readers couldn't observe - // the commits. It's unlikely, but - // possible if the git backend had strong negative object - // cache for example. + // the commits. It's unlikely, but possible if the git + // backend had strong negative object cache for example. eprintln!( "reader {i} couldn't observe the following commits: \ {pending_commit_ids:#?}" diff --git a/lib/tests/test_local_working_copy_concurrent.rs b/lib/tests/test_local_working_copy_concurrent.rs index 7370c27a96d..b49167418c0 100644 --- a/lib/tests/test_local_working_copy_concurrent.rs +++ b/lib/tests/test_local_working_copy_concurrent.rs @@ -147,10 +147,9 @@ fn test_checkout_parallel() -> TestResult { assert_eq!(stats.added_files, 1); assert_eq!(stats.removed_files, 1); // Check that the working copy contains one of the trees. We may - // see a different tree than the one we just - // checked out, but since write_tree() should - // take the same lock as check_out(), write_tree() - // should never produce a different tree. + // see a different tree than the one we just checked out, but + // since write_tree() should take the same lock as check_out(), + // write_tree() should never produce a different tree. let mut locked_ws = workspace.start_working_copy_mutation().block_on().unwrap(); let (new_tree, _stats) = locked_ws .locked_wc() diff --git a/lib/tests/test_revset.rs b/lib/tests/test_revset.rs index 196e49d3a04..9e32225187e 100644 --- a/lib/tests/test_revset.rs +++ b/lib/tests/test_revset.rs @@ -5254,8 +5254,7 @@ fn test_reverse_graph() -> TestResult { // Tests that merges, forks, direct edges, indirect edges, and "missing" // edges are correct in reversed graph. "Missing" edges (i.e. edges to // commits not in the input set) won't be part of the reversed graph. - // Conversely, there won't be missing edges to children not in the - // input. + // Conversely, there won't be missing edges to children not in the input. // // F // |\ diff --git a/lib/tests/test_rewrite.rs b/lib/tests/test_rewrite.rs index 88b7bbc7dbd..294b6750e69 100644 --- a/lib/tests/test_rewrite.rs +++ b/lib/tests/test_rewrite.rs @@ -506,7 +506,8 @@ fn test_restore_tree_with_conflicts() -> TestResult { ); // path3 is updated in the existing conflict terms due to - // `MergedTree::resolve`. If we implement https://github.com/jj-vcs/jj/issues/4152, the conflict would + // `MergedTree::resolve`. If we implement + // https://github.com/jj-vcs/jj/issues/4152, the conflict would // instead have an extra side showing the diff from the restore. let expected_side1 = create_tree( repo, @@ -1864,9 +1865,8 @@ fn test_rebase_descendants_bookmark_delete_modify_abandon( let repo = &test_repo.repo; // Bookmark "main" initially points to commit A. One operation rewrites it - // to point to B (child of A). A concurrent operation deletes the - // bookmark. That leaves the bookmark pointing to "0-A+B". We now - // abandon B. + // to point to B (child of A). A concurrent operation deletes the bookmark. + // That leaves the bookmark pointing to "0-A+B". We now abandon B. // // - If delete_abandoned_bookmarks = false, that should result in the // bookmark pointing to "0-A+A=0". @@ -2249,8 +2249,8 @@ fn test_empty_commit_option(empty_behavior: EmptyBehavior) { // The changes in D are included in BD, so D is newly empty. assert_abandoned_with_parent(tx.repo_mut(), &rebase_map, &commit_d, commit_bd.id()); // E was already empty, so F is a merge commit with C and E as - // parents. Although it's empty, we still keep it - // because we don't want to drop merge commits. + // parents. Although it's empty, we still keep it because we + // don't want to drop merge commits. let new_commit_e = assert_rebased_onto(tx.repo_mut(), &rebase_map, &commit_e, &[commit_bd.id()]); let new_commit_f = assert_rebased_onto( diff --git a/lib/tests/test_view.rs b/lib/tests/test_view.rs index 48bca399eff..e658e3d98af 100644 --- a/lib/tests/test_view.rs +++ b/lib/tests/test_view.rs @@ -798,9 +798,9 @@ fn test_merge_three_operations() -> TestResult { fn test_merge_views_criss_cross(op_b_first: bool) -> TestResult { // Consider the operation log below, where D and E are both merges of B and // C. When merging F and E, if we pick C as common ancestor, we will get - // divergence because the working-copy commit was rewritten from K to L - // in operation E (but actually in operation B) and it was rewritten - // from K to M in operation F. + // divergence because the working-copy commit was rewritten from K to L in + // operation E (but actually in operation B) and it was rewritten from K to + // M in operation F. // // F wc: M // |