repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/sparse/list.rs | cli/src/commands/sparse/list.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::Write as _;
use std::path::Path;
use tracing::instrument;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// List the patterns that are currently present in the working copy
///
/// By default, a newly cloned or initialized repo will have have a pattern
/// matching all files from the repo root. That pattern is rendered as `.` (a
/// single period).
#[derive(clap::Args, Clone, Debug)]
pub struct SparseListArgs {}
#[instrument(skip_all)]
pub fn cmd_sparse_list(
ui: &mut Ui,
command: &CommandHelper,
_args: &SparseListArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
for path in workspace_command.working_copy().sparse_patterns()? {
writeln!(
ui.stdout(),
"{}",
path.to_fs_path_unchecked(Path::new("")).display()
)?;
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/sparse/mod.rs | cli/src/commands/sparse/mod.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod edit;
mod list;
mod reset;
mod set;
use clap::Subcommand;
use jj_lib::repo_path::RepoPathBuf;
use pollster::FutureExt as _;
use tracing::instrument;
use self::edit::SparseEditArgs;
use self::edit::cmd_sparse_edit;
use self::list::SparseListArgs;
use self::list::cmd_sparse_list;
use self::reset::SparseResetArgs;
use self::reset::cmd_sparse_reset;
use self::set::SparseSetArgs;
use self::set::cmd_sparse_set;
use crate::cli_util::CommandHelper;
use crate::cli_util::WorkspaceCommandHelper;
use crate::cli_util::print_checkout_stats;
use crate::command_error::CommandError;
use crate::command_error::internal_error_with_message;
use crate::ui::Ui;
/// Manage which paths from the working-copy commit are present in the working
/// copy
#[derive(Subcommand, Clone, Debug)]
pub(crate) enum SparseCommand {
Edit(SparseEditArgs),
List(SparseListArgs),
Reset(SparseResetArgs),
Set(SparseSetArgs),
}
#[instrument(skip_all)]
pub(crate) fn cmd_sparse(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &SparseCommand,
) -> Result<(), CommandError> {
match subcommand {
SparseCommand::Edit(args) => cmd_sparse_edit(ui, command, args),
SparseCommand::List(args) => cmd_sparse_list(ui, command, args),
SparseCommand::Reset(args) => cmd_sparse_reset(ui, command, args),
SparseCommand::Set(args) => cmd_sparse_set(ui, command, args),
}
}
fn update_sparse_patterns_with(
ui: &mut Ui,
workspace_command: &mut WorkspaceCommandHelper,
f: impl FnOnce(&mut Ui, &[RepoPathBuf]) -> Result<Vec<RepoPathBuf>, CommandError>,
) -> Result<(), CommandError> {
let (mut locked_ws, wc_commit) = workspace_command.start_working_copy_mutation()?;
let new_patterns = f(ui, locked_ws.locked_wc().sparse_patterns()?)?;
let stats = locked_ws
.locked_wc()
.set_sparse_patterns(new_patterns)
.block_on()
.map_err(|err| internal_error_with_message("Failed to update working copy paths", err))?;
let operation_id = locked_ws.locked_wc().old_operation_id().clone();
locked_ws.finish(operation_id)?;
print_checkout_stats(ui, &stats, &wc_commit)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/sparse/edit.rs | cli/src/commands/sparse/edit.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Write as _;
use std::path::Path;
use itertools::Itertools as _;
use jj_lib::repo_path::RepoPathBuf;
use tracing::instrument;
use super::update_sparse_patterns_with;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::internal_error;
use crate::command_error::user_error_with_message;
use crate::description_util::TextEditor;
use crate::ui::Ui;
/// Start an editor to update the patterns that are present in the working copy
#[derive(clap::Args, Clone, Debug)]
pub struct SparseEditArgs {}
#[instrument(skip_all)]
pub fn cmd_sparse_edit(
ui: &mut Ui,
command: &CommandHelper,
_args: &SparseEditArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let editor = workspace_command.text_editor()?;
update_sparse_patterns_with(ui, &mut workspace_command, |_ui, old_patterns| {
let mut new_patterns = edit_sparse(&editor, old_patterns)?;
new_patterns.sort_unstable();
new_patterns.dedup();
Ok(new_patterns)
})
}
fn edit_sparse(
editor: &TextEditor,
sparse: &[RepoPathBuf],
) -> Result<Vec<RepoPathBuf>, CommandError> {
let mut content = String::new();
for sparse_path in sparse {
// Invalid path shouldn't block editing. Edited paths will be validated.
let workspace_relative_sparse_path = sparse_path.to_fs_path_unchecked(Path::new(""));
let path_string = workspace_relative_sparse_path.to_str().ok_or_else(|| {
internal_error(format!(
"Stored sparse path is not valid utf-8: {}",
workspace_relative_sparse_path.display()
))
})?;
writeln!(&mut content, "{path_string}").unwrap();
}
let content = editor
.edit_str(content, Some(".jjsparse"))
.map_err(|err| err.with_name("sparse patterns"))?;
content
.lines()
.filter(|line| !line.starts_with("JJ:"))
.map(|line| line.trim())
.filter(|line| !line.is_empty())
.map(|line| {
RepoPathBuf::from_relative_path(line).map_err(|err| {
user_error_with_message(format!("Failed to parse sparse pattern: {line}"), err)
})
})
.try_collect()
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/sparse/reset.rs | cli/src/commands/sparse/reset.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use jj_lib::repo_path::RepoPathBuf;
use tracing::instrument;
use super::update_sparse_patterns_with;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// Reset the patterns to include all files in the working copy
#[derive(clap::Args, Clone, Debug)]
pub struct SparseResetArgs {}
#[instrument(skip_all)]
pub fn cmd_sparse_reset(
ui: &mut Ui,
command: &CommandHelper,
_args: &SparseResetArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
update_sparse_patterns_with(ui, &mut workspace_command, |_ui, _old_patterns| {
Ok(vec![RepoPathBuf::root()])
})
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/sparse/set.rs | cli/src/commands/sparse/set.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use itertools::Itertools as _;
use jj_lib::repo_path::RepoPathBuf;
use tracing::instrument;
use super::update_sparse_patterns_with;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// Update the patterns that are present in the working copy
///
/// For example, if all you need is the `README.md` and the `lib/`
/// directory, use `jj sparse set --clear --add README.md --add lib`.
/// If you no longer need the `lib` directory, use `jj sparse set --remove lib`.
#[derive(clap::Args, Clone, Debug)]
pub struct SparseSetArgs {
/// Patterns to add to the working copy
#[arg(
long,
value_hint = clap::ValueHint::AnyPath,
value_parser = |s: &str| RepoPathBuf::from_relative_path(s),
)]
add: Vec<RepoPathBuf>,
/// Patterns to remove from the working copy
#[arg(
long,
conflicts_with = "clear",
value_hint = clap::ValueHint::AnyPath,
value_parser = |s: &str| RepoPathBuf::from_relative_path(s),
)]
remove: Vec<RepoPathBuf>,
/// Include no files in the working copy (combine with --add)
#[arg(long)]
clear: bool,
}
#[instrument(skip_all)]
pub fn cmd_sparse_set(
ui: &mut Ui,
command: &CommandHelper,
args: &SparseSetArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
update_sparse_patterns_with(ui, &mut workspace_command, |_ui, old_patterns| {
let mut new_patterns = HashSet::new();
if !args.clear {
new_patterns.extend(old_patterns.iter().cloned());
for path in &args.remove {
new_patterns.remove(path);
}
}
for path in &args.add {
new_patterns.insert(path.to_owned());
}
Ok(new_patterns.into_iter().sorted_unstable().collect())
})
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bisect/mod.rs | cli/src/commands/bisect/mod.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod run;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// Find a bad revision by bisection.
#[derive(clap::Subcommand, Clone, Debug)]
pub enum BisectCommand {
Run(run::BisectRunArgs),
}
pub fn cmd_bisect(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &BisectCommand,
) -> Result<(), CommandError> {
match subcommand {
BisectCommand::Run(args) => run::cmd_bisect_run(ui, command, args),
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bisect/run.rs | cli/src/commands/bisect/run.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCompleter;
use jj_lib::bisect::BisectionResult;
use jj_lib::bisect::Bisector;
use jj_lib::bisect::Evaluation;
use jj_lib::commit::Commit;
use jj_lib::object_id::ObjectId as _;
use tracing::instrument;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::cli_util::WorkspaceCommandHelper;
use crate::cli_util::short_operation_hash;
use crate::command_error::CommandError;
use crate::command_error::cli_error;
use crate::command_error::internal_error_with_message;
use crate::command_error::user_error;
use crate::command_error::user_error_with_message;
use crate::complete;
use crate::config::CommandNameAndArgs;
use crate::ui::Ui;
/// Run a given command to find the first bad revision.
///
/// Uses binary search to find the first bad revision. Revisions are evaluated
/// by running a given command (see the documentation for `--command` for
/// details).
///
/// It is assumed that if a given revision is bad, then all its descendants
/// in the input range are also bad.
///
/// The target of the bisection can be inverted to look for the first good
/// revision by passing `--find-good`.
///
/// Hint: You can pass your shell as evaluation command. You can then run
/// manual tests in the shell and make sure to exit the shell with appropriate
/// error code depending on the outcome (e.g. `exit 0` to mark the revision as
/// good in Bash or Fish).
///
/// Example: To run `cargo test` with the changes from revision `xyz` applied:
///
/// `jj bisect run --range v1.0..main -- bash -c "jj duplicate -r xyz -B @ &&
/// cargo test"`
#[derive(clap::Args, Clone, Debug)]
pub(crate) struct BisectRunArgs {
/// Range of revisions to bisect
///
/// This is typically a range like `v1.0..main`. The heads of the range are
/// assumed to be bad. Ancestors of the range that are not also in the range
/// are assumed to be good.
#[arg(long, short, value_name = "REVSETS", required = true)]
#[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
range: Vec<RevisionArg>,
/// Deprecated. Use positional arguments instead.
#[arg(
long = "command",
value_name = "COMMAND",
hide = true,
conflicts_with = "command"
)]
legacy_command: Option<CommandNameAndArgs>,
/// Command to run to determine whether the bug is present
///
/// The exit status of the command will be used to mark revisions as good or
/// bad: status 0 means good, 125 means to skip the revision, 127 (command
/// not found) will abort the bisection, and any other non-zero exit status
/// means the revision is bad.
///
/// The target's commit ID is available to the command in the
/// `$JJ_BISECT_TARGET` environment variable.
#[arg(value_name = "COMMAND")]
command: Option<String>,
/// Arguments to pass to the command
///
/// Hint: Use a `--` separator to allow passing arguments starting with `-`.
/// For example `jj bisect run --range=... -- test -f some-file`.
#[arg(value_name = "ARGS")]
args: Vec<String>,
/// Whether to find the first good revision instead
///
/// Inverts the interpretation of exit statuses (excluding special exit
/// statuses).
#[arg(long, value_name = "TARGET", default_value = "false")]
find_good: bool,
}
#[instrument(skip_all)]
pub(crate) fn cmd_bisect_run(
ui: &mut Ui,
command: &CommandHelper,
args: &BisectRunArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
if let Some(command) = &args.legacy_command {
writeln!(
ui.warning_default(),
"`--command` is deprecated; use positional arguments instead: `jj bisect run \
--range=... -- {command}`"
)?;
} else if args.command.is_none() {
return Err(cli_error("Command argument is required"));
}
let input_range = workspace_command
.parse_union_revsets(ui, &args.range)?
.resolve()?;
let initial_repo = workspace_command.repo().clone();
let mut bisector = Bisector::new(initial_repo.as_ref(), input_range)?;
let bisection_result = loop {
match bisector.next_step()? {
jj_lib::bisect::NextStep::Evaluate(commit) => {
{
let mut formatter = ui.stdout_formatter();
// TODO: Show a graph of the current range instead?
// TODO: Say how many commits are left and estimate the number of iterations.
let commit_template = workspace_command.commit_summary_template();
write!(formatter, "Now evaluating: ")?;
commit_template.format(&commit, formatter.as_mut())?;
writeln!(formatter)?;
}
let cmd = get_command(args);
let evaluation = evaluate_commit(ui, &mut workspace_command, cmd, &commit)?;
{
let mut formatter = ui.stdout_formatter();
let message = match evaluation {
Evaluation::Good => "The revision is good.",
Evaluation::Bad => "The revision is bad.",
Evaluation::Skip => {
"It could not be determined if the revision is good or bad."
}
};
writeln!(formatter, "{message}")?;
writeln!(formatter)?;
}
if args.find_good {
// If we're looking for the first good revision,
// invert the evaluation result.
bisector.mark(commit.id().clone(), evaluation.invert());
} else {
bisector.mark(commit.id().clone(), evaluation);
}
// Reload the workspace because the evaluation command may run `jj` commands.
workspace_command = command.workspace_helper(ui)?;
}
jj_lib::bisect::NextStep::Done(bisection_result) => {
break bisection_result;
}
}
};
let mut formatter = ui.stdout_formatter();
writeln!(
formatter,
"Search complete. To discard any revisions created during search, run:"
)?;
writeln!(
formatter,
" jj op restore {}",
short_operation_hash(initial_repo.op_id())
)?;
let target = if args.find_good { "good" } else { "bad" };
match bisection_result {
BisectionResult::Indeterminate => {
return Err(user_error(format!(
"Could not find the first {target} revision. Was the input range empty?"
)));
}
BisectionResult::Found(first_target_commits) => {
let commit_template = workspace_command.commit_summary_template();
if let [first_target_commit] = first_target_commits.as_slice() {
write!(formatter, "The first {target} revision is: ")?;
commit_template.format(first_target_commit, formatter.as_mut())?;
writeln!(formatter)?;
} else {
writeln!(formatter, "The first {target} revisions are:")?;
for first_target_commit in first_target_commits {
commit_template.format(&first_target_commit, formatter.as_mut())?;
writeln!(formatter)?;
}
}
}
}
Ok(())
}
fn get_command(args: &BisectRunArgs) -> std::process::Command {
if let Some(command) = &args.command {
let mut cmd = std::process::Command::new(command);
cmd.args(&args.args);
cmd
} else {
args.legacy_command.as_ref().unwrap().to_command()
}
}
fn evaluate_commit(
ui: &mut Ui,
workspace_command: &mut WorkspaceCommandHelper,
mut cmd: std::process::Command,
commit: &Commit,
) -> Result<Evaluation, CommandError> {
let mut tx = workspace_command.start_transaction();
let commit_id_hex = commit.id().hex();
tx.check_out(commit)?;
tx.finish(
ui,
format!("Updated to revision {commit_id_hex} for bisection"),
)?;
let jj_executable_path = std::env::current_exe().map_err(|err| {
internal_error_with_message("Could not get path for the jj executable", err)
})?;
tracing::info!(?cmd, "running bisection evaluation command");
let status = cmd
.env("JJ_EXECUTABLE_PATH", jj_executable_path)
.env("JJ_BISECT_TARGET", &commit_id_hex)
.status()
.map_err(|err| user_error_with_message("Failed to run evaluation command", err))?;
let evaluation = if status.success() {
Evaluation::Good
} else {
match status.code() {
Some(125) => Evaluation::Skip,
Some(127) => {
return Err(user_error(
"Evaluation command returned 127 (command not found) - aborting bisection.",
));
}
_ => Evaluation::Bad,
}
};
Ok(evaluation)
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/gerrit/upload.rs | cli/src/commands/gerrit/upload.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::fmt::Debug;
use std::io::Write as _;
use std::sync::Arc;
use bstr::BStr;
use itertools::Itertools as _;
use jj_lib::backend::CommitId;
use jj_lib::commit::Commit;
use jj_lib::git;
use jj_lib::git::GitRefUpdate;
use jj_lib::git::GitSubprocessOptions;
use jj_lib::object_id::ObjectId as _;
use jj_lib::repo::Repo as _;
use jj_lib::revset::RevsetExpression;
use jj_lib::settings::UserSettings;
use jj_lib::store::Store;
use jj_lib::trailer::Trailer;
use jj_lib::trailer::parse_description_trailers;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::cli_util::short_change_hash;
use crate::command_error::CommandError;
use crate::command_error::internal_error;
use crate::command_error::user_error;
use crate::command_error::user_error_with_hint;
use crate::command_error::user_error_with_message;
use crate::git_util::with_remote_git_callbacks;
use crate::ui::Ui;
/// Upload changes to Gerrit for code review, or update existing changes.
///
/// Uploading in a set of revisions to Gerrit creates a single "change" for
/// each revision included in the revset. These changes are then available
/// for review on your Gerrit instance.
///
/// Note: The gerrit commit Id may not match that of your local commit Id,
/// since we add a `Change-Id` footer to the commit message if one does not
/// already exist. This ID is based off the jj Change-Id, but is not the same.
///
/// If a change already exists for a given revision (i.e. it contains the
/// same `Change-Id`), this command will update the contents of the existing
/// change to match.
///
/// Note: this command takes 1-or-more revsets arguments, each of which can
/// resolve to multiple revisions; so you may post trees or ranges of
/// commits to Gerrit for review all at once.
#[derive(clap::Args, Clone, Debug)]
pub struct UploadArgs {
/// The revset, selecting which revisions are sent in to Gerrit
///
/// This can be any arbitrary set of commits. Note that when you push a
/// commit at the head of a stack, all ancestors are pushed too. This means
/// that `jj gerrit upload -r foo` is equivalent to `jj gerrit upload -r
/// 'mutable()::foo`.
#[arg(long, short = 'r')]
revisions: Vec<RevisionArg>,
/// The location where your changes are intended to land
///
/// This should be a branch on the remote. Can be configured with the
/// `gerrit.default-remote-branch` repository option.
#[arg(long = "remote-branch", short = 'b')]
remote_branch: Option<String>,
/// The Gerrit remote to push to
///
/// Can be configured with the `gerrit.default-remote` repository option as
/// well. This is typically a full SSH URL for your Gerrit instance.
#[arg(long)]
remote: Option<String>,
/// Do not actually push the changes to Gerrit
#[arg(long = "dry-run", short = 'n')]
dry_run: bool,
}
fn calculate_push_remote(
store: &Arc<Store>,
settings: &UserSettings,
remote: Option<&str>,
) -> Result<String, CommandError> {
let git_repo = git::get_git_repo(store)?; // will fail if not a git repo
let remotes = git_repo.remote_names();
// If --remote was provided, use that
if let Some(remote) = remote {
if remotes.contains(BStr::new(&remote)) {
return Ok(remote.to_string());
}
return Err(user_error(format!(
"The remote '{remote}' (specified via `--remote`) does not exist",
)));
}
// If the Gerrit-specific config was set, use that
if let Ok(remote) = settings.get_string("gerrit.default-remote") {
if remotes.contains(BStr::new(&remote)) {
return Ok(remote);
}
return Err(user_error(format!(
"The remote '{remote}' (configured via `gerrit.default-remote`) does not exist",
)));
}
// If a general push remote was configured, use that
if let Some(remote) = git_repo.remote_default_name(gix::remote::Direction::Push) {
return Ok(remote.to_string());
}
// If there is a Git remote called "gerrit", use that
if remotes.iter().any(|r| **r == "gerrit") {
return Ok("gerrit".to_owned());
}
// Otherwise error out
Err(user_error(
"No remote specified, and no 'gerrit' remote was found",
))
}
/// Determine what Gerrit ref and remote to use. The logic is:
///
/// 1. If the user specifies `--remote-branch branch`, use that
/// 2. If the user has 'gerrit.default-remote-branch' configured, use that
/// 3. Otherwise, bail out
fn calculate_push_ref(
settings: &UserSettings,
remote_branch: Option<String>,
) -> Result<String, CommandError> {
// case 1
if let Some(remote_branch) = remote_branch {
return Ok(remote_branch);
}
// case 2
if let Ok(branch) = settings.get_string("gerrit.default-remote-branch") {
return Ok(branch);
}
// case 3
Err(user_error(
"No target branch specified via --remote-branch, and no 'gerrit.default-remote-branch' \
was found",
))
}
pub fn cmd_gerrit_upload(
ui: &mut Ui,
command: &CommandHelper,
args: &UploadArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let target_expr = workspace_command
.parse_union_revsets(ui, &args.revisions)?
.resolve()?;
workspace_command.check_rewritable_expr(&target_expr)?;
let revisions: Vec<_> = target_expr
.evaluate(workspace_command.repo().as_ref())?
.iter()
.try_collect()?;
if revisions.is_empty() {
writeln!(ui.status(), "No revisions to 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.
// We make an assumption here that all immutable commits already have a
// Change-ID.
let to_upload: Vec<Commit> = workspace_command
.attach_revset_evaluator(
workspace_command
.env()
.immutable_expression()
.range(&RevsetExpression::commits(revisions.clone())),
)
.evaluate_to_commits()?
.try_collect()?;
// Note: This transaction is intentionally never finished. This way, the
// Change-Id is never part of the commit description in jj.
// This avoids scenarios where you have many commits with the same
// Change-Id, or a single commit with many Change-Ids after running
// jj split / jj squash respectively.
// If a user doesn't like this behavior, they can add the following to
// their Cargo.toml.
// commit_trailers = 'if(!trailers.contains_key("Change-Id"),
// format_gerrit_change_id_trailer(self))'
let mut tx = workspace_command.start_transaction();
let base_repo = tx.base_repo();
let store = base_repo.store().clone();
let old_heads = base_repo
.index()
.heads(&mut revisions.iter())
.map_err(internal_error)?;
let subprocess_options = GitSubprocessOptions::from_settings(command.settings())?;
let remote = calculate_push_remote(&store, command.settings(), args.remote.as_deref())?;
let remote_branch = calculate_push_ref(command.settings(), args.remote_branch.clone())?;
// Immediately error and reject any commits that shouldn't be uploaded.
for commit in &to_upload {
if commit.is_empty(tx.repo_mut())? {
return Err(user_error_with_hint(
format!(
"Refusing to upload revision {} because it is empty",
short_change_hash(commit.change_id())
),
"Perhaps you squashed then ran upload? Maybe you meant to upload the parent \
commit instead (eg. @-)",
));
}
if commit.description().is_empty() {
return Err(user_error_with_hint(
format!(
"Refusing to upload revision {} because it is has no description",
short_change_hash(commit.change_id())
),
"Maybe you meant to upload the parent commit instead (eg. @-)",
));
}
}
let mut old_to_new: HashMap<CommitId, Commit> = HashMap::new();
for original_commit in to_upload.into_iter().rev() {
let trailers = parse_description_trailers(original_commit.description());
let change_id_trailers: Vec<&Trailer> = trailers
.iter()
.filter(|trailer| trailer.key == "Change-Id")
.collect();
// There shouldn't be multiple change-ID fields. So just error out if
// there is.
if change_id_trailers.len() > 1 {
return Err(user_error(format!(
"Multiple Change-Id footers in revision {}",
short_change_hash(original_commit.change_id())
)));
}
// The user can choose to explicitly set their own change-ID to
// override the default change-ID based on the jj change-ID.
let new_description = if let Some(trailer) = change_id_trailers.first() {
// Check the change-id format is correct.
if trailer.value.len() != 41 || !trailer.value.starts_with('I') {
// Intentionally leave the invalid change IDs as-is.
writeln!(
ui.warning_default(),
"Invalid Change-Id footer in revision {}",
short_change_hash(original_commit.change_id()),
)?;
}
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
// 6a6a6964 (hex of "jjid").
let gerrit_change_id = format!("I{}6a6a6964", original_commit.change_id().hex());
format!(
"{}{}Change-Id: {}\n",
original_commit.description().trim(),
if trailers.is_empty() { "\n\n" } else { "\n" },
gerrit_change_id
)
};
let new_parents = original_commit
.parent_ids()
.iter()
.map(|id| old_to_new.get(id).map_or(id, |p| p.id()).clone())
.collect();
if new_description == original_commit.description()
&& new_parents == original_commit.parent_ids()
{
// map the old commit to itself
old_to_new.insert(original_commit.id().clone(), original_commit);
continue;
}
// rewrite the set of parents to point to the commits that were
// previously rewritten in toposort order
let new_commit = tx
.repo_mut()
.rewrite_commit(&original_commit)
.set_description(new_description)
.set_parents(new_parents)
// Set the timestamp back to the timestamp of the original commit.
// Otherwise, `jj gerrit upload @ && jj gerrit upload @` will upload
// two patchsets with the only difference being the timestamp.
.set_committer(original_commit.committer().clone())
.set_author(original_commit.author().clone())
.write()?;
old_to_new.insert(original_commit.id().clone(), new_commit);
}
let remote_ref = format!("refs/for/{remote_branch}");
writeln!(
ui.status(),
"Found {} heads to push to Gerrit (remote '{}'), target branch '{}'",
old_heads.len(),
remote,
remote_branch,
)?;
// NOTE (aseipp): because we are pushing everything to the same remote ref,
// we have to loop and push each commit one at a time, even though
// push_updates in theory supports multiple GitRefUpdates at once, because
// we obviously can't push multiple heads to the same ref.
for head in &old_heads {
if let Some(mut formatter) = ui.status_formatter() {
if args.dry_run {
write!(formatter, "Dry-run: Would push ")?;
} else {
write!(formatter, "Pushing ")?;
}
// We have to write the old commit here, because until we finish
// the transaction (which we don't), the new commit is labeled as
// "hidden".
tx.base_workspace_helper()
.write_commit_summary(formatter.as_mut(), &store.get_commit(head).unwrap())?;
writeln!(formatter)?;
}
if args.dry_run {
continue;
}
let new_commit = old_to_new.get(head).unwrap();
// how do we get better errors from the remote? 'git push' tells us
// about rejected refs AND ALSO '(nothing changed)' when there are no
// changes to push, but we don't get that here.
with_remote_git_callbacks(ui, |cb| {
git::push_updates(
tx.repo_mut(),
subprocess_options.clone(),
remote.as_ref(),
&[GitRefUpdate {
qualified_name: remote_ref.clone().into(),
expected_current_target: None,
new_target: Some(new_commit.id().clone()),
}],
cb,
)
})
// Despite the fact that a manual git push will error out with 'no new
// changes' if you're up to date, this git backend appears to silently
// succeed - no idea why.
// It'd be nice if we could distinguish this. We should ideally succeed,
// but give the user a warning.
.map_err(|err| match err {
git::GitPushError::NoSuchRemote(_)
| git::GitPushError::RemoteName(_)
| git::GitPushError::UnexpectedBackend(_) => user_error(err),
git::GitPushError::Subprocess(_) => {
user_error_with_message("Internal git error while pushing to gerrit", err)
}
})?;
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/gerrit/mod.rs | cli/src/commands/gerrit/mod.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use clap::Subcommand;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::commands::gerrit;
use crate::ui::Ui;
/// Interact with Gerrit Code Review.
#[derive(Subcommand, Clone, Debug)]
pub enum GerritCommand {
Upload(gerrit::upload::UploadArgs),
}
pub fn cmd_gerrit(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &GerritCommand,
) -> Result<(), CommandError> {
match subcommand {
GerritCommand::Upload(review) => gerrit::upload::cmd_gerrit_upload(ui, command, review),
}
}
mod upload;
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/push.rs | cli/src/commands/git/push.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use std::io;
use std::io::Write as _;
use std::iter;
use clap::ArgGroup;
use clap_complete::ArgValueCandidates;
use clap_complete::ArgValueCompleter;
use indexmap::IndexSet;
use itertools::Itertools as _;
use jj_lib::backend::CommitId;
use jj_lib::commit::Commit;
use jj_lib::commit::CommitIteratorExt as _;
use jj_lib::config::ConfigGetResultExt as _;
use jj_lib::git;
use jj_lib::git::GitBranchPushTargets;
use jj_lib::git::GitPushStats;
use jj_lib::git::GitSettings;
use jj_lib::index::IndexResult;
use jj_lib::op_store::RefTarget;
use jj_lib::operation::Operation;
use jj_lib::ref_name::RefName;
use jj_lib::ref_name::RefNameBuf;
use jj_lib::ref_name::RemoteName;
use jj_lib::ref_name::RemoteNameBuf;
use jj_lib::ref_name::RemoteRefSymbol;
use jj_lib::refs::BookmarkPushAction;
use jj_lib::refs::BookmarkPushUpdate;
use jj_lib::refs::LocalAndRemoteRef;
use jj_lib::refs::classify_bookmark_push_action;
use jj_lib::repo::Repo;
use jj_lib::revset::RevsetExpression;
use jj_lib::settings::UserSettings;
use jj_lib::signing::SignBehavior;
use jj_lib::str_util::StringExpression;
use jj_lib::view::View;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::cli_util::WorkspaceCommandHelper;
use crate::cli_util::WorkspaceCommandTransaction;
use crate::cli_util::has_tracked_remote_bookmarks;
use crate::cli_util::short_commit_hash;
use crate::command_error::CommandError;
use crate::command_error::cli_error;
use crate::command_error::cli_error_with_message;
use crate::command_error::user_error;
use crate::command_error::user_error_with_hint;
use crate::command_error::user_error_with_message;
use crate::commands::git::get_single_remote;
use crate::complete;
use crate::formatter::Formatter;
use crate::formatter::FormatterExt as _;
use crate::git_util::with_remote_git_callbacks;
use crate::revset_util::parse_bookmark_name;
use crate::revset_util::parse_union_name_patterns;
use crate::ui::Ui;
/// Push to a Git remote
///
/// By default, pushes tracking bookmarks pointing to
/// `remote_bookmarks(remote=<remote>)..@`. Use `--bookmark` to push specific
/// bookmarks. Use `--all` to push all bookmarks. Use `--change` to generate
/// bookmark names based on the change IDs of specific commits.
///
/// When pushing a bookmark, the command pushes all commits in the range from
/// the remote's current position up to and including the bookmark's target
/// commit. Any descendant commits beyond the bookmark are not pushed.
///
/// If the local bookmark has changed from the last fetch, push will update the
/// remote bookmark to the new position after passing safety checks. This is
/// similar to `git push --force-with-lease` - the remote is updated only if its
/// current state matches what Jujutsu last fetched.
///
/// Unlike in Git, the remote to push to is not derived from the tracked remote
/// bookmarks. Use `--remote` to select the remote Git repository by name. There
/// is no option to push to multiple remotes.
///
/// Before the command actually moves, creates, or deletes a remote bookmark, it
/// makes several [safety checks]. If there is a problem, you may need to run
/// `jj git fetch --remote <remote name>` and/or resolve some [bookmark
/// conflicts].
///
/// [safety checks]:
/// https://docs.jj-vcs.dev/latest/bookmarks/#pushing-bookmarks-safety-checks
///
/// [bookmark conflicts]:
/// https://docs.jj-vcs.dev/latest/bookmarks/#conflicts
#[derive(clap::Args, Clone, Debug)]
#[command(group(ArgGroup::new("specific").args(&["bookmark", "change", "revisions", "named"]).multiple(true)))]
#[command(group(ArgGroup::new("what").args(&["all", "tracked"]).conflicts_with("specific")))]
pub struct GitPushArgs {
/// The remote to push to (only named remotes are supported)
///
/// This defaults to the `git.push` setting. If that is not configured, and
/// if there are multiple remotes, the remote named "origin" will be used.
#[arg(long)]
#[arg(add = ArgValueCandidates::new(complete::git_remotes))]
remote: Option<RemoteNameBuf>,
/// Push only this bookmark, or bookmarks matching a pattern (can be
/// repeated)
///
/// By default, the specified pattern matches bookmark names with glob
/// syntax. You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(long, short, alias = "branch")]
#[arg(add = ArgValueCandidates::new(complete::local_bookmarks))]
bookmark: Vec<String>,
/// Push all bookmarks (including new bookmarks)
#[arg(long)]
all: bool,
/// Push all tracked bookmarks
///
/// This usually means that the bookmark was already pushed to or fetched
/// from the [relevant remote].
///
/// [relevant remote]:
/// https://docs.jj-vcs.dev/latest/bookmarks#remotes-and-tracked-bookmarks
#[arg(long)]
tracked: bool,
/// Push all deleted bookmarks
///
/// Only tracked bookmarks can be successfully deleted on the remote. A
/// warning will be printed if any untracked bookmarks on the remote
/// correspond to missing local bookmarks.
#[arg(long, conflicts_with = "specific")]
deleted: bool,
// TODO: Delete in jj 0.42.0+
/// Allow pushing new bookmarks
///
/// Newly-created remote bookmarks will be tracked automatically.
#[arg(long, short = 'N', hide = true, conflicts_with = "what")]
allow_new: bool,
/// Allow pushing commits with empty descriptions
#[arg(long)]
allow_empty_description: bool,
/// Allow pushing commits that are private
///
/// The set of private commits can be configured by the
/// `git.private-commits` setting. The default is `none()`, meaning all
/// commits are eligible to be pushed.
#[arg(long)]
allow_private: bool,
/// Push bookmarks pointing to these commits (can be repeated)
#[arg(long, short, value_name = "REVSETS")]
// While `-r` will often be used with mutable revisions, immutable revisions
// can be useful as parts of revsets or to push special-purpose branches.
#[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
revisions: Vec<RevisionArg>,
/// Push this commit by creating a bookmark (can be repeated)
///
/// The created bookmark will be tracked automatically. Use the
/// `templates.git_push_bookmark` setting to customize the generated
/// bookmark name. The default is `"push-" ++ change_id.short()`.
#[arg(long, short, value_name = "REVSETS")]
// I'm guessing that `git push -c` is almost exclusively used with recently
// created mutable revisions, even though it can in theory be used with
// immutable ones as well. We can change it if the guess turns out to be
// wrong.
#[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
change: Vec<RevisionArg>,
/// Specify a new bookmark name and a revision to push under that name, e.g.
/// '--named myfeature=@'
///
/// Automatically tracks the bookmark if it is new.
#[arg(long, value_name = "NAME=REVISION")]
#[arg(add = ArgValueCompleter::new(complete::branch_name_equals_any_revision))]
named: Vec<String>,
/// Only display what will change on the remote
#[arg(long)]
dry_run: bool,
}
fn make_bookmark_term(bookmark_names: &[impl fmt::Display]) -> String {
match bookmark_names {
[bookmark_name] => format!("bookmark {bookmark_name}"),
bookmark_names => format!("bookmarks {}", bookmark_names.iter().join(", ")),
}
}
const DEFAULT_REMOTE: &RemoteName = RemoteName::new("origin");
const TX_DESC_PUSH: &str = "push ";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum BookmarkMoveDirection {
Forward,
Backward,
Sideways,
}
pub fn cmd_git_push(
ui: &mut Ui,
command: &CommandHelper,
args: &GitPushArgs,
) -> Result<(), CommandError> {
if args.allow_new {
writeln!(
ui.warning_default(),
"--allow-new is deprecated, track bookmarks manually or configure \
remotes.<name>.auto-track-bookmarks instead."
)?;
}
let mut workspace_command = command.workspace_helper(ui)?;
let default_remote;
let remote = if let Some(name) = &args.remote {
name
} else {
default_remote = get_default_push_remote(ui, &workspace_command)?;
&default_remote
};
let mut tx = workspace_command.start_transaction();
let view = tx.repo().view();
let tx_description;
let mut bookmark_updates = vec![];
if args.all {
for (name, targets) in view.local_remote_bookmarks(remote) {
let allow_new = true; // implied by --all
match classify_bookmark_update(
name.to_remote_symbol(remote),
targets,
allow_new,
args.deleted,
) {
Ok(Some(update)) => bookmark_updates.push((name.to_owned(), update)),
Ok(None) => {}
Err(reason) => reason.print(ui)?,
}
}
tx_description = format!(
"{TX_DESC_PUSH}all bookmarks to git remote {remote}",
remote = remote.as_symbol()
);
} else if args.tracked {
for (name, targets) in view.local_remote_bookmarks(remote) {
if !targets.remote_ref.is_tracked() {
continue;
}
let allow_new = false; // doesn't matter
match classify_bookmark_update(
name.to_remote_symbol(remote),
targets,
allow_new,
args.deleted,
) {
Ok(Some(update)) => bookmark_updates.push((name.to_owned(), update)),
Ok(None) => {}
Err(reason) => reason.print(ui)?,
}
}
tx_description = format!(
"{TX_DESC_PUSH}all tracked bookmarks to git remote {remote}",
remote = remote.as_symbol()
);
} else if args.deleted {
for (name, targets) in view.local_remote_bookmarks(remote) {
if targets.local_target.is_present() {
continue;
}
let allow_new = false; // doesn't matter
let allow_delete = true;
match classify_bookmark_update(
name.to_remote_symbol(remote),
targets,
allow_new,
allow_delete,
) {
Ok(Some(update)) => bookmark_updates.push((name.to_owned(), update)),
Ok(None) => {}
Err(reason) => reason.print(ui)?,
}
}
tx_description = format!(
"{TX_DESC_PUSH}all deleted bookmarks to git remote {remote}",
remote = remote.as_symbol()
);
} else {
let mut seen_bookmarks: HashSet<&RefName> = HashSet::new();
// --change and --named don't move existing bookmarks. If they did, be
// careful to not select old state by -r/--revisions and bookmark names.
let change_bookmark_names = create_change_bookmarks(ui, &mut tx, &args.change)?;
let created_bookmark_names: Vec<RefNameBuf> = args
.named
.iter()
.map(|name_revision| create_explicitly_named_bookmarks(ui, &mut tx, name_revision))
.try_collect()?;
let created_bookmarks = change_bookmark_names
.iter()
.chain(created_bookmark_names.iter())
.map(|name| {
let remote_symbol = name.to_remote_symbol(remote);
let targets = LocalAndRemoteRef {
local_target: tx.repo().view().get_local_bookmark(name),
remote_ref: tx.repo().view().get_remote_bookmark(remote_symbol),
};
(remote_symbol, targets)
});
for (remote_symbol, targets) in created_bookmarks {
let name = remote_symbol.name;
if !seen_bookmarks.insert(name) {
continue;
}
let allow_new = true; // --change implies creation of remote bookmark
let allow_delete = false; // doesn't matter
match classify_bookmark_update(remote_symbol, targets, allow_new, allow_delete) {
Ok(Some(update)) => bookmark_updates.push((name.to_owned(), update)),
Ok(None) => writeln!(
ui.status(),
"Bookmark {remote_symbol} already matches {name}",
name = name.as_symbol()
)?,
Err(reason) => return Err(reason.into()),
}
}
let view = tx.repo().view();
// TODO: Delete in jj 0.42.0+
let allow_new = args.allow_new || tx.settings().get("git.push-new-bookmarks")?;
let bookmarks_by_name = find_bookmarks_to_push(ui, view, &args.bookmark, remote)?;
for &(name, targets) in &bookmarks_by_name {
if !seen_bookmarks.insert(name) {
continue;
}
let remote_symbol = name.to_remote_symbol(remote);
let allow_delete = true; // named explicitly, allow delete without --delete
match classify_bookmark_update(remote_symbol, targets, allow_new, allow_delete) {
Ok(Some(update)) => bookmark_updates.push((name.to_owned(), update)),
Ok(None) => writeln!(
ui.status(),
"Bookmark {remote_symbol} already matches {name}",
name = name.as_symbol()
)?,
Err(reason) => return Err(reason.into()),
}
}
let use_default_revset = args.bookmark.is_empty()
&& args.change.is_empty()
&& args.revisions.is_empty()
&& args.named.is_empty();
let bookmarks_targeted = find_bookmarks_targeted_by_revisions(
ui,
tx.base_workspace_helper(),
remote,
&args.revisions,
use_default_revset,
)?;
for &(name, targets) in &bookmarks_targeted {
if !seen_bookmarks.insert(name) {
continue;
}
let allow_delete = false;
match classify_bookmark_update(
name.to_remote_symbol(remote),
targets,
allow_new,
allow_delete,
) {
Ok(Some(update)) => bookmark_updates.push((name.to_owned(), update)),
Ok(None) => {}
Err(reason) => reason.print(ui)?,
}
}
tx_description = format!(
"{TX_DESC_PUSH}{names} to git remote {remote}",
names = make_bookmark_term(
&bookmark_updates
.iter()
.map(|(name, _)| name.as_symbol())
.collect_vec()
),
remote = remote.as_symbol()
);
}
if bookmark_updates.is_empty() {
writeln!(ui.status(), "Nothing changed.")?;
return Ok(());
}
let sign_behavior = if tx.settings().get_bool("git.sign-on-push")? {
Some(SignBehavior::Own)
} else {
None
};
let commits_to_sign =
validate_commits_ready_to_push(ui, &bookmark_updates, remote, &tx, args, sign_behavior)?;
if !args.dry_run
&& !commits_to_sign.is_empty()
&& let Some(sign_behavior) = sign_behavior
{
let num_updated_signatures = commits_to_sign.len();
let num_rebased_descendants;
(num_rebased_descendants, bookmark_updates) =
sign_commits_before_push(&mut tx, commits_to_sign, sign_behavior, bookmark_updates)?;
if let Some(mut formatter) = ui.status_formatter() {
writeln!(
formatter,
"Updated signatures of {num_updated_signatures} commits"
)?;
if num_rebased_descendants > 0 {
writeln!(
formatter,
"Rebased {num_rebased_descendants} descendant commits"
)?;
}
}
}
if let Some(mut formatter) = ui.status_formatter() {
writeln!(
formatter,
"Changes to push to {remote}:",
remote = remote.as_symbol()
)?;
print_commits_ready_to_push(formatter.as_mut(), tx.repo(), &bookmark_updates)?;
}
if args.dry_run {
writeln!(ui.status(), "Dry-run requested, not pushing.")?;
return Ok(());
}
let targets = GitBranchPushTargets {
branch_updates: bookmark_updates,
};
let git_settings = GitSettings::from_settings(tx.settings())?;
let push_stats = with_remote_git_callbacks(ui, |cb| {
git::push_branches(
tx.repo_mut(),
git_settings.to_subprocess_options(),
remote,
&targets,
cb,
)
})?;
print_stats(ui, &push_stats)?;
// TODO: On partial success, locally-created --change/--named bookmarks will
// be committed. It's probably better to remove failed local bookmarks.
if push_stats.all_ok() || !push_stats.pushed.is_empty() {
tx.finish(ui, tx_description)?;
}
if push_stats.all_ok() {
Ok(())
} else {
Err(user_error("Failed to push some bookmarks"))
}
}
fn print_stats(ui: &Ui, stats: &GitPushStats) -> io::Result<()> {
if !stats.rejected.is_empty() {
writeln!(
ui.warning_default(),
"The following references unexpectedly moved on the remote:"
)?;
let mut formatter = ui.stderr_formatter();
for (reference, reason) in &stats.rejected {
write!(formatter, " ")?;
write!(formatter.labeled("git_ref"), "{}", reference.as_symbol())?;
if let Some(r) = reason {
write!(formatter, " (reason: {r})")?;
}
writeln!(formatter)?;
}
drop(formatter);
writeln!(
ui.hint_default(),
"Try fetching from the remote, then make the bookmark point to where you want it to \
be, and push again.",
)?;
}
if !stats.remote_rejected.is_empty() {
writeln!(
ui.warning_default(),
"The remote rejected the following updates:"
)?;
let mut formatter = ui.stderr_formatter();
for (reference, reason) in &stats.remote_rejected {
write!(formatter, " ")?;
write!(formatter.labeled("git_ref"), "{}", reference.as_symbol())?;
if let Some(r) = reason {
write!(formatter, " (reason: {r})")?;
}
writeln!(formatter)?;
}
drop(formatter);
writeln!(
ui.hint_default(),
"Try checking if you have permission to push to all the bookmarks."
)?;
}
Ok(())
}
/// Validates that the commits that will be pushed are ready (have authorship
/// information, are not conflicted, etc.).
///
/// Returns the list of commits which need to be signed.
fn validate_commits_ready_to_push(
ui: &Ui,
bookmark_updates: &[(RefNameBuf, BookmarkPushUpdate)],
remote: &RemoteName,
tx: &WorkspaceCommandTransaction,
args: &GitPushArgs,
sign_behavior: Option<SignBehavior>,
) -> Result<Vec<Commit>, CommandError> {
let workspace_helper = tx.base_workspace_helper();
let repo = workspace_helper.repo();
let new_heads = bookmark_updates
.iter()
.filter_map(|(_, update)| update.new_target.clone())
.collect_vec();
let old_heads = repo
.view()
.remote_bookmarks(remote)
.flat_map(|(_, old_head)| old_head.target.added_ids())
.cloned()
.collect_vec();
let commits_to_push = RevsetExpression::commits(old_heads)
.union(workspace_helper.env().immutable_heads_expression())
.range(&RevsetExpression::commits(new_heads));
let settings = workspace_helper.settings();
let private_revset_str = RevisionArg::from(settings.get_string("git.private-commits")?);
let is_private = workspace_helper
.parse_revset(ui, &private_revset_str)?
.evaluate()?
.containing_fn();
let sign_settings = sign_behavior.map(|sign_behavior| {
let mut sign_settings = settings.sign_settings();
sign_settings.behavior = sign_behavior;
sign_settings
});
let mut commits_to_sign = vec![];
for commit in workspace_helper
.attach_revset_evaluator(commits_to_push)
.evaluate_to_commits()?
{
let commit = commit?;
let mut reasons = vec![];
if commit.description().is_empty() && !args.allow_empty_description {
reasons.push("it has no description");
}
if commit.author().name.is_empty()
|| commit.author().name == UserSettings::USER_NAME_PLACEHOLDER
|| commit.author().email.is_empty()
|| commit.author().email == UserSettings::USER_EMAIL_PLACEHOLDER
|| commit.committer().name.is_empty()
|| commit.committer().name == UserSettings::USER_NAME_PLACEHOLDER
|| commit.committer().email.is_empty()
|| commit.committer().email == UserSettings::USER_EMAIL_PLACEHOLDER
{
reasons.push("it has no author and/or committer set");
}
if commit.has_conflict() {
reasons.push("it has conflicts");
}
let is_private = is_private(commit.id())?;
if !args.allow_private && is_private {
reasons.push("it is private");
}
if !reasons.is_empty() {
let mut error = user_error(format!(
"Won't push commit {} since {}",
short_commit_hash(commit.id()),
reasons.join(" and ")
));
error.add_formatted_hint_with(|formatter| {
write!(formatter, "Rejected commit: ")?;
workspace_helper.write_commit_summary(formatter, &commit)?;
Ok(())
});
if !args.allow_private && is_private {
error.add_hint(format!(
"Configured git.private-commits: '{private_revset_str}'",
));
}
return Err(error);
}
if let Some(sign_settings) = &sign_settings
&& !commit.is_signed()
&& sign_settings.should_sign(commit.store_commit())
{
commits_to_sign.push(commit);
}
}
Ok(commits_to_sign)
}
/// Signs commits before pushing.
///
/// Returns the number of commits with rebased descendants and the updated list
/// of bookmark names and corresponding [`BookmarkPushUpdate`]s.
fn sign_commits_before_push(
tx: &mut WorkspaceCommandTransaction,
commits_to_sign: Vec<Commit>,
sign_behavior: SignBehavior,
bookmark_updates: Vec<(RefNameBuf, BookmarkPushUpdate)>,
) -> Result<(usize, Vec<(RefNameBuf, BookmarkPushUpdate)>), CommandError> {
let commit_ids: IndexSet<CommitId> = commits_to_sign.iter().ids().cloned().collect();
let mut old_to_new_commits_map: HashMap<CommitId, CommitId> = HashMap::new();
let mut num_rebased_descendants = 0;
tx.repo_mut().transform_descendants(
commit_ids.iter().cloned().collect_vec(),
async |rewriter| {
let old_commit_id = rewriter.old_commit().id().clone();
if commit_ids.contains(&old_commit_id) {
let commit = rewriter
.reparent()
.set_sign_behavior(sign_behavior)
.write()?;
old_to_new_commits_map.insert(old_commit_id, commit.id().clone());
} else {
num_rebased_descendants += 1;
let commit = rewriter.reparent().write()?;
old_to_new_commits_map.insert(old_commit_id, commit.id().clone());
}
Ok(())
},
)?;
let bookmark_updates = bookmark_updates
.into_iter()
.map(|(bookmark_name, update)| {
(
bookmark_name,
BookmarkPushUpdate {
old_target: update.old_target,
new_target: update
.new_target
.map(|id| old_to_new_commits_map.get(&id).cloned().unwrap_or(id)),
},
)
})
.collect_vec();
Ok((num_rebased_descendants, bookmark_updates))
}
fn print_commits_ready_to_push(
formatter: &mut dyn Formatter,
repo: &dyn Repo,
bookmark_updates: &[(RefNameBuf, BookmarkPushUpdate)],
) -> Result<(), CommandError> {
let to_direction =
|old_target: &CommitId, new_target: &CommitId| -> IndexResult<BookmarkMoveDirection> {
assert_ne!(old_target, new_target);
if repo.index().is_ancestor(old_target, new_target)? {
Ok(BookmarkMoveDirection::Forward)
} else if repo.index().is_ancestor(new_target, old_target)? {
Ok(BookmarkMoveDirection::Backward)
} else {
Ok(BookmarkMoveDirection::Sideways)
}
};
for (bookmark_name, update) in bookmark_updates {
match (&update.old_target, &update.new_target) {
(Some(old_target), Some(new_target)) => {
let bookmark_name = bookmark_name.as_symbol();
let old = short_commit_hash(old_target);
let new = short_commit_hash(new_target);
// TODO(ilyagr): Add color. Once there is color, "Move bookmark ... sideways"
// may read more naturally than "Move sideways bookmark ...".
// Without color, it's hard to see at a glance if one bookmark
// among many was moved sideways (say). TODO: People on Discord
// suggest "Move bookmark ... forward by n commits",
// possibly "Move bookmark ... sideways (X forward, Y back)".
let msg = match to_direction(old_target, new_target)? {
BookmarkMoveDirection::Forward => {
format!("Move forward bookmark {bookmark_name} from {old} to {new}")
}
BookmarkMoveDirection::Backward => {
format!("Move backward bookmark {bookmark_name} from {old} to {new}")
}
BookmarkMoveDirection::Sideways => {
format!("Move sideways bookmark {bookmark_name} from {old} to {new}")
}
};
writeln!(formatter, " {msg}")?;
}
(Some(old_target), None) => {
writeln!(
formatter,
" Delete bookmark {bookmark_name} from {old}",
bookmark_name = bookmark_name.as_symbol(),
old = short_commit_hash(old_target)
)?;
}
(None, Some(new_target)) => {
writeln!(
formatter,
" Add bookmark {bookmark_name} to {new}",
bookmark_name = bookmark_name.as_symbol(),
new = short_commit_hash(new_target)
)?;
}
(None, None) => {
panic!("Not pushing any change to bookmark {bookmark_name:?}");
}
}
}
Ok(())
}
fn get_default_push_remote(
ui: &Ui,
workspace_command: &WorkspaceCommandHelper,
) -> Result<RemoteNameBuf, CommandError> {
let settings = workspace_command.settings();
if let Some(remote) = settings.get_string("git.push").optional()? {
Ok(remote.into())
} else if let Some(remote) = get_single_remote(workspace_command.repo().store())? {
// similar to get_default_fetch_remotes
if remote != DEFAULT_REMOTE {
writeln!(
ui.hint_default(),
"Pushing to the only existing remote: {remote}",
remote = remote.as_symbol()
)?;
}
Ok(remote)
} else {
Ok(DEFAULT_REMOTE.to_owned())
}
}
#[derive(Clone, Debug)]
struct RejectedBookmarkUpdateReason {
message: String,
hint: Option<String>,
}
impl RejectedBookmarkUpdateReason {
fn print(&self, ui: &Ui) -> io::Result<()> {
writeln!(ui.warning_default(), "{}", self.message)?;
if let Some(hint) = &self.hint {
writeln!(ui.hint_default(), "{hint}")?;
}
Ok(())
}
}
impl From<RejectedBookmarkUpdateReason> for CommandError {
fn from(reason: RejectedBookmarkUpdateReason) -> Self {
let RejectedBookmarkUpdateReason { message, hint } = reason;
let mut cmd_err = user_error(message);
cmd_err.extend_hints(hint);
cmd_err
}
}
fn classify_bookmark_update(
remote_symbol: RemoteRefSymbol<'_>,
targets: LocalAndRemoteRef,
allow_new: bool,
allow_delete: bool,
) -> Result<Option<BookmarkPushUpdate>, RejectedBookmarkUpdateReason> {
let push_action = classify_bookmark_push_action(targets);
match push_action {
BookmarkPushAction::AlreadyMatches => Ok(None),
BookmarkPushAction::LocalConflicted => Err(RejectedBookmarkUpdateReason {
message: format!(
"Bookmark {name} is conflicted",
name = remote_symbol.name.as_symbol()
),
hint: Some(
"Run `jj bookmark list` to inspect, and use `jj bookmark set` to fix it up."
.to_owned(),
),
}),
BookmarkPushAction::RemoteConflicted => Err(RejectedBookmarkUpdateReason {
message: format!("Bookmark {remote_symbol} is conflicted"),
hint: Some("Run `jj git fetch` to update the conflicted remote bookmark.".to_owned()),
}),
BookmarkPushAction::RemoteUntracked => Err(RejectedBookmarkUpdateReason {
message: format!("Non-tracking remote bookmark {remote_symbol} exists"),
hint: Some(format!(
"Run `jj bookmark track {name} --remote={remote}` to import the remote bookmark.",
name = remote_symbol.name.as_symbol(),
remote = remote_symbol.remote.as_symbol()
)),
}),
// TODO: deprecate --allow-new and make classify_bookmark_push_action()
// reject untracked remote?
BookmarkPushAction::Update(_) if !targets.remote_ref.is_tracked() && !allow_new => {
Err(RejectedBookmarkUpdateReason {
message: format!("Refusing to create new remote bookmark {remote_symbol}"),
hint: Some(format!(
"Run `jj bookmark track {name} --remote={remote}` and try again.",
name = remote_symbol.name.as_symbol(),
remote = remote_symbol.remote.as_symbol()
)),
})
}
BookmarkPushAction::Update(update) if update.new_target.is_none() && !allow_delete => {
Err(RejectedBookmarkUpdateReason {
message: format!(
"Refusing to push deleted bookmark {name}",
name = remote_symbol.name.as_symbol(),
),
hint: Some(
"Push deleted bookmarks with --deleted or forget the bookmark to suppress \
this warning."
.to_owned(),
),
})
}
BookmarkPushAction::Update(update) => Ok(Some(update)),
}
}
fn ensure_new_bookmark_name(repo: &dyn Repo, name: &RefName) -> Result<(), CommandError> {
let symbol = name.as_symbol();
if repo.view().get_local_bookmark(name).is_present() {
return Err(user_error_with_hint(
format!("Bookmark already exists: {symbol}"),
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/root.rs | cli/src/commands/git/root.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::Write as _;
use jj_lib::file_util;
use jj_lib::repo::Repo as _;
use tracing::instrument;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::ui::Ui;
/// Show the underlying Git directory of a repository using the Git backend
#[derive(clap::Args, Clone, Debug)]
pub struct GitRootArgs {}
#[instrument(skip_all)]
pub fn cmd_git_root(
ui: &mut Ui,
command: &CommandHelper,
_args: &GitRootArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let store = workspace_command.repo().store();
let git_backend = jj_lib::git::get_git_backend(store)?;
let path_bytes = file_util::path_to_bytes(git_backend.git_repo_path()).map_err(user_error)?;
ui.stdout().write_all(path_bytes)?;
writeln!(ui.stdout())?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/fetch.rs | cli/src/commands/git/fetch.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io;
use clap_complete::ArgValueCandidates;
use itertools::Itertools as _;
use jj_lib::config::ConfigGetResultExt as _;
use jj_lib::git;
use jj_lib::git::GitFetch;
use jj_lib::git::GitSettings;
use jj_lib::git::IgnoredRefspec;
use jj_lib::git::IgnoredRefspecs;
use jj_lib::git::expand_default_fetch_refspecs;
use jj_lib::git::expand_fetch_refspecs;
use jj_lib::git::get_git_backend;
use jj_lib::ref_name::RefName;
use jj_lib::ref_name::RemoteName;
use jj_lib::repo::Repo as _;
use jj_lib::str_util::StringExpression;
use crate::cli_util::CommandHelper;
use crate::cli_util::WorkspaceCommandHelper;
use crate::cli_util::WorkspaceCommandTransaction;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::commands::git::get_single_remote;
use crate::complete;
use crate::git_util::load_git_import_options;
use crate::git_util::print_git_import_stats;
use crate::git_util::with_remote_git_callbacks;
use crate::revset_util::parse_union_name_patterns;
use crate::ui::Ui;
/// Fetch from a Git remote
///
/// If a working-copy commit gets abandoned, it will be given a new, empty
/// commit. This is true in general; it is not specific to this command.
#[derive(clap::Args, Clone, Debug)]
pub struct GitFetchArgs {
/// Fetch only some of the branches
///
/// By default, the specified pattern matches branch names with glob syntax,
/// but only `*` is expanded. Other wildcard characters such as `?` are
/// *not* supported. Patterns can be repeated or combined with [logical
/// operators] to specify multiple branches, but only union and negative
/// intersection are supported.
///
/// Examples: `push-*`, `(push-* | foo/*) ~ foo/unwanted`
///
/// [logical operators]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(long, short, alias = "bookmark")]
#[arg(add = ArgValueCandidates::new(complete::bookmarks))]
branch: Option<Vec<String>>,
/// Fetch only tracked bookmarks
///
/// This fetches only bookmarks that are already tracked from the specified
/// remote(s).
#[arg(long, conflicts_with = "branch")]
tracked: bool,
/// The remote to fetch from (only named remotes are supported, can be
/// repeated)
///
/// This defaults to the `git.fetch` setting. If that is not configured, and
/// if there are multiple remotes, the remote named "origin" will be used.
///
/// By default, the specified pattern matches remote names with glob syntax,
/// e.g. `--remote '*'`. You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(long = "remote", value_name = "REMOTE")]
#[arg(add = ArgValueCandidates::new(complete::git_remotes))]
remotes: Option<Vec<String>>,
/// Fetch from all remotes
#[arg(long, conflicts_with = "remotes")]
all_remotes: bool,
}
#[tracing::instrument(skip_all)]
pub fn cmd_git_fetch(
ui: &mut Ui,
command: &CommandHelper,
args: &GitFetchArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let remote_expr = if args.all_remotes {
StringExpression::all()
} else if let Some(remotes) = &args.remotes {
parse_union_name_patterns(ui, remotes)?
} else {
get_default_fetch_remotes(ui, &workspace_command)?
};
let remote_matcher = remote_expr.to_matcher();
let all_remotes = git::get_all_remote_names(workspace_command.repo().store())?;
let matching_remotes: Vec<&RemoteName> = all_remotes
.iter()
.filter(|r| remote_matcher.is_match(r.as_str()))
.map(AsRef::as_ref)
.collect();
let mut unmatched_remotes = remote_expr
.exact_strings()
.map(RemoteName::new)
// do linear search. all_remotes should be small.
.filter(|&name| all_remotes.iter().all(|r| r != name))
.peekable();
if unmatched_remotes.peek().is_some() {
writeln!(
ui.warning_default(),
"No matching remotes for names: {}",
unmatched_remotes.map(|name| name.as_symbol()).join(", ")
)?;
}
if matching_remotes.is_empty() {
return Err(user_error("No git remotes to fetch from"));
}
let mut tx = workspace_command.start_transaction();
let common_bookmark_expr = match &args.branch {
Some(texts) => Some(parse_union_name_patterns(ui, texts)?),
None => None,
};
let mut expansions = Vec::with_capacity(matching_remotes.len());
if args.tracked {
for remote in &matching_remotes {
let bookmark_expr = StringExpression::union_all(
tx.repo()
.view()
.local_remote_bookmarks(remote)
.filter(|(_, targets)| targets.remote_ref.is_tracked())
.map(|(name, _)| StringExpression::exact(name))
.collect(),
);
expansions.push((remote, expand_fetch_refspecs(remote, bookmark_expr)?));
}
} else if let Some(bookmark_expr) = &common_bookmark_expr {
for remote in &matching_remotes {
let expanded = expand_fetch_refspecs(remote, bookmark_expr.clone())?;
expansions.push((remote, expanded));
}
} else {
let git_repo = get_git_backend(tx.repo_mut().store())?.git_repo();
for remote in &matching_remotes {
let (ignored, expanded) = expand_default_fetch_refspecs(remote, &git_repo)?;
warn_ignored_refspecs(ui, remote, ignored)?;
expansions.push((remote, expanded));
}
};
let git_settings = GitSettings::from_settings(tx.settings())?;
let remote_settings = tx.settings().remote_settings()?;
let import_options = load_git_import_options(ui, &git_settings, &remote_settings)?;
let mut git_fetch = GitFetch::new(
tx.repo_mut(),
git_settings.to_subprocess_options(),
&import_options,
)?;
for (remote, expanded) in expansions {
with_remote_git_callbacks(ui, |callbacks| {
git_fetch.fetch(remote, expanded, callbacks, None, None)
})?;
}
let import_stats = git_fetch.import_refs()?;
print_git_import_stats(ui, tx.repo(), &import_stats, true)?;
if let Some(bookmark_expr) = &common_bookmark_expr {
warn_if_branches_not_found(ui, &tx, bookmark_expr, &matching_remotes)?;
}
tx.finish(
ui,
format!(
"fetch from git remote(s) {}",
matching_remotes.iter().map(|n| n.as_symbol()).join(",")
),
)?;
Ok(())
}
const DEFAULT_REMOTE: &RemoteName = RemoteName::new("origin");
fn get_default_fetch_remotes(
ui: &Ui,
workspace_command: &WorkspaceCommandHelper,
) -> Result<StringExpression, CommandError> {
const KEY: &str = "git.fetch";
let settings = workspace_command.settings();
if let Ok(remotes) = settings.get::<Vec<String>>(KEY) {
parse_union_name_patterns(ui, &remotes)
} else if let Some(remote) = settings.get_string(KEY).optional()? {
parse_union_name_patterns(ui, [&remote])
} else if let Some(remote) = get_single_remote(workspace_command.repo().store())? {
// if nothing was explicitly configured, try to guess
if remote != DEFAULT_REMOTE {
writeln!(
ui.hint_default(),
"Fetching from the only existing remote: {remote}",
remote = remote.as_symbol()
)?;
}
Ok(StringExpression::exact(remote))
} else {
Ok(StringExpression::exact(DEFAULT_REMOTE))
}
}
fn warn_if_branches_not_found(
ui: &mut Ui,
tx: &WorkspaceCommandTransaction,
bookmark_expr: &StringExpression,
remotes: &[&RemoteName],
) -> io::Result<()> {
let bookmark_matcher = bookmark_expr.to_matcher();
let mut missing_branches = bookmark_expr
.exact_strings()
.filter(|name| bookmark_matcher.is_match(name)) // exclude negative patterns
.map(RefName::new)
.filter(|name| {
remotes.iter().all(|&remote| {
let symbol = name.to_remote_symbol(remote);
let view = tx.repo().view();
let base_view = tx.base_repo().view();
view.get_remote_bookmark(symbol).is_absent()
&& base_view.get_remote_bookmark(symbol).is_absent()
})
})
.peekable();
if missing_branches.peek().is_none() {
return Ok(());
}
writeln!(
ui.warning_default(),
"No matching branches found on any specified/configured remote: {}",
missing_branches.map(|name| name.as_symbol()).join(", ")
)
}
fn warn_ignored_refspecs(
ui: &Ui,
remote_name: &RemoteName,
IgnoredRefspecs(ignored_refspecs): IgnoredRefspecs,
) -> Result<(), CommandError> {
let remote_name = remote_name.as_symbol();
for IgnoredRefspec { refspec, reason } in ignored_refspecs {
writeln!(
ui.warning_default(),
"Ignored refspec `{refspec}` from `{remote_name}`: {reason}",
)?;
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/clone.rs | cli/src/commands/git/clone.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs;
use std::io;
use std::io::Write as _;
use std::num::NonZeroU32;
use std::path::Path;
use itertools::Itertools as _;
use jj_lib::file_util;
use jj_lib::git;
use jj_lib::git::FetchTagsOverride;
use jj_lib::git::GitFetch;
use jj_lib::git::GitSettings;
use jj_lib::git::expand_fetch_refspecs;
use jj_lib::ref_name::RefName;
use jj_lib::ref_name::RefNameBuf;
use jj_lib::ref_name::RemoteName;
use jj_lib::ref_name::RemoteNameBuf;
use jj_lib::repo::Repo as _;
use jj_lib::str_util::StringExpression;
use jj_lib::workspace::Workspace;
use super::write_repository_level_trunk_alias;
use crate::cli_util::CommandHelper;
use crate::cli_util::WorkspaceCommandHelper;
use crate::command_error::CommandError;
use crate::command_error::cli_error;
use crate::command_error::user_error;
use crate::command_error::user_error_with_message;
use crate::commands::git::FetchTagsMode;
use crate::commands::git::maybe_add_gitignore;
use crate::git_util::absolute_git_url;
use crate::git_util::load_git_import_options;
use crate::git_util::print_git_import_stats;
use crate::git_util::with_remote_git_callbacks;
use crate::revset_util::parse_union_name_patterns;
use crate::ui::Ui;
/// Create a new repo backed by a clone of a Git repo
#[derive(clap::Args, Clone, Debug)]
pub struct GitCloneArgs {
/// URL or path of the Git repo to clone
///
/// Local path will be resolved to absolute form.
#[arg(value_hint = clap::ValueHint::Url)]
source: String,
/// Specifies the target directory for the Jujutsu repository clone.
/// If not provided, defaults to a directory named after the last component
/// of the source URL. The full directory path will be created if it
/// doesn't exist.
#[arg(value_hint = clap::ValueHint::DirPath)]
destination: Option<String>,
/// Name of the newly created remote
#[arg(long = "remote", default_value = "origin")]
remote_name: RemoteNameBuf,
/// Colocate the Jujutsu repo with the git repo
///
/// Specifies that the `jj` repo should also be a valid `git` repo, allowing
/// the use of both `jj` and `git` commands in the same directory.
///
/// The repository will contain a `.git` dir in the top-level. Regular Git
/// tools will be able to operate on the repo.
///
/// **This is the default**, and this option has no effect, unless the
/// [git.colocate config] is set to `false`.
///
/// [git.colocate config]:
/// https://docs.jj-vcs.dev/latest/config/#default-colocation
#[arg(long)]
colocate: bool,
/// Disable colocation of the Jujutsu repo with the git repo
///
/// Prevent Git tools that are unaware of `jj` and regular Git commands from
/// operating on the repo. The Git repository that stores most of the repo
/// data will be hidden inside a sub-directory of the `.jj` directory.
///
/// See [colocation docs] for some minor advantages of non-colocated
/// workspaces.
///
/// [colocation docs]:
/// https://docs.jj-vcs.dev/latest/git-compatibility/#colocated-jujutsugit-repos
#[arg(long, conflicts_with = "colocate")]
no_colocate: bool,
/// Create a shallow clone of the given depth
#[arg(long)]
depth: Option<NonZeroU32>,
/// Configure when to fetch tags
///
/// Unless otherwise specified, the initial clone will fetch all tags,
/// while all subsequent fetches will only fetch included tags.
#[arg(long, value_enum)]
fetch_tags: Option<FetchTagsMode>,
/// Name of the branch to fetch and use as the parent of the working-copy
/// change
///
/// If not present, all branches are fetched and the repository's default
/// branch is used as parent of the working-copy change.
///
/// By default, the specified pattern matches branch names with glob syntax,
/// but only `*` is expanded. Other wildcard characters such as `?` are
/// *not* supported. Patterns can be repeated or combined with [logical
/// operators] to specify multiple branches, but only union and negative
/// intersection are supported. If there are multiple matching branches, the
/// first exact branch name is used as the working-copy parent.
///
/// Examples: `push-*`, `(push-* | foo/*) ~ foo/unwanted`
///
/// [logical operators]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(long, short, alias = "bookmark")]
branch: Option<Vec<String>>,
}
fn clone_destination_for_source(source: &str) -> Option<&str> {
let destination = source.strip_suffix(".git").unwrap_or(source);
let destination = destination.strip_suffix('/').unwrap_or(destination);
destination
.rsplit_once(&['/', '\\', ':'][..])
.map(|(_, name)| name)
}
pub fn cmd_git_clone(
ui: &mut Ui,
command: &CommandHelper,
args: &GitCloneArgs,
) -> Result<(), CommandError> {
let remote_name = &args.remote_name;
if command.global_args().at_operation.is_some() {
return Err(cli_error("--at-op is not respected"));
}
let source = absolute_git_url(command.cwd(), &args.source)?;
let wc_path_str = args
.destination
.as_deref()
.or_else(|| clone_destination_for_source(&source))
.ok_or_else(|| user_error("No destination specified and wasn't able to guess it"))?;
let wc_path = command.cwd().join(wc_path_str);
let wc_path_existed = wc_path.exists();
if wc_path_existed && !file_util::is_empty_dir(&wc_path)? {
return Err(user_error(
"Destination path exists and is not an empty directory",
));
}
// will create a tree dir in case if was deleted after last check
fs::create_dir_all(&wc_path)
.map_err(|err| user_error_with_message(format!("Failed to create {wc_path_str}"), err))?;
let colocate = if command.settings().get_bool("git.colocate")? {
!args.no_colocate
} else {
args.colocate
};
let bookmark_expr = match &args.branch {
Some(texts) => parse_union_name_patterns(ui, texts)?,
None => StringExpression::all(),
};
// Canonicalize because fs::remove_dir_all() doesn't seem to like e.g.
// `/some/path/.`
let canonical_wc_path = dunce::canonicalize(&wc_path)
.map_err(|err| user_error_with_message(format!("Failed to create {wc_path_str}"), err))?;
let clone_result = (|| -> Result<_, CommandError> {
let workspace_command = init_workspace(ui, command, &canonical_wc_path, colocate)?;
let mut workspace_command = configure_remote(
ui,
command,
workspace_command,
remote_name,
&source,
// If not explicitly specified on the CLI, configure the remote for only fetching
// included tags for future fetches.
args.fetch_tags.unwrap_or(FetchTagsMode::Included),
&bookmark_expr,
)?;
let default_branch = fetch_new_remote(
ui,
&mut workspace_command,
remote_name,
// If we add default fetch patterns to jj's config, these patterns
// will be loaded here?
&bookmark_expr,
args.depth,
args.fetch_tags,
)?;
Ok((workspace_command, default_branch))
})();
if clone_result.is_err() {
let clean_up_dirs = || -> io::Result<()> {
let sub_dirs = [Some(".jj"), colocate.then_some(".git")];
for &name in sub_dirs.iter().flatten() {
let dir = canonical_wc_path.join(name);
fs::remove_dir_all(&dir).or_else(|err| match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(err),
})?;
}
if !wc_path_existed {
fs::remove_dir(&canonical_wc_path)?;
}
Ok(())
};
if let Err(err) = clean_up_dirs() {
writeln!(
ui.warning_default(),
"Failed to clean up {}: {}",
canonical_wc_path.display(),
err
)
.ok();
}
}
let (mut workspace_command, (working_branch, working_is_default)) = clone_result?;
if let Some(name) = &working_branch {
let working_symbol = name.to_remote_symbol(remote_name);
if working_is_default {
write_repository_level_trunk_alias(ui, workspace_command.repo_path(), working_symbol)?;
}
let working_branch_remote_ref = workspace_command
.repo()
.view()
.get_remote_bookmark(working_symbol);
if let Some(commit_id) = working_branch_remote_ref.target.as_normal().cloned() {
let mut tx = workspace_command.start_transaction();
if let Ok(commit) = tx.repo().store().get_commit(&commit_id) {
tx.check_out(&commit)?;
}
tx.finish(
ui,
format!("check out git remote's branch: {}", name.as_symbol()),
)?;
}
}
if colocate {
writeln!(
ui.hint_default(),
r"Running `git clean -xdf` will remove `.jj/`!",
)?;
}
Ok(())
}
fn init_workspace(
ui: &Ui,
command: &CommandHelper,
wc_path: &Path,
colocate: bool,
) -> Result<WorkspaceCommandHelper, CommandError> {
let settings = command.settings_for_new_workspace(wc_path)?;
let (workspace, repo) = if colocate {
Workspace::init_colocated_git(&settings, wc_path)?
} else {
Workspace::init_internal_git(&settings, wc_path)?
};
let workspace_command = command.for_workable_repo(ui, workspace, repo)?;
maybe_add_gitignore(&workspace_command)?;
Ok(workspace_command)
}
fn configure_remote(
ui: &Ui,
command: &CommandHelper,
mut workspace_command: WorkspaceCommandHelper,
remote_name: &RemoteName,
source: &str,
fetch_tags: FetchTagsMode,
bookmark_expr: &StringExpression,
) -> Result<WorkspaceCommandHelper, CommandError> {
let mut tx = workspace_command.start_transaction();
git::add_remote(
tx.repo_mut(),
remote_name,
source,
None,
fetch_tags.as_fetch_tags(),
bookmark_expr,
)?;
tx.finish(ui, format!("add git remote {}", remote_name.as_symbol()))?;
// Reload workspace to apply new remote configuration to
// gix::ThreadSafeRepository behind the store.
let workspace = command.load_workspace_at(
workspace_command.workspace_root(),
workspace_command.settings(),
)?;
let op = workspace
.repo_loader()
.load_operation(workspace_command.repo().op_id())?;
let repo = workspace.repo_loader().load_at(&op)?;
command.for_workable_repo(ui, workspace, repo)
}
fn fetch_new_remote(
ui: &Ui,
workspace_command: &mut WorkspaceCommandHelper,
remote_name: &RemoteName,
bookmark_expr: &StringExpression,
depth: Option<NonZeroU32>,
fetch_tags: Option<FetchTagsMode>,
) -> Result<(Option<RefNameBuf>, bool), CommandError> {
writeln!(
ui.status(),
r#"Fetching into new repo in "{}""#,
workspace_command.workspace_root().display()
)?;
let settings = workspace_command.settings();
let git_settings = GitSettings::from_settings(settings)?;
let remote_settings = settings.remote_settings()?;
let subprocess_options = git_settings.to_subprocess_options();
let import_options = load_git_import_options(ui, &git_settings, &remote_settings)?;
let should_track_default = settings.get_bool("git.track-default-bookmark-on-clone")?;
let mut tx = workspace_command.start_transaction();
let (default_branch, import_stats) = {
let mut git_fetch = GitFetch::new(tx.repo_mut(), subprocess_options, &import_options)?;
let fetch_refspecs = expand_fetch_refspecs(remote_name, bookmark_expr.clone())?;
with_remote_git_callbacks(ui, |cb| {
git_fetch.fetch(
remote_name,
fetch_refspecs,
cb,
depth,
match fetch_tags {
// If not explicitly specified on the CLI, override the remote
// configuration and fetch all tags by default since this is
// the Git default behavior.
None => Some(FetchTagsOverride::AllTags),
// Technically by this point the remote should already be
// configured based on the CLI parameters so we shouldn't *need*
// to apply an override here but all the cases are expanded here
// for clarity.
Some(FetchTagsMode::All) => Some(FetchTagsOverride::AllTags),
Some(FetchTagsMode::None) => Some(FetchTagsOverride::NoTags),
Some(FetchTagsMode::Included) => None,
},
)
})?;
let import_stats = git_fetch.import_refs()?;
let default_branch = git_fetch.get_default_branch(remote_name)?;
(default_branch, import_stats)
};
// Warn unmatched exact patterns, and record the first matching branch as
// the working branch. If there are no matching exact patterns, use the
// default branch of the remote.
let mut missing_branches = vec![];
let mut working_branch = None;
let bookmark_matcher = bookmark_expr.to_matcher();
let exact_bookmarks = bookmark_expr
.exact_strings()
.filter(|name| bookmark_matcher.is_match(name)) // exclude negative patterns
.map(RefName::new);
for name in exact_bookmarks {
let symbol = name.to_remote_symbol(remote_name);
if tx.repo().view().get_remote_bookmark(symbol).is_absent() {
missing_branches.push(name);
} else if working_branch.is_none() {
working_branch = Some(name);
}
}
if working_branch.is_none() {
working_branch = default_branch.as_deref().filter(|name| {
let symbol = name.to_remote_symbol(remote_name);
tx.repo().view().get_remote_bookmark(symbol).is_present()
});
}
if !missing_branches.is_empty() {
writeln!(
ui.warning_default(),
"No matching branches found on remote: {}",
missing_branches
.iter()
.map(|name| name.as_symbol())
.join(", ")
)?;
}
let working_is_default = working_branch == default_branch.as_deref();
if let Some(name) = working_branch
&& working_is_default
&& should_track_default
{
// For convenience, create local bookmark as Git would do.
let remote_symbol = name.to_remote_symbol(remote_name);
tx.repo_mut().track_remote_bookmark(remote_symbol)?;
}
print_git_import_stats(ui, tx.repo(), &import_stats, true)?;
if git_settings.auto_local_bookmark && !should_track_default {
writeln!(
ui.hint_default(),
"`git.track-default-bookmark-on-clone=false` has no effect if \
`git.auto-local-bookmark` is enabled."
)?;
}
tx.finish(ui, "fetch from git remote into empty repo")?;
Ok((working_branch.map(ToOwned::to_owned), working_is_default))
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/mod.rs | cli/src/commands/git/mod.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod clone;
mod colocation;
mod export;
mod fetch;
mod import;
mod init;
mod push;
mod remote;
mod root;
use std::io::Write as _;
use std::path::Path;
use clap::Subcommand;
use clap::ValueEnum;
use jj_lib::config::ConfigFile;
use jj_lib::config::ConfigSource;
use jj_lib::git;
use jj_lib::git::UnexpectedGitBackendError;
use jj_lib::ref_name::RemoteNameBuf;
use jj_lib::ref_name::RemoteRefSymbol;
use jj_lib::store::Store;
use self::clone::GitCloneArgs;
use self::clone::cmd_git_clone;
use self::colocation::GitColocationCommand;
use self::colocation::cmd_git_colocation;
use self::export::GitExportArgs;
use self::export::cmd_git_export;
use self::fetch::GitFetchArgs;
use self::fetch::cmd_git_fetch;
use self::import::GitImportArgs;
use self::import::cmd_git_import;
use self::init::GitInitArgs;
use self::init::cmd_git_init;
use self::push::GitPushArgs;
use self::push::cmd_git_push;
pub use self::push::is_push_operation;
use self::remote::RemoteCommand;
use self::remote::cmd_git_remote;
use self::root::GitRootArgs;
use self::root::cmd_git_root;
use crate::cli_util::CommandHelper;
use crate::cli_util::WorkspaceCommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error_with_message;
use crate::ui::Ui;
/// Commands for working with Git remotes and the underlying Git repo
///
/// See this [comparison], including a [table of commands].
///
/// [comparison]:
/// https://docs.jj-vcs.dev/latest/git-comparison/.
///
/// [table of commands]:
/// https://docs.jj-vcs.dev/latest/git-command-table
#[derive(Subcommand, Clone, Debug)]
pub enum GitCommand {
Clone(GitCloneArgs),
#[command(subcommand)]
Colocation(GitColocationCommand),
Export(GitExportArgs),
Fetch(GitFetchArgs),
Import(GitImportArgs),
Init(GitInitArgs),
Push(GitPushArgs),
#[command(subcommand)]
Remote(RemoteCommand),
Root(GitRootArgs),
}
pub fn cmd_git(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &GitCommand,
) -> Result<(), CommandError> {
match subcommand {
GitCommand::Clone(args) => cmd_git_clone(ui, command, args),
GitCommand::Colocation(subcommand) => cmd_git_colocation(ui, command, subcommand),
GitCommand::Export(args) => cmd_git_export(ui, command, args),
GitCommand::Fetch(args) => cmd_git_fetch(ui, command, args),
GitCommand::Import(args) => cmd_git_import(ui, command, args),
GitCommand::Init(args) => cmd_git_init(ui, command, args),
GitCommand::Push(args) => cmd_git_push(ui, command, args),
GitCommand::Remote(args) => cmd_git_remote(ui, command, args),
GitCommand::Root(args) => cmd_git_root(ui, command, args),
}
}
pub fn maybe_add_gitignore(workspace_command: &WorkspaceCommandHelper) -> Result<(), CommandError> {
if workspace_command.working_copy_shared_with_git() {
std::fs::write(
workspace_command
.workspace_root()
.join(".jj")
.join(".gitignore"),
"/*\n",
)
.map_err(|e| user_error_with_message("Failed to write .jj/.gitignore file", e))
} else {
Ok(())
}
}
fn get_single_remote(store: &Store) -> Result<Option<RemoteNameBuf>, UnexpectedGitBackendError> {
let mut names = git::get_all_remote_names(store)?;
Ok(match names.len() {
1 => names.pop(),
_ => None,
})
}
/// Sets repository level `trunk()` alias to the specified remote symbol.
fn write_repository_level_trunk_alias(
ui: &Ui,
repo_path: &Path,
symbol: RemoteRefSymbol<'_>,
) -> Result<(), CommandError> {
let mut file = ConfigFile::load_or_empty(ConfigSource::Repo, repo_path.join("config.toml"))?;
file.set_value(["revset-aliases", "trunk()"], symbol.to_string())
.expect("initial repo config shouldn't have invalid values");
file.save()?;
writeln!(
ui.status(),
"Setting the revset alias `trunk()` to `{symbol}`",
)?;
Ok(())
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum FetchTagsMode {
/// Always fetch all tags
All,
/// Only fetch tags that point to objects that are already being
/// transmitted.
Included,
/// Do not fetch any tags
None,
}
impl FetchTagsMode {
fn as_fetch_tags(&self) -> gix::remote::fetch::Tags {
match self {
Self::All => gix::remote::fetch::Tags::All,
Self::Included => gix::remote::fetch::Tags::Included,
Self::None => gix::remote::fetch::Tags::None,
}
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/init.rs | cli/src/commands/git/init.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io;
use std::io::Write as _;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use itertools::Itertools as _;
use jj_lib::file_util;
use jj_lib::git;
use jj_lib::git::GitRefKind;
use jj_lib::git::GitSettings;
use jj_lib::git::parse_git_ref;
use jj_lib::repo::ReadonlyRepo;
use jj_lib::repo::Repo as _;
use jj_lib::view::View;
use jj_lib::workspace::Workspace;
use super::write_repository_level_trunk_alias;
use crate::cli_util::CommandHelper;
use crate::cli_util::WorkspaceCommandHelper;
use crate::cli_util::start_repo_transaction;
use crate::command_error::CommandError;
use crate::command_error::cli_error;
use crate::command_error::internal_error;
use crate::command_error::user_error_with_hint;
use crate::command_error::user_error_with_message;
use crate::commands::git::maybe_add_gitignore;
use crate::formatter::FormatterExt as _;
use crate::git_util::is_colocated_git_workspace;
use crate::git_util::load_git_import_options;
use crate::git_util::print_git_export_stats;
use crate::git_util::print_git_import_stats;
use crate::ui::Ui;
/// Create a new Git backed repo.
#[derive(clap::Args, Clone, Debug)]
pub struct GitInitArgs {
/// The destination directory where the `jj` repo will be created.
/// If the directory does not exist, it will be created.
/// If no directory is given, the current directory is used.
///
/// By default the `git` repo is under `$destination/.jj`
#[arg(default_value = ".", value_hint = clap::ValueHint::DirPath)]
destination: String,
/// Colocate the Jujutsu repo with the git repo
///
/// Specifies that the `jj` repo should also be a valid `git` repo, allowing
/// the use of both `jj` and `git` commands in the same directory.
///
/// The repository will contain a `.git` dir in the top-level. Regular Git
/// tools will be able to operate on the repo.
///
/// **This is the default**, and this option has no effect, unless the
/// [git.colocate config] is set to `false`.
///
/// This option is mutually exclusive with `--git-repo`.
///
/// [git.colocate config]:
/// https://docs.jj-vcs.dev/latest/config/#default-colocation
#[arg(long, conflicts_with = "git_repo")]
colocate: bool,
/// Disable colocation of the Jujutsu repo with the git repo
///
/// Prevent Git tools that are unaware of `jj` and regular Git commands from
/// operating on the repo. The Git repository that stores most of the repo
/// data will be hidden inside a sub-directory of the `.jj` directory.
///
/// See [colocation docs] for some minor advantages of non-colocated
/// workspaces.
///
/// [colocation docs]:
/// https://docs.jj-vcs.dev/latest/git-compatibility/#colocated-jujutsugit-repos
#[arg(long, conflicts_with = "colocate")]
no_colocate: bool,
/// Specifies a path to an **existing** git repository to be
/// used as the backing git repo for the newly created `jj` repo.
///
/// If the specified `--git-repo` path happens to be the same as
/// the `jj` repo path (both .jj and .git directories are in the
/// same working directory), then both `jj` and `git` commands
/// will work on the same repo. This is called a colocated workspace.
///
/// This option is mutually exclusive with `--colocate`.
#[arg(long, conflicts_with = "colocate", value_hint = clap::ValueHint::DirPath)]
git_repo: Option<String>,
}
pub fn cmd_git_init(
ui: &mut Ui,
command: &CommandHelper,
args: &GitInitArgs,
) -> Result<(), CommandError> {
if command.global_args().ignore_working_copy {
return Err(cli_error("--ignore-working-copy is not respected"));
}
if command.global_args().at_operation.is_some() {
return Err(cli_error("--at-op is not respected"));
}
let cwd = command.cwd();
let wc_path = cwd.join(&args.destination);
let wc_path = file_util::create_or_reuse_dir(&wc_path)
.and_then(|_| dunce::canonicalize(wc_path))
.map_err(|e| user_error_with_message("Failed to create workspace", e))?;
let colocate = if command.settings().get_bool("git.colocate")? {
!args.no_colocate
} else {
args.colocate
};
do_init(ui, command, &wc_path, colocate, args.git_repo.as_deref())?;
let relative_wc_path = file_util::relative_path(cwd, &wc_path);
writeln!(
ui.status(),
r#"Initialized repo in "{}""#,
relative_wc_path.display()
)?;
if colocate {
writeln!(
ui.hint_default(),
r"Running `git clean -xdf` will remove `.jj/`!",
)?;
}
Ok(())
}
fn do_init(
ui: &mut Ui,
command: &CommandHelper,
workspace_root: &Path,
colocate: bool,
git_repo: Option<&str>,
) -> Result<(), CommandError> {
#[derive(Clone, Debug)]
enum GitInitMode {
Colocate,
External(PathBuf),
Internal,
}
let colocated_git_repo_path = workspace_root.join(".git");
let init_mode = if colocate {
if colocated_git_repo_path.exists() {
GitInitMode::External(colocated_git_repo_path)
} else {
GitInitMode::Colocate
}
} else if let Some(path_str) = git_repo {
let mut git_repo_path = command.cwd().join(path_str);
if !git_repo_path.ends_with(".git") {
git_repo_path.push(".git");
// Undo if .git doesn't exist - likely a bare repo.
if !git_repo_path.exists() {
git_repo_path.pop();
}
}
GitInitMode::External(git_repo_path)
} else {
if colocated_git_repo_path.exists() {
return Err(user_error_with_hint(
"Did not create a jj repo because there is an existing Git repo in this directory.",
"To create a repo backed by the existing Git repo, run `jj git init --colocate` \
instead.",
));
}
GitInitMode::Internal
};
let settings = command.settings_for_new_workspace(workspace_root)?;
match &init_mode {
GitInitMode::Colocate => {
let (workspace, repo) = Workspace::init_colocated_git(&settings, workspace_root)?;
let workspace_command = command.for_workable_repo(ui, workspace, repo)?;
maybe_add_gitignore(&workspace_command)?;
}
GitInitMode::External(git_repo_path) => {
let (workspace, repo) =
Workspace::init_external_git(&settings, workspace_root, git_repo_path)?;
// Import refs first so all the reachable commits are indexed in
// chronological order.
let colocated = is_colocated_git_workspace(&workspace, &repo);
let repo = init_git_refs(ui, repo, command.string_args(), colocated)?;
let mut workspace_command = command.for_workable_repo(ui, workspace, repo)?;
maybe_add_gitignore(&workspace_command)?;
workspace_command.maybe_snapshot(ui)?;
maybe_set_repository_level_trunk_alias(ui, &workspace_command)?;
if !workspace_command.working_copy_shared_with_git() {
let mut tx = workspace_command.start_transaction();
jj_lib::git::import_head(tx.repo_mut())?;
if let Some(git_head_id) = tx.repo().view().git_head().as_normal().cloned() {
let git_head_commit = tx.repo().store().get_commit(&git_head_id)?;
tx.check_out(&git_head_commit)?;
}
if tx.repo().has_changes() {
tx.finish(ui, "import git head")?;
}
}
print_trackable_remote_bookmarks(ui, workspace_command.repo().view())?;
}
GitInitMode::Internal => {
Workspace::init_internal_git(&settings, workspace_root)?;
}
}
Ok(())
}
/// Imports branches and tags from the underlying Git repo, exports changes if
/// the repo is colocated.
///
/// This is similar to `WorkspaceCommandHelper::import_git_refs()`, but never
/// moves the Git HEAD to the working copy parent.
fn init_git_refs(
ui: &mut Ui,
repo: Arc<ReadonlyRepo>,
string_args: &[String],
colocated: bool,
) -> Result<Arc<ReadonlyRepo>, CommandError> {
let git_settings = GitSettings::from_settings(repo.settings())?;
let remote_settings = repo.settings().remote_settings()?;
let mut import_options = load_git_import_options(ui, &git_settings, &remote_settings)?;
let mut tx = start_repo_transaction(&repo, string_args);
// There should be no old refs to abandon, but enforce it.
import_options.abandon_unreachable_commits = false;
let stats = git::import_refs(tx.repo_mut(), &import_options)?;
print_git_import_stats(ui, tx.repo(), &stats, false)?;
if !tx.repo().has_changes() {
return Ok(repo);
}
if colocated {
// If git.auto-local-bookmark = true or
// remotes.<name>.auto-track-bookmarks is set, local bookmarks could be
// created for the imported remote branches.
let stats = git::export_refs(tx.repo_mut())?;
print_git_export_stats(ui, &stats)?;
}
let repo = tx.commit("import git refs")?;
writeln!(
ui.status(),
"Done importing changes from the underlying Git repo."
)?;
Ok(repo)
}
// Set repository level `trunk()` alias to the default branch.
// Checks "upstream" first, then "origin" as fallback.
pub fn maybe_set_repository_level_trunk_alias(
ui: &Ui,
workspace_command: &WorkspaceCommandHelper,
) -> Result<(), CommandError> {
let git_repo = git::get_git_repo(workspace_command.repo().store())?;
// Try "upstream" first, then fall back to "origin"
for remote in ["upstream", "origin"] {
let ref_name = format!("refs/remotes/{remote}/HEAD");
if let Some(reference) = git_repo
.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.
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?
let symbol = symbol.name.to_remote_symbol(remote.as_ref());
write_repository_level_trunk_alias(ui, workspace_command.repo_path(), symbol)?;
}
return Ok(());
}
}
Ok(())
}
fn print_trackable_remote_bookmarks(ui: &Ui, view: &View) -> io::Result<()> {
let remote_bookmark_symbols = view
.bookmarks()
.filter(|(_, bookmark_target)| bookmark_target.local_target.is_present())
.flat_map(|(name, bookmark_target)| {
bookmark_target
.remote_refs
.into_iter()
.filter(|&(_, remote_ref)| !remote_ref.is_tracked())
.map(move |(remote, _)| name.to_remote_symbol(remote))
})
.collect_vec();
if remote_bookmark_symbols.is_empty() {
return Ok(());
}
if let Some(mut formatter) = ui.status_formatter() {
writeln!(
formatter.labeled("hint").with_heading("Hint: "),
"The following remote bookmarks aren't associated with the existing local bookmarks:"
)?;
for symbol in &remote_bookmark_symbols {
write!(formatter, " ")?;
writeln!(formatter.labeled("bookmark"), "{symbol}")?;
}
writeln!(
formatter.labeled("hint").with_heading("Hint: "),
"Run the following command to keep local bookmarks updated on future pulls:"
)?;
for symbol in &remote_bookmark_symbols {
writeln!(
formatter.labeled("hint"),
" jj bookmark track {name} --remote={remote}",
name = symbol.name.as_symbol(),
remote = symbol.remote.as_symbol()
)?;
}
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/colocation.rs | cli/src/commands/git/colocation.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::ErrorKind;
use std::io::Write as _;
use itertools::Itertools as _;
use jj_lib::commit::Commit;
use jj_lib::file_util::IoResultExt as _;
use jj_lib::git;
use jj_lib::op_store::RefTarget;
use jj_lib::repo::Repo as _;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::command_error::user_error_with_message;
use crate::commands::git::maybe_add_gitignore;
use crate::git_util::is_colocated_git_workspace;
use crate::ui::Ui;
/// Show the current colocation status
#[derive(clap::Args, Clone, Debug)]
pub struct GitColocationStatusArgs {}
/// Convert into a colocated Jujutsu/Git repository
///
/// This moves the underlying Git repository that is found inside the .jj
/// directory to the root of the Jujutsu workspace. This allows you to
/// use Git commands directly in the Jujutsu workspace.
#[derive(clap::Args, Clone, Debug)]
pub struct GitColocationEnableArgs {}
/// Convert into a non-colocated Jujutsu/Git repository
///
/// This moves the Git repository that is at the root of the Jujutsu
/// workspace into the .jj directory. Once this is done you will no longer
/// be able to use Git commands directly in the Jujutsu workspace.
#[derive(clap::Args, Clone, Debug)]
pub struct GitColocationDisableArgs {}
/// Manage Jujutsu repository colocation with Git
#[derive(clap::Subcommand, Clone, Debug)]
pub enum GitColocationCommand {
Disable(GitColocationDisableArgs),
Enable(GitColocationEnableArgs),
Status(GitColocationStatusArgs),
}
pub fn cmd_git_colocation(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &GitColocationCommand,
) -> Result<(), CommandError> {
match subcommand {
GitColocationCommand::Disable(args) => cmd_git_colocation_disable(ui, command, args),
GitColocationCommand::Enable(args) => cmd_git_colocation_enable(ui, command, args),
GitColocationCommand::Status(args) => cmd_git_colocation_status(ui, command, args),
}
}
/// Check that the repository supports colocation commands
/// which means that the repo is backed by git, is not
/// already colocated, and is a main workspace
fn workspace_supports_git_colocation_commands(
workspace_command: &crate::cli_util::WorkspaceCommandHelper,
) -> Result<(), CommandError> {
// Check if backend is Git (will show an error otherwise)
git::get_git_backend(workspace_command.repo().store())?;
// Ensure that this is the main workspace
let repo_dir = workspace_command.workspace_root().join(".jj").join("repo");
if repo_dir.is_file() {
return Err(user_error(
"This command cannot be used in a non-main Jujutsu workspace",
));
}
Ok(())
}
fn cmd_git_colocation_status(
ui: &mut Ui,
command: &CommandHelper,
_args: &GitColocationStatusArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
// Make sure that the workspace supports git colocation commands
workspace_supports_git_colocation_commands(&workspace_command)?;
let repo = workspace_command.repo();
let is_colocated = is_colocated_git_workspace(workspace_command.workspace(), repo);
let git_head = repo.view().git_head();
if is_colocated {
writeln!(ui.stdout(), "Workspace is currently colocated with Git.")?;
} else {
writeln!(
ui.stdout(),
"Workspace is currently not colocated with Git."
)?;
}
// git_head should be absent in non-colocated workspace, but print the
// actual status so we can debug problems.
writeln!(
ui.stdout(),
"Last imported/exported Git HEAD: {}",
git_head
.as_merge()
.iter()
.map(|maybe_id| match maybe_id {
Some(id) => id.to_string(),
None => "(none)".to_owned(),
})
.join(", ")
)?;
if is_colocated {
writeln!(
ui.hint_default(),
"To disable colocation, run: `jj git colocation disable`"
)?;
} else {
writeln!(
ui.hint_default(),
"To enable colocation, run: `jj git colocation enable`"
)?;
}
Ok(())
}
fn cmd_git_colocation_enable(
ui: &mut Ui,
command: &CommandHelper,
_args: &GitColocationEnableArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
// Make sure that the workspace supports git colocation commands
workspace_supports_git_colocation_commands(&workspace_command)?;
// Then ensure that the workspace is not already colocated before proceeding
if is_colocated_git_workspace(workspace_command.workspace(), workspace_command.repo()) {
writeln!(ui.status(), "Workspace is already colocated with Git.")?;
return Ok(());
}
// 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"))?
.clone();
let workspace_root = workspace_command.workspace_root();
let jj_repo_path = workspace_command.repo_path();
let git_store_path = jj_repo_path.join("store").join("git");
let git_target_path = jj_repo_path.join("store").join("git_target");
let dot_git_path = workspace_root.join(".git");
// Move the git repository from .jj/repo/store/git to .git
std::fs::rename(&git_store_path, &dot_git_path).map_err(|err| match err.kind() {
ErrorKind::AlreadyExists | ErrorKind::DirectoryNotEmpty => {
user_error("A .git directory already exists in the workspace root. Cannot colocate.")
}
_ => user_error_with_message(
"Failed to move Git repository from .jj/repo/store/git to workspace root directory.",
err,
),
})?;
// Update the git_target file to point to the new location of the git repo
let git_target_content = "../../../.git";
std::fs::write(&git_target_path, git_target_content).context(git_target_path)?;
// Then we must make the Git repository non-bare
set_git_repo_bare(&dot_git_path, false)?;
// Reload the workspace command helper to ensure it picks up the changes
let mut workspace_command = reload_workspace_helper(ui, command, workspace_command)?;
// Add a .jj/.gitignore file (if needed) to ensure that the colocated Git
// repository does not track Jujutsu's repository
maybe_add_gitignore(&workspace_command)?;
// Finally, update git HEAD to point to the working-copy commit's parent
let wc_commit = workspace_command.repo().store().get_commit(&wc_commit_id)?;
set_git_head_to_wc_parent(ui, &mut workspace_command, &wc_commit)?;
writeln!(
ui.status(),
"Workspace successfully converted into a colocated Jujutsu/Git workspace."
)?;
Ok(())
}
fn cmd_git_colocation_disable(
ui: &mut Ui,
command: &CommandHelper,
_args: &GitColocationDisableArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
// Make sure that the repository supports git colocation commands
workspace_supports_git_colocation_commands(&workspace_command)?;
// Then ensure that the repo is colocated before proceeding
if !is_colocated_git_workspace(workspace_command.workspace(), workspace_command.repo()) {
writeln!(ui.status(), "Workspace is already not colocated with Git.")?;
return Ok(());
}
let workspace_root = workspace_command.workspace_root();
let dot_jj_path = workspace_root.join(".jj");
let git_store_path = workspace_command.repo_path().join("store").join("git");
let git_target_path = workspace_command
.repo_path()
.join("store")
.join("git_target");
let dot_git_path = workspace_root.join(".git");
let jj_gitignore_path = dot_jj_path.join(".gitignore");
// Move the Git repository from .git into .jj/repo/store/git
std::fs::rename(&dot_git_path, &git_store_path).map_err(|e| {
user_error_with_message("Failed to move Git repository to .jj/repo/store/git", e)
})?;
// Make the Git repository bare
set_git_repo_bare(&git_store_path, true)?;
// Update the git_target file to point to the internal git store
let git_target_content = "git";
std::fs::write(&git_target_path, git_target_content).context(&git_target_path)?;
// Remove the .jj/.gitignore file if it exists
std::fs::remove_file(&jj_gitignore_path).ok();
// Reload the workspace command helper to ensure it picks up the changes
let mut workspace_command = reload_workspace_helper(ui, command, workspace_command)?;
// And finally, remove the git HEAD reference
remove_git_head(ui, &mut workspace_command)?;
writeln!(
ui.status(),
"Workspace successfully converted into a non-colocated Jujutsu/Git workspace."
)?;
Ok(())
}
/// Set the Git repository at `path` to be bare or non-bare
fn set_git_repo_bare(path: &std::path::Path, bare: bool) -> Result<(), CommandError> {
let bare_str = if bare { "true" } else { "false" };
let config_path = path.join("config");
let mut config_file =
gix::config::File::from_path_no_includes(config_path.clone(), gix::config::Source::Local)
.map_err(|err| user_error_with_message("Failed to open Git config file.", err))?;
config_file
.set_raw_value(&"core.bare", bare_str)
.map_err(|err| {
user_error_with_message(
format!("Failed to set core.bare to {bare_str} in Git config."),
err,
)
})?;
git::save_git_config(&config_file).map_err(|err| {
user_error_with_message(
format!(
"Failed to write to Git config file at {}.",
config_path.display()
),
err,
)
})?;
Ok(())
}
/// Set the git HEAD to the working copy commit's parent
fn set_git_head_to_wc_parent(
ui: &mut Ui,
workspace_command: &mut crate::cli_util::WorkspaceCommandHelper,
wc_commit: &Commit,
) -> Result<(), CommandError> {
let mut tx = workspace_command.start_transaction();
git::reset_head(tx.repo_mut(), wc_commit)?;
if tx.repo().has_changes() {
tx.finish(ui, "set git head to working copy parent")?;
}
Ok(())
}
/// Remove the git HEAD reference
fn remove_git_head(
ui: &mut Ui,
workspace_command: &mut crate::cli_util::WorkspaceCommandHelper,
) -> Result<(), CommandError> {
let mut tx = workspace_command.start_transaction();
tx.repo_mut().set_git_head_target(RefTarget::absent());
if tx.repo().has_changes() {
tx.finish(ui, "remove git head reference")?;
}
Ok(())
}
/// Gets an up to date workspace helper to pick up changes made to the repo
fn reload_workspace_helper(
ui: &mut Ui,
command: &CommandHelper,
workspace_command: crate::cli_util::WorkspaceCommandHelper,
) -> Result<crate::cli_util::WorkspaceCommandHelper, CommandError> {
let workspace = command.load_workspace_at(
workspace_command.workspace_root(),
workspace_command.settings(),
)?;
let op = workspace
.repo_loader()
.load_operation(workspace_command.repo().op_id())?;
let repo = workspace.repo_loader().load_at(&op)?;
let workspace_command = command.for_workable_repo(ui, workspace, repo)?;
Ok(workspace_command)
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/export.rs | cli/src/commands/git/export.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use jj_lib::git;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::git_util::print_git_export_stats;
use crate::ui::Ui;
/// Update the underlying Git repo with changes made in the repo
///
/// There is no need to run this command if you're in colocated workspace
/// because the export happens automatically there.
#[derive(clap::Args, Clone, Debug)]
pub struct GitExportArgs {}
pub fn cmd_git_export(
ui: &mut Ui,
command: &CommandHelper,
_args: &GitExportArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let mut tx = workspace_command.start_transaction();
let stats = git::export_refs(tx.repo_mut())?;
tx.finish(ui, "export git refs")?;
print_git_export_stats(ui, &stats)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/import.rs | cli/src/commands/git/import.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use jj_lib::git;
use jj_lib::git::GitSettings;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::git_util::load_git_import_options;
use crate::git_util::print_git_import_stats;
use crate::ui::Ui;
/// Update repo with changes made in the underlying Git repo
///
/// If a working-copy commit gets abandoned, it will be given a new, empty
/// commit. This is true in general; it is not specific to this command.
///
/// There is no need to run this command if you're in colocated workspace
/// because the import happens automatically there.
#[derive(clap::Args, Clone, Debug)]
pub struct GitImportArgs {}
pub fn cmd_git_import(
ui: &mut Ui,
command: &CommandHelper,
_args: &GitImportArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let git_settings = GitSettings::from_settings(workspace_command.settings())?;
let remote_settings = workspace_command.settings().remote_settings()?;
let import_options = load_git_import_options(ui, &git_settings, &remote_settings)?;
let mut tx = workspace_command.start_transaction();
// In non-colocated workspace, Git HEAD will never be moved internally by jj.
// That's why cmd_git_export() doesn't export the HEAD ref.
git::import_head(tx.repo_mut())?;
let stats = git::import_refs(tx.repo_mut(), &import_options)?;
print_git_import_stats(ui, tx.repo(), &stats, true)?;
tx.finish(ui, "import git refs")?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/remote/rename.rs | cli/src/commands/git/remote/rename.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use jj_lib::git;
use jj_lib::ref_name::RemoteNameBuf;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::complete;
use crate::ui::Ui;
/// Rename a Git remote
#[derive(clap::Args, Clone, Debug)]
pub struct GitRemoteRenameArgs {
/// The name of an existing remote
#[arg(add = ArgValueCandidates::new(complete::git_remotes))]
old: RemoteNameBuf,
/// The desired name for `old`
new: RemoteNameBuf,
}
pub fn cmd_git_remote_rename(
ui: &mut Ui,
command: &CommandHelper,
args: &GitRemoteRenameArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let mut tx = workspace_command.start_transaction();
git::rename_remote(tx.repo_mut(), &args.old, &args.new)?;
if tx.repo().has_changes() {
tx.finish(
ui,
format!(
"rename git remote {old} to {new}",
old = args.old.as_symbol(),
new = args.new.as_symbol()
),
)
} else {
Ok(()) // Do not print "Nothing changed."
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/remote/list.rs | cli/src/commands/git/remote/list.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::Write as _;
use bstr::BString;
use gix::Remote;
use jj_lib::git;
use jj_lib::repo::Repo as _;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error_with_message;
use crate::ui::Ui;
/// List Git remotes
#[derive(clap::Args, Clone, Debug)]
pub struct GitRemoteListArgs {}
pub fn cmd_git_remote_list(
ui: &mut Ui,
command: &CommandHelper,
_args: &GitRemoteListArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let git_repo = git::get_git_repo(workspace_command.repo().store())?;
for remote_name in git_repo.remote_names() {
let remote = match git_repo.try_find_remote(&*remote_name) {
Some(Ok(remote)) => remote,
Some(Err(err)) => {
return Err(user_error_with_message(
format!("Failed to load configured remote {remote_name}"),
err,
));
}
None => continue, // ignore empty [remote "<name>"] section
};
let fetch_url = get_url(&remote, gix::remote::Direction::Fetch);
let push_url = get_url(&remote, gix::remote::Direction::Push);
if fetch_url == push_url {
writeln!(ui.stdout(), "{remote_name} {fetch_url}")?;
} else {
writeln!(ui.stdout(), "{remote_name} {fetch_url} (push: {push_url})")?;
}
}
Ok(())
}
fn get_url(remote: &Remote, direction: gix::remote::Direction) -> BString {
remote
.url(direction)
.map(|url| url.to_bstring())
.unwrap_or_else(|| "<no URL>".into())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/remote/mod.rs | cli/src/commands/git/remote/mod.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod add;
mod list;
mod remove;
mod rename;
mod set_url;
use clap::Subcommand;
use self::add::GitRemoteAddArgs;
use self::add::cmd_git_remote_add;
use self::list::GitRemoteListArgs;
use self::list::cmd_git_remote_list;
use self::remove::GitRemoteRemoveArgs;
use self::remove::cmd_git_remote_remove;
use self::rename::GitRemoteRenameArgs;
use self::rename::cmd_git_remote_rename;
use self::set_url::GitRemoteSetUrlArgs;
use self::set_url::cmd_git_remote_set_url;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// Manage Git remotes
///
/// The Git repo will be a bare git repo stored inside the `.jj/` directory.
#[derive(Subcommand, Clone, Debug)]
pub enum RemoteCommand {
Add(GitRemoteAddArgs),
List(GitRemoteListArgs),
Remove(GitRemoteRemoveArgs),
Rename(GitRemoteRenameArgs),
SetUrl(GitRemoteSetUrlArgs),
}
pub fn cmd_git_remote(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &RemoteCommand,
) -> Result<(), CommandError> {
match subcommand {
RemoteCommand::Add(args) => cmd_git_remote_add(ui, command, args),
RemoteCommand::List(args) => cmd_git_remote_list(ui, command, args),
RemoteCommand::Remove(args) => cmd_git_remote_remove(ui, command, args),
RemoteCommand::Rename(args) => cmd_git_remote_rename(ui, command, args),
RemoteCommand::SetUrl(args) => cmd_git_remote_set_url(ui, command, args),
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/remote/set_url.rs | cli/src/commands/git/remote/set_url.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use jj_lib::git;
use jj_lib::ref_name::RemoteNameBuf;
use jj_lib::repo::Repo as _;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::complete;
use crate::git_util::absolute_git_url;
use crate::ui::Ui;
/// Set the URL of a Git remote
#[derive(clap::Args, Clone, Debug)]
pub struct GitRemoteSetUrlArgs {
/// The remote's name
#[arg(add = ArgValueCandidates::new(complete::git_remotes))]
remote: RemoteNameBuf,
/// The URL or path to fetch from
///
/// This is a short form, equivalent to using the explicit --fetch.
///
/// Local path will be resolved to absolute form.
#[arg(value_hint = clap::ValueHint::Url)]
url: Option<String>,
/// The URL or path to push to
///
/// Local path will be resolved to absolute form.
#[arg(long, value_hint = clap::ValueHint::Url)]
push: Option<String>,
/// The URL or path to fetch from
///
/// Local path will be resolved to absolute form.
#[arg(long, value_hint = clap::ValueHint::Url, conflicts_with = "url")]
fetch: Option<String>,
}
pub fn cmd_git_remote_set_url(
ui: &mut Ui,
command: &CommandHelper,
args: &GitRemoteSetUrlArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let process_url = |url: Option<&String>| {
url.map(|url| absolute_git_url(command.cwd(), url))
.transpose()
};
let fetch_url = process_url(args.url.as_ref().or(args.fetch.as_ref()))?;
let push_url = process_url(args.push.as_ref())?;
git::set_remote_urls(
workspace_command.repo().store(),
&args.remote,
fetch_url.as_deref(),
push_url.as_deref(),
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/remote/add.rs | cli/src/commands/git/remote/add.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use jj_lib::git;
use jj_lib::ref_name::RemoteNameBuf;
use jj_lib::str_util::StringExpression;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::commands::git::FetchTagsMode;
use crate::git_util::absolute_git_url;
use crate::ui::Ui;
/// Add a Git remote
#[derive(clap::Args, Clone, Debug)]
pub struct GitRemoteAddArgs {
/// The remote's name
remote: RemoteNameBuf,
/// The remote's URL or path
///
/// Local path will be resolved to absolute form.
#[arg(value_hint = clap::ValueHint::Url)]
url: String,
/// Configure when to fetch tags
#[arg(long, value_enum, default_value_t = FetchTagsMode::Included)]
fetch_tags: FetchTagsMode,
/// The URL used for push
///
/// Local path will be resolved to absolute form
#[arg(long, value_hint = clap::ValueHint::Url)]
push_url: Option<String>,
}
pub fn cmd_git_remote_add(
ui: &mut Ui,
command: &CommandHelper,
args: &GitRemoteAddArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let url = absolute_git_url(command.cwd(), &args.url)?;
let push_url = args
.push_url
.as_deref()
.map(|url| absolute_git_url(command.cwd(), url))
.transpose()?;
let mut tx = workspace_command.start_transaction();
let bookmark_expr = StringExpression::all(); // TODO: add command arg?
git::add_remote(
tx.repo_mut(),
&args.remote,
&url,
push_url.as_deref(),
args.fetch_tags.as_fetch_tags(),
&bookmark_expr,
)?;
tx.finish(ui, format!("add git remote {}", args.remote.as_symbol()))?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/git/remote/remove.rs | cli/src/commands/git/remote/remove.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use jj_lib::git;
use jj_lib::ref_name::RemoteNameBuf;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::complete;
use crate::ui::Ui;
/// Remove a Git remote and forget its bookmarks
#[derive(clap::Args, Clone, Debug)]
pub struct GitRemoteRemoveArgs {
/// The remote's name
#[arg(add = ArgValueCandidates::new(complete::git_remotes))]
remote: RemoteNameBuf,
}
pub fn cmd_git_remote_remove(
ui: &mut Ui,
command: &CommandHelper,
args: &GitRemoteRemoveArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let mut tx = workspace_command.start_transaction();
git::remove_remote(tx.repo_mut(), &args.remote)?;
if tx.repo().has_changes() {
tx.finish(ui, format!("remove git remote {}", args.remote.as_symbol()))
} else {
// Do not print "Nothing changed." for the remote named "git".
Ok(())
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/move.rs | cli/src/commands/bookmark/move.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use clap_complete::ArgValueCompleter;
use itertools::Itertools as _;
use jj_lib::iter_util::fallible_any;
use jj_lib::iter_util::fallible_find;
use jj_lib::object_id::ObjectId as _;
use jj_lib::op_store::RefTarget;
use jj_lib::str_util::StringExpression;
use super::is_fast_forward;
use super::warn_unmatched_local_bookmarks;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::command_error::CommandError;
use crate::command_error::user_error_with_hint;
use crate::complete;
use crate::revset_util::parse_union_name_patterns;
use crate::ui::Ui;
/// Move existing bookmarks to target revision
///
/// If bookmark names are given, the specified bookmarks will be updated to
/// point to the target revision.
///
/// If `--from` options are given, bookmarks currently pointing to the
/// specified revisions will be updated. The bookmarks can also be filtered by
/// names.
///
/// Example: pull up the nearest bookmarks to the working-copy parent
///
/// $ jj bookmark move --from 'heads(::@- & bookmarks())' --to @-
#[derive(clap::Args, Clone, Debug)]
#[command(group(clap::ArgGroup::new("source").multiple(true).required(true)))]
pub struct BookmarkMoveArgs {
/// Move bookmarks matching the given name patterns
///
/// By default, the specified pattern matches bookmark names with glob
/// syntax. You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(group = "source")]
#[arg(add = ArgValueCandidates::new(complete::local_bookmarks))]
names: Option<Vec<String>>,
/// Move bookmarks from the given revisions
#[arg(long, short, group = "source", value_name = "REVSETS")]
#[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
from: Vec<RevisionArg>,
/// Move bookmarks to this revision
#[arg(long, short, default_value = "@", value_name = "REVSET")]
#[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
to: RevisionArg,
/// Allow moving bookmarks backwards or sideways
#[arg(long, short = 'B')]
allow_backwards: bool,
}
pub fn cmd_bookmark_move(
ui: &mut Ui,
command: &CommandHelper,
args: &BookmarkMoveArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo().clone();
let target_commit = workspace_command.resolve_single_rev(ui, &args.to)?;
let matched_bookmarks = {
let is_source_ref: Box<dyn Fn(&RefTarget) -> _> = if !args.from.is_empty() {
let is_source_commit = workspace_command
.parse_union_revsets(ui, &args.from)?
.evaluate()?
.containing_fn();
Box::new(move |target| fallible_any(target.added_ids(), &is_source_commit))
} else {
Box::new(|_| Ok(true))
};
let name_expr = match &args.names {
Some(texts) => parse_union_name_patterns(ui, texts)?,
None => StringExpression::all(),
};
let name_matcher = name_expr.to_matcher();
let mut bookmarks: Vec<_> = repo
.view()
.local_bookmarks_matching(&name_matcher)
.filter_map(|(name, target)| {
is_source_ref(target)
.map(|matched| matched.then_some((name, target)))
.transpose()
})
.try_collect()?;
warn_unmatched_local_bookmarks(ui, repo.view(), &name_expr)?;
// Noop matches aren't error, but should be excluded from stats.
bookmarks.retain(|(_, old_target)| old_target.as_normal() != Some(target_commit.id()));
bookmarks
};
if matched_bookmarks.is_empty() {
writeln!(ui.status(), "No bookmarks to update.")?;
return Ok(());
}
if !args.allow_backwards
&& let Some((name, _)) = fallible_find(
matched_bookmarks.iter(),
|(_, old_target)| -> Result<_, CommandError> {
let is_ff = is_fast_forward(repo.as_ref(), old_target, target_commit.id())?;
Ok(!is_ff)
},
)?
{
return Err(user_error_with_hint(
format!(
"Refusing to move bookmark backwards or sideways: {name}",
name = name.as_symbol()
),
"Use --allow-backwards to allow it.",
));
}
if target_commit.is_discardable(repo.as_ref())? {
writeln!(ui.warning_default(), "Target revision is empty.")?;
}
let mut tx = workspace_command.start_transaction();
for (name, _) in &matched_bookmarks {
tx.repo_mut()
.set_local_bookmark_target(name, RefTarget::normal(target_commit.id().clone()));
}
if let Some(mut formatter) = ui.status_formatter() {
write!(formatter, "Moved {} bookmarks to ", matched_bookmarks.len())?;
tx.write_commit_summary(formatter.as_mut(), &target_commit)?;
writeln!(formatter)?;
}
if matched_bookmarks.len() > 1 && args.names.is_none() {
writeln!(
ui.hint_default(),
"Specify bookmark by name to update just one of the bookmarks."
)?;
}
tx.finish(
ui,
format!(
"point bookmark {names} to commit {id}",
names = matched_bookmarks
.iter()
.map(|(name, _)| name.as_symbol())
.join(", "),
id = target_commit.id().hex()
),
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/untrack.rs | cli/src/commands/bookmark/untrack.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use itertools::Itertools as _;
use jj_lib::repo::Repo as _;
use jj_lib::str_util::StringExpression;
use super::find_trackable_remote_bookmarks;
use super::trackable_remote_bookmarks_matching;
use super::warn_unmatched_local_or_remote_bookmarks;
use super::warn_unmatched_remotes;
use crate::cli_util::CommandHelper;
use crate::cli_util::RemoteBookmarkNamePattern;
use crate::cli_util::default_ignored_remote_name;
use crate::command_error::CommandError;
use crate::command_error::cli_error;
use crate::complete;
use crate::revset_util::parse_union_name_patterns;
use crate::ui::Ui;
/// Stop tracking given remote bookmarks
///
/// A non-tracking remote bookmark is just a pointer to the last-fetched remote
/// bookmark. It won't be imported as a local bookmark on future pulls.
///
/// If you want to forget a local bookmark while also untracking the
/// corresponding remote bookmarks, use `jj bookmark forget` instead.
#[derive(clap::Args, Clone, Debug)]
pub struct BookmarkUntrackArgs {
/// Bookmark names to untrack
///
/// By default, the specified pattern matches bookmark names with glob
/// syntax. You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(required = true, value_name = "BOOKMARK")]
#[arg(add = ArgValueCandidates::new(complete::tracked_bookmarks))]
names: Vec<String>,
/// Remote names to untrack
///
/// By default, the specified pattern matches remote names with glob syntax.
/// You can also use other [string pattern syntax].
///
/// If no remote names are given, all remote bookmarks matching the bookmark
/// names will be untracked.
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(long = "remote", value_name = "REMOTE")]
remotes: Option<Vec<String>>,
}
pub fn cmd_bookmark_untrack(
ui: &mut Ui,
command: &CommandHelper,
args: &BookmarkUntrackArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo().clone();
let view = repo.view();
let ignored_remote = default_ignored_remote_name(repo.store())
// suppress unmatched remotes warning for default-ignored remote
.filter(|name| view.get_remote_view(name).is_some());
let matched_refs = if args.remotes.is_none() && args.names.iter().all(|s| s.contains('@')) {
// TODO: Delete in jj 0.43+
writeln!(
ui.warning_default(),
"<bookmark>@<remote> syntax is deprecated, use `<bookmark> --remote=<remote>` instead."
)?;
let name_patterns: Vec<RemoteBookmarkNamePattern> = args
.names
.iter()
.map(|s| s.parse())
.try_collect()
.map_err(cli_error)?;
find_trackable_remote_bookmarks(ui, view, &name_patterns)?
} else {
let bookmark_expr = parse_union_name_patterns(ui, &args.names)?;
let remote_expr = match (&args.remotes, ignored_remote) {
(Some(text), _) => parse_union_name_patterns(ui, text)?,
(None, Some(ignored)) => StringExpression::exact(ignored).negated(),
(None, None) => StringExpression::all(),
};
let bookmark_matcher = bookmark_expr.to_matcher();
let remote_matcher = remote_expr.to_matcher();
let matched_refs =
trackable_remote_bookmarks_matching(view, &bookmark_matcher, &remote_matcher).collect();
warn_unmatched_local_or_remote_bookmarks(ui, view, &bookmark_expr)?;
warn_unmatched_remotes(ui, view, &remote_expr)?;
matched_refs
};
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.
writeln!(
ui.warning_default(),
"Git-tracking bookmark cannot be untracked: {symbol}"
)?;
} else if !remote_ref.is_tracked() {
writeln!(
ui.warning_default(),
"Remote bookmark not tracked yet: {symbol}"
)?;
} else {
symbols.push(symbol);
}
}
let mut tx = workspace_command.start_transaction();
for &symbol in &symbols {
tx.repo_mut().untrack_remote_bookmark(symbol);
}
if !symbols.is_empty() {
writeln!(
ui.status(),
"Stopped tracking {} remote bookmarks.",
symbols.len()
)?;
}
tx.finish(
ui,
format!("untrack remote bookmark {}", symbols.iter().join(", ")),
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/track.rs | cli/src/commands/bookmark/track.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::rc::Rc;
use clap_complete::ArgValueCandidates;
use itertools::Itertools as _;
use jj_lib::repo::Repo as _;
use jj_lib::str_util::StringExpression;
use super::find_trackable_remote_bookmarks;
use super::trackable_remote_bookmarks_matching;
use super::warn_unmatched_local_or_remote_bookmarks;
use super::warn_unmatched_remotes;
use crate::cli_util::CommandHelper;
use crate::cli_util::RemoteBookmarkNamePattern;
use crate::cli_util::default_ignored_remote_name;
use crate::command_error::CommandError;
use crate::command_error::cli_error;
use crate::commit_templater::CommitRef;
use crate::complete;
use crate::revset_util::parse_union_name_patterns;
use crate::templater::TemplateRenderer;
use crate::ui::Ui;
/// Start tracking given remote bookmarks
///
/// A tracking remote bookmark will be imported as a local bookmark of the same
/// name. Changes to it will propagate to the existing local bookmark on future
/// pulls.
#[derive(clap::Args, Clone, Debug)]
pub struct BookmarkTrackArgs {
/// Bookmark names to track
///
/// By default, the specified pattern matches bookmark names with glob
/// syntax. You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(required = true, value_name = "BOOKMARK")]
#[arg(add = ArgValueCandidates::new(complete::untracked_bookmarks))]
names: Vec<String>,
/// Remote names to track
///
/// By default, the specified pattern matches remote names with glob syntax.
/// You can also use other [string pattern syntax].
///
/// If no remote names are given, all remote bookmarks matching the bookmark
/// names will be tracked.
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(long = "remote", value_name = "REMOTE")]
remotes: Option<Vec<String>>,
}
pub fn cmd_bookmark_track(
ui: &mut Ui,
command: &CommandHelper,
args: &BookmarkTrackArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo().clone();
let view = repo.view();
let matched_refs = if args.remotes.is_none() && args.names.iter().all(|s| s.contains('@')) {
// TODO: Delete in jj 0.43+
writeln!(
ui.warning_default(),
"<bookmark>@<remote> syntax is deprecated, use `<bookmark> --remote=<remote>` instead."
)?;
let name_patterns: Vec<RemoteBookmarkNamePattern> = args
.names
.iter()
.map(|s| s.parse())
.try_collect()
.map_err(cli_error)?;
find_trackable_remote_bookmarks(ui, view, &name_patterns)?
} else {
let ignored_remote = default_ignored_remote_name(repo.store())
// suppress unmatched remotes warning for default-ignored remote
.filter(|name| view.get_remote_view(name).is_some());
let bookmark_expr = parse_union_name_patterns(ui, &args.names)?;
let remote_expr = match (&args.remotes, ignored_remote) {
(Some(text), _) => parse_union_name_patterns(ui, text)?,
(None, Some(ignored)) => StringExpression::exact(ignored).negated(),
(None, None) => StringExpression::all(),
};
let bookmark_matcher = bookmark_expr.to_matcher();
let remote_matcher = remote_expr.to_matcher();
let matched_refs =
trackable_remote_bookmarks_matching(view, &bookmark_matcher, &remote_matcher).collect();
warn_unmatched_local_or_remote_bookmarks(ui, view, &bookmark_expr)?;
warn_unmatched_remotes(ui, view, &remote_expr)?;
matched_refs
};
let mut symbols = Vec::new();
for (symbol, remote_ref) in matched_refs {
if remote_ref.is_tracked() {
writeln!(
ui.warning_default(),
"Remote bookmark already tracked: {symbol}"
)?;
} else {
symbols.push(symbol);
}
}
let mut tx = workspace_command.start_transaction();
for &symbol in &symbols {
tx.repo_mut().track_remote_bookmark(symbol)?;
}
if !symbols.is_empty() {
writeln!(
ui.status(),
"Started tracking {} remote bookmarks.",
symbols.len()
)?;
}
tx.finish(
ui,
format!("track remote bookmark {}", symbols.iter().join(", ")),
)?;
//show conflicted bookmarks if there are some
if let Some(mut formatter) = ui.status_formatter() {
let template: TemplateRenderer<Rc<CommitRef>> = {
let language = workspace_command.commit_template_language();
let text = workspace_command
.settings()
.get::<String>("templates.bookmark_list")?;
workspace_command
.parse_template(ui, &language, &text)?
.labeled(["bookmark_list"])
};
let mut remote_per_bookmark: HashMap<_, Vec<_>> = HashMap::new();
for symbol in &symbols {
remote_per_bookmark
.entry(symbol.name)
.or_default()
.push(symbol.remote);
}
let bookmarks_to_list =
workspace_command
.repo()
.view()
.bookmarks()
.filter(|(name, target)| {
remote_per_bookmark.contains_key(name) && target.local_target.has_conflict()
});
for (name, bookmark_target) in bookmarks_to_list {
let local_target = bookmark_target.local_target;
let commit_ref = CommitRef::local(
name,
local_target.clone(),
bookmark_target.remote_refs.iter().map(|x| x.1),
);
template.format(&commit_ref, formatter.as_mut())?;
for (remote_name, remote_ref) in bookmark_target.remote_refs {
if remote_per_bookmark[name].contains(&remote_name) {
let commit_ref =
CommitRef::remote(name, remote_name, remote_ref.clone(), local_target);
template.format(&commit_ref, formatter.as_mut())?;
}
}
}
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/rename.rs | cli/src/commands/bookmark/rename.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use clap_complete::ArgValueCandidates;
use itertools::Itertools as _;
use jj_lib::op_store::RefTarget;
use jj_lib::ref_name::RefNameBuf;
use jj_lib::repo::Repo as _;
use jj_lib::str_util::StringExpression;
use jj_lib::str_util::StringMatcher;
use crate::cli_util::CommandHelper;
use crate::cli_util::default_ignored_remote_name;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::complete;
use crate::revset_util;
use crate::ui::Ui;
/// Rename `old` bookmark name to `new` bookmark name
///
/// The new bookmark name points at the same commit as the old bookmark name.
#[derive(clap::Args, Clone, Debug)]
pub struct BookmarkRenameArgs {
/// The old name of the bookmark
#[arg(value_parser = revset_util::parse_bookmark_name)]
#[arg(add = ArgValueCandidates::new(complete::local_bookmarks))]
old: RefNameBuf,
/// The new name of the bookmark
#[arg(value_parser = revset_util::parse_bookmark_name)]
new: RefNameBuf,
}
pub fn cmd_bookmark_rename(
ui: &mut Ui,
command: &CommandHelper,
args: &BookmarkRenameArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let view = workspace_command.repo().view();
let old_bookmark = &args.old;
let ref_target = view.get_local_bookmark(old_bookmark).clone();
if ref_target.is_absent() {
return Err(user_error(format!(
"No such bookmark: {old_bookmark}",
old_bookmark = old_bookmark.as_symbol()
)));
}
let new_bookmark = &args.new;
if view.get_local_bookmark(new_bookmark).is_present() {
return Err(user_error(format!(
"Bookmark already exists: {new_bookmark}",
new_bookmark = new_bookmark.as_symbol()
)));
}
let mut tx = workspace_command.start_transaction();
tx.repo_mut()
.set_local_bookmark_target(new_bookmark, ref_target);
tx.repo_mut()
.set_local_bookmark_target(old_bookmark, RefTarget::absent());
let remote_matcher = match default_ignored_remote_name(tx.repo().store()) {
Some(remote) => StringExpression::exact(remote).negated().to_matcher(),
None => StringMatcher::all(),
};
let mut tracked_present_remote_bookmarks_exist_for_old_bookmark = false;
let old_tracked_remotes = tx
.base_repo()
.view()
.remote_bookmarks_matching(&StringMatcher::exact(old_bookmark), &remote_matcher)
.filter(|(_, remote_ref)| {
if remote_ref.is_tracked() && remote_ref.is_present() {
tracked_present_remote_bookmarks_exist_for_old_bookmark = true;
}
remote_ref.is_tracked()
})
.map(|(symbol, _)| symbol.remote.to_owned())
.collect_vec();
let mut tracked_remote_bookmarks_exist_for_new_bookmark = false;
let existing_untracked_remotes = tx
.base_repo()
.view()
.remote_bookmarks_matching(&StringMatcher::exact(new_bookmark), &remote_matcher)
.filter(|(_, remote_ref)| {
if remote_ref.is_tracked() {
tracked_remote_bookmarks_exist_for_new_bookmark = true;
}
!remote_ref.is_tracked()
})
.map(|(symbol, _)| symbol.remote.to_owned())
.collect::<HashSet<_>>();
// preserve tracking state of old bookmark
for old_remote in old_tracked_remotes {
let new_remote_bookmark = new_bookmark.to_remote_symbol(&old_remote);
if existing_untracked_remotes.contains(new_remote_bookmark.remote) {
writeln!(
ui.warning_default(),
"The renamed bookmark already exists on the remote '{remote}', tracking state was \
dropped.",
remote = new_remote_bookmark.remote.as_symbol(),
)?;
writeln!(
ui.hint_default(),
"To track the existing remote bookmark, run `jj bookmark track {name} \
--remote={remote}`",
name = new_remote_bookmark.name.as_symbol(),
remote = new_remote_bookmark.remote.as_symbol()
)?;
continue;
}
tx.repo_mut().track_remote_bookmark(new_remote_bookmark)?;
}
tx.finish(
ui,
format!(
"rename bookmark {old_bookmark} to {new_bookmark}",
old_bookmark = old_bookmark.as_symbol(),
new_bookmark = new_bookmark.as_symbol()
),
)?;
if tracked_present_remote_bookmarks_exist_for_old_bookmark {
writeln!(
ui.warning_default(),
"Tracked remote bookmarks for bookmark {old_bookmark} were not renamed.",
old_bookmark = old_bookmark.as_symbol(),
)?;
writeln!(
ui.hint_default(),
"To rename the bookmark on the remote, you can `jj git push --bookmark \
{old_bookmark}` first (to delete it on the remote), and then `jj git push --bookmark \
{new_bookmark}`. `jj git push --all --deleted` would also be sufficient.",
old_bookmark = old_bookmark.as_symbol(),
new_bookmark = new_bookmark.as_symbol()
)?;
}
if tracked_remote_bookmarks_exist_for_new_bookmark {
// This isn't an error because bookmark renaming can't be propagated to
// the remote immediately. "rename old new && rename new old" should be
// allowed even if the original old bookmark had tracked remotes.
writeln!(
ui.warning_default(),
"Tracked remote bookmarks for bookmark {new_bookmark} exist.",
new_bookmark = new_bookmark.as_symbol()
)?;
writeln!(
ui.hint_default(),
"Run `jj bookmark untrack {new_bookmark}` to disassociate them.",
new_bookmark = new_bookmark.as_symbol()
)?;
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/list.rs | cli/src/commands/bookmark/list.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::cmp;
use std::collections::HashMap;
use std::collections::HashSet;
use std::rc::Rc;
use std::sync::Arc;
use clap::ValueEnum;
use clap_complete::ArgValueCandidates;
use itertools::Itertools as _;
use jj_lib::backend;
use jj_lib::backend::CommitId;
use jj_lib::config::ConfigValue;
use jj_lib::repo::Repo as _;
use jj_lib::revset::RevsetExpression;
use jj_lib::str_util::StringExpression;
use super::warn_unmatched_local_or_remote_bookmarks;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::cli_util::default_ignored_remote_name;
use crate::command_error::CommandError;
use crate::commit_templater::CommitRef;
use crate::complete;
use crate::revset_util::parse_union_name_patterns;
use crate::templater::TemplateRenderer;
use crate::ui::Ui;
/// List bookmarks and their targets
///
/// By default, a tracking remote bookmark will be included only if its target
/// is different from the local target. A non-tracking remote bookmark won't be
/// listed. For a conflicted bookmark (both local and remote), old target
/// revisions are preceded by a "-" and new target revisions are preceded by a
/// "+".
///
/// See [`jj help -k bookmarks`] for more information.
///
/// [`jj help -k bookmarks`]:
/// https://docs.jj-vcs.dev/latest/bookmarks
#[derive(clap::Args, Clone, Debug)]
pub struct BookmarkListArgs {
/// Show all tracking and non-tracking remote bookmarks including the ones
/// whose targets are synchronized with the local bookmarks
#[arg(long, short, alias = "all")]
all_remotes: bool,
/// Show all tracking and non-tracking remote bookmarks belonging
/// to this remote
///
/// Can be combined with `--tracked` or `--conflicted` to filter the
/// bookmarks shown (can be repeated.)
///
/// By default, the specified pattern matches remote names with glob syntax.
/// You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(long = "remote", value_name = "REMOTE", conflicts_with_all = ["all_remotes"])]
#[arg(add = ArgValueCandidates::new(complete::git_remotes))]
remotes: Option<Vec<String>>,
/// Show remote tracked bookmarks only. Omits local Git-tracking bookmarks
/// by default
#[arg(long, short, conflicts_with_all = ["all_remotes"])]
tracked: bool,
/// Show conflicted bookmarks only
#[arg(long, short, conflicts_with_all = ["all_remotes"])]
conflicted: bool,
/// Show bookmarks whose local name matches
///
/// By default, the specified pattern matches bookmark names with glob
/// syntax. You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(add = ArgValueCandidates::new(complete::bookmarks))]
names: Option<Vec<String>>,
/// Show bookmarks whose local targets are in the given revisions
///
/// Note that `-r deleted_bookmark` will not work since `deleted_bookmark`
/// wouldn't have a local target.
#[arg(long, short, value_name = "REVSETS")]
revisions: Option<Vec<RevisionArg>>,
/// Render each bookmark using the given template
///
/// All 0-argument methods of the [`CommitRef` type] are available as
/// keywords in the template expression. See [`jj help -k templates`]
/// for more information.
///
/// [`CommitRef` type]:
/// https://docs.jj-vcs.dev/latest/templates/#commitref-type
///
/// [`jj help -k templates`]:
/// https://docs.jj-vcs.dev/latest/templates/
#[arg(long, short = 'T')]
#[arg(add = ArgValueCandidates::new(complete::template_aliases))]
template: Option<String>,
/// Sort bookmarks based on the given key (or multiple keys)
///
/// Suffix the key with `-` to sort in descending order of the value (e.g.
/// `--sort name-`). Note that when using multiple keys, the first key is
/// the most significant.
///
/// This defaults to the `ui.bookmark-list-sort-keys` setting.
#[arg(long, value_name = "SORT_KEY", value_enum, value_delimiter = ',')]
sort: Vec<SortKey>,
}
pub fn cmd_bookmark_list(
ui: &mut Ui,
command: &CommandHelper,
args: &BookmarkListArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo();
let view = repo.view();
// Like cmd_git_push(), names and revisions are OR-ed.
let name_expr = match (&args.names, &args.revisions) {
(Some(texts), _) => parse_union_name_patterns(ui, texts)?,
(None, Some(_)) => StringExpression::none(),
(None, None) => StringExpression::all(),
};
let name_matcher = name_expr.to_matcher();
let matched_local_targets: HashSet<_> = if let Some(revisions) = &args.revisions {
// 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.
expression.intersect_with(&RevsetExpression::bookmarks(StringExpression::all()));
expression.evaluate_to_commit_ids()?.try_collect()?
} else {
HashSet::new()
};
let template: TemplateRenderer<Rc<CommitRef>> = {
let language = workspace_command.commit_template_language();
let text = match &args.template {
Some(value) => value.to_owned(),
None => workspace_command
.settings()
.get("templates.bookmark_list")?,
};
workspace_command
.parse_template(ui, &language, &text)?
.labeled(["bookmark_list"])
};
let ignored_tracked_remote = default_ignored_remote_name(repo.store());
let remote_expr = match &args.remotes {
Some(texts) => parse_union_name_patterns(ui, texts)?,
None => StringExpression::all(),
};
let remote_matcher = remote_expr.to_matcher();
let mut bookmark_list_items: Vec<RefListItem> = Vec::new();
let bookmarks_to_list = view
.bookmarks()
.filter(|(name, target)| {
name_matcher.is_match(name.as_str())
|| target
.local_target
.added_ids()
.any(|id| matched_local_targets.contains(id))
})
.filter(|(_, target)| !args.conflicted || target.local_target.has_conflict());
let mut any_conflicts = false;
for (name, bookmark_target) in bookmarks_to_list {
let local_target = bookmark_target.local_target;
any_conflicts |= local_target.has_conflict();
let remote_refs = bookmark_target.remote_refs;
let (mut tracked_remote_refs, untracked_remote_refs) = remote_refs
.iter()
.copied()
.filter(|(remote_name, _)| remote_matcher.is_match(remote_name.as_str()))
.partition::<Vec<_>, _>(|&(_, remote_ref)| remote_ref.is_tracked());
if args.tracked {
tracked_remote_refs.retain(|&(remote, _)| {
ignored_tracked_remote.is_none_or(|ignored| remote != ignored)
});
} else if !args.all_remotes && args.remotes.is_none() {
tracked_remote_refs.retain(|&(_, remote_ref)| remote_ref.target != *local_target);
}
let include_local_only = !args.tracked && args.remotes.is_none();
if include_local_only && local_target.is_present() || !tracked_remote_refs.is_empty() {
let primary = CommitRef::local(
name,
local_target.clone(),
remote_refs.iter().map(|&(_, remote_ref)| remote_ref),
);
let tracked = tracked_remote_refs
.iter()
.map(|&(remote, remote_ref)| {
CommitRef::remote(name, remote, remote_ref.clone(), local_target)
})
.collect();
bookmark_list_items.push(RefListItem { primary, tracked });
}
if !args.tracked && (args.all_remotes || args.remotes.is_some()) {
bookmark_list_items.extend(untracked_remote_refs.iter().map(
|&(remote, remote_ref)| RefListItem {
primary: CommitRef::remote_only(name, remote, remote_ref.target.clone()),
tracked: vec![],
},
));
}
}
let sort_keys = if args.sort.is_empty() {
workspace_command
.settings()
.get_value_with("ui.bookmark-list-sort-keys", parse_sort_keys)?
} else {
args.sort.clone()
};
let store = repo.store();
let mut commits: HashMap<CommitId, Arc<backend::Commit>> = HashMap::new();
if sort_keys.iter().any(|key| key.is_commit_dependant()) {
commits = bookmark_list_items
.iter()
.filter_map(|item| item.primary.target().added_ids().next())
.map(|commit_id| {
store
.get_commit(commit_id)
.map(|commit| (commit_id.clone(), commit.store_commit().clone()))
})
.try_collect()?;
}
sort(&mut bookmark_list_items, &sort_keys, &commits);
ui.request_pager();
let mut formatter = ui.stdout_formatter();
bookmark_list_items
.iter()
.flat_map(|item| itertools::chain([&item.primary], &item.tracked))
.try_for_each(|commit_ref| template.format(commit_ref, formatter.as_mut()))?;
drop(formatter);
warn_unmatched_local_or_remote_bookmarks(ui, view, &name_expr)?;
if any_conflicts {
writeln!(
ui.hint_default(),
"Some bookmarks have conflicts. Use `jj bookmark set <name> -r <rev>` to resolve."
)?;
}
#[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.
let deleted_tracking = bookmark_list_items
.iter()
.filter(|item| item.primary.is_local() && item.primary.is_absent())
.map(|item| {
item.tracked.iter().any(|r| {
let remote = r.remote_name().expect("tracked ref should be remote");
ignored_tracked_remote.is_none_or(|ignored| remote != ignored)
})
})
.max();
match deleted_tracking {
Some(true) => {
writeln!(
ui.hint_default(),
"Bookmarks marked as deleted can be *deleted permanently* on the remote by \
running `jj git push --deleted`. Use `jj bookmark forget` if you don't want \
that."
)?;
}
Some(false) => {
writeln!(
ui.hint_default(),
"Bookmarks marked as deleted will be deleted from the underlying Git repo on \
the next `jj git export`."
)?;
}
None => {}
}
}
Ok(())
}
#[derive(Clone, Debug)]
struct RefListItem {
/// Local bookmark or untracked remote bookmark.
primary: Rc<CommitRef>,
/// Remote bookmarks tracked by the primary (or local) bookmark.
tracked: Vec<Rc<CommitRef>>,
}
/// Sort key for the `--sort` argument option.
#[derive(Copy, Clone, PartialEq, Debug, ValueEnum)]
enum SortKey {
Name,
#[value(name = "name-")]
NameDesc,
AuthorName,
#[value(name = "author-name-")]
AuthorNameDesc,
AuthorEmail,
#[value(name = "author-email-")]
AuthorEmailDesc,
AuthorDate,
#[value(name = "author-date-")]
AuthorDateDesc,
CommitterName,
#[value(name = "committer-name-")]
CommitterNameDesc,
CommitterEmail,
#[value(name = "committer-email-")]
CommitterEmailDesc,
CommitterDate,
#[value(name = "committer-date-")]
CommitterDateDesc,
}
impl SortKey {
fn is_commit_dependant(&self) -> bool {
match self {
Self::Name | Self::NameDesc => false,
Self::AuthorName
| Self::AuthorNameDesc
| Self::AuthorEmail
| Self::AuthorEmailDesc
| Self::AuthorDate
| Self::AuthorDateDesc
| Self::CommitterName
| Self::CommitterNameDesc
| Self::CommitterEmail
| Self::CommitterEmailDesc
| Self::CommitterDate
| Self::CommitterDateDesc => true,
}
}
}
fn parse_sort_keys(value: ConfigValue) -> Result<Vec<SortKey>, String> {
if let Some(array) = value.as_array() {
array
.iter()
.map(|item| {
item.as_str()
.ok_or("Expected sort key as a string".to_owned())
.and_then(|key| SortKey::from_str(key, false))
})
.try_collect()
} else {
Err("Expected an array of sort keys as strings".to_owned())
}
}
fn sort(
bookmark_items: &mut [RefListItem],
sort_keys: &[SortKey],
commits: &HashMap<CommitId, Arc<backend::Commit>>,
) {
let to_commit = |item: &RefListItem| {
let id = item.primary.target().added_ids().next()?;
commits.get(id)
};
// Multi-pass sorting, the first key is most significant.
// Skip first iteration if sort key is `Name`, since bookmarks are already
// sorted by name.
for sort_key in sort_keys
.iter()
.rev()
.skip_while(|key| *key == &SortKey::Name)
{
match sort_key {
SortKey::Name => {
bookmark_items.sort_by_key(|item| {
(
item.primary.name().to_owned(),
item.primary.remote_name().map(|name| name.to_owned()),
)
});
}
SortKey::NameDesc => {
bookmark_items.sort_by_key(|item| {
cmp::Reverse((
item.primary.name().to_owned(),
item.primary.remote_name().map(|name| name.to_owned()),
))
});
}
SortKey::AuthorName => bookmark_items
.sort_by_key(|item| to_commit(item).map(|commit| commit.author.name.as_str())),
SortKey::AuthorNameDesc => bookmark_items.sort_by_key(|item| {
cmp::Reverse(to_commit(item).map(|commit| commit.author.name.as_str()))
}),
SortKey::AuthorEmail => bookmark_items
.sort_by_key(|item| to_commit(item).map(|commit| commit.author.email.as_str())),
SortKey::AuthorEmailDesc => bookmark_items.sort_by_key(|item| {
cmp::Reverse(to_commit(item).map(|commit| commit.author.email.as_str()))
}),
SortKey::AuthorDate => bookmark_items
.sort_by_key(|item| to_commit(item).map(|commit| commit.author.timestamp)),
SortKey::AuthorDateDesc => bookmark_items.sort_by_key(|item| {
cmp::Reverse(to_commit(item).map(|commit| commit.author.timestamp))
}),
SortKey::CommitterName => bookmark_items
.sort_by_key(|item| to_commit(item).map(|commit| commit.committer.name.as_str())),
SortKey::CommitterNameDesc => bookmark_items.sort_by_key(|item| {
cmp::Reverse(to_commit(item).map(|commit| commit.committer.name.as_str()))
}),
SortKey::CommitterEmail => bookmark_items
.sort_by_key(|item| to_commit(item).map(|commit| commit.committer.email.as_str())),
SortKey::CommitterEmailDesc => bookmark_items.sort_by_key(|item| {
cmp::Reverse(to_commit(item).map(|commit| commit.committer.email.as_str()))
}),
SortKey::CommitterDate => bookmark_items
.sort_by_key(|item| to_commit(item).map(|commit| commit.committer.timestamp)),
SortKey::CommitterDateDesc => bookmark_items.sort_by_key(|item| {
cmp::Reverse(to_commit(item).map(|commit| commit.committer.timestamp))
}),
}
}
}
#[cfg(test)]
mod tests {
use jj_lib::backend::ChangeId;
use jj_lib::backend::MillisSinceEpoch;
use jj_lib::backend::Signature;
use jj_lib::backend::Timestamp;
use jj_lib::backend::TreeId;
use jj_lib::merge::Merge;
use jj_lib::op_store::RefTarget;
use super::*;
fn make_backend_commit(author: Signature, committer: Signature) -> Arc<backend::Commit> {
Arc::new(backend::Commit {
parents: vec![],
predecessors: vec![],
root_tree: Merge::resolved(TreeId::new(vec![])),
conflict_labels: Merge::resolved(String::new()),
change_id: ChangeId::new(vec![]),
description: String::new(),
author,
committer,
secure_sig: None,
})
}
fn make_default_signature() -> Signature {
Signature {
name: "Test User".to_owned(),
email: "test.user@g.com".to_owned(),
timestamp: Timestamp {
timestamp: MillisSinceEpoch(0),
tz_offset: 0,
},
}
}
fn commit_id_generator() -> impl FnMut() -> CommitId {
let mut iter = (1_u128..).map(|n| CommitId::new(n.to_le_bytes().into()));
move || iter.next().unwrap()
}
fn commit_ts_generator() -> impl FnMut() -> Timestamp {
// iter starts as 1, 1, 2, ... for test purposes
let mut iter = Some(1_i64).into_iter().chain(1_i64..).map(|ms| Timestamp {
timestamp: MillisSinceEpoch(ms),
tz_offset: 0,
});
move || iter.next().unwrap()
}
// 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();
let names = ["bob", "alice", "eve", "bob", "bob"];
let emails = [
"bob@g.com",
"alice@g.com",
"eve@g.com",
"bob@g.com",
"bob@g.com",
];
let bookmark_names = ["feature", "bug-fix", "chore", "bug-fix", "feature"];
let remote_names = [None, Some("upstream"), None, Some("origin"), Some("origin")];
let deleted = [false, false, false, false, true];
let mut bookmark_items: Vec<RefListItem> = Vec::new();
let mut commits: HashMap<CommitId, Arc<backend::Commit>> = HashMap::new();
for (&name, &email, bookmark_name, remote_name, &is_deleted) in
itertools::izip!(&names, &emails, &bookmark_names, &remote_names, &deleted)
{
let commit_id = new_commit_id();
let mut b_name = "foo";
let mut author = make_default_signature();
let mut committer = make_default_signature();
if sort_keys.contains(&SortKey::Name) || sort_keys.contains(&SortKey::NameDesc) {
b_name = bookmark_name;
}
if sort_keys.contains(&SortKey::AuthorName)
|| sort_keys.contains(&SortKey::AuthorNameDesc)
{
author.name = String::from(name);
}
if sort_keys.contains(&SortKey::AuthorEmail)
|| sort_keys.contains(&SortKey::AuthorEmailDesc)
{
author.email = String::from(email);
}
if sort_keys.contains(&SortKey::AuthorDate)
|| sort_keys.contains(&SortKey::AuthorDateDesc)
{
author.timestamp = new_timestamp();
}
if sort_keys.contains(&SortKey::CommitterName)
|| sort_keys.contains(&SortKey::CommitterNameDesc)
{
committer.name = String::from(name);
}
if sort_keys.contains(&SortKey::CommitterEmail)
|| sort_keys.contains(&SortKey::CommitterEmailDesc)
{
committer.email = String::from(email);
}
if sort_keys.contains(&SortKey::CommitterDate)
|| sort_keys.contains(&SortKey::CommitterDateDesc)
{
committer.timestamp = new_timestamp();
}
if let Some(remote_name) = remote_name {
if is_deleted {
bookmark_items.push(RefListItem {
primary: CommitRef::remote_only(b_name, *remote_name, RefTarget::absent()),
tracked: vec![CommitRef::local_only(
b_name,
RefTarget::normal(commit_id.clone()),
)],
});
} else {
bookmark_items.push(RefListItem {
primary: CommitRef::remote_only(
b_name,
*remote_name,
RefTarget::normal(commit_id.clone()),
),
tracked: vec![],
});
}
} else {
bookmark_items.push(RefListItem {
primary: CommitRef::local_only(b_name, RefTarget::normal(commit_id.clone())),
tracked: vec![],
});
}
commits.insert(commit_id, make_backend_commit(author, committer));
}
// The sort function has an assumption that refs are sorted by name.
// Here we support this assumption.
bookmark_items.sort_by_key(|item| {
(
item.primary.name().to_owned(),
item.primary.remote_name().map(|name| name.to_owned()),
)
});
sort_and_snapshot(&mut bookmark_items, sort_keys, &commits)
}
// Helper function to sort refs and prepare snapshot with relevant information.
fn sort_and_snapshot(
items: &mut [RefListItem],
sort_keys: &[SortKey],
commits: &HashMap<CommitId, Arc<backend::Commit>>,
) -> String {
sort(items, sort_keys, commits);
let to_commit = |item: &RefListItem| {
let id = item.primary.target().added_ids().next()?;
commits.get(id)
};
macro_rules! row_format {
($($args:tt)*) => {
format!("{:<20}{:<16}{:<17}{:<14}{:<16}{:<17}{}", $($args)*)
}
}
let header = row_format!(
"Name",
"AuthorName",
"AuthorEmail",
"AuthorDate",
"CommitterName",
"CommitterEmail",
"CommitterDate"
);
let rows: Vec<String> = items
.iter()
.map(|item| {
let name = [Some(item.primary.name()), item.primary.remote_name()]
.iter()
.flatten()
.join("@");
let commit = to_commit(item);
let author_name = commit
.map(|c| c.author.name.clone())
.unwrap_or_else(|| String::from("-"));
let author_email = commit
.map(|c| c.author.email.clone())
.unwrap_or_else(|| String::from("-"));
let author_date = commit
.map(|c| c.author.timestamp.timestamp.0.to_string())
.unwrap_or_else(|| String::from("-"));
let committer_name = commit
.map(|c| c.committer.name.clone())
.unwrap_or_else(|| String::from("-"));
let committer_email = commit
.map(|c| c.committer.email.clone())
.unwrap_or_else(|| String::from("-"));
let committer_date = commit
.map(|c| c.committer.timestamp.timestamp.0.to_string())
.unwrap_or_else(|| String::from("-"));
row_format!(
name,
author_name,
author_email,
author_date,
committer_name,
committer_email,
committer_date
)
})
.collect();
let mut result = vec![header];
result.extend(rows);
result.join("\n")
}
#[test]
fn test_sort_by_name() {
insta::assert_snapshot!(
prepare_data_sort_and_snapshot(&[SortKey::Name]), @r"
Name AuthorName AuthorEmail AuthorDate CommitterName CommitterEmail CommitterDate
bug-fix@origin Test User test.user@g.com 0 Test User test.user@g.com 0
bug-fix@upstream Test User test.user@g.com 0 Test User test.user@g.com 0
chore Test User test.user@g.com 0 Test User test.user@g.com 0
feature Test User test.user@g.com 0 Test User test.user@g.com 0
feature@origin - - - - - -
");
}
#[test]
fn test_sort_by_name_desc() {
insta::assert_snapshot!(
prepare_data_sort_and_snapshot(&[SortKey::NameDesc]), @r"
Name AuthorName AuthorEmail AuthorDate CommitterName CommitterEmail CommitterDate
feature@origin - - - - - -
feature Test User test.user@g.com 0 Test User test.user@g.com 0
chore Test User test.user@g.com 0 Test User test.user@g.com 0
bug-fix@upstream Test User test.user@g.com 0 Test User test.user@g.com 0
bug-fix@origin Test User test.user@g.com 0 Test User test.user@g.com 0
");
}
#[test]
fn test_sort_by_author_name() {
insta::assert_snapshot!(
prepare_data_sort_and_snapshot(&[SortKey::AuthorName]), @r"
Name AuthorName AuthorEmail AuthorDate CommitterName CommitterEmail CommitterDate
foo@origin - - - - - -
foo@upstream alice test.user@g.com 0 Test User test.user@g.com 0
foo bob test.user@g.com 0 Test User test.user@g.com 0
foo@origin bob test.user@g.com 0 Test User test.user@g.com 0
foo eve test.user@g.com 0 Test User test.user@g.com 0
");
}
#[test]
fn test_sort_by_author_name_desc() {
insta::assert_snapshot!(
prepare_data_sort_and_snapshot(&[SortKey::AuthorNameDesc]), @r"
Name AuthorName AuthorEmail AuthorDate CommitterName CommitterEmail CommitterDate
foo eve test.user@g.com 0 Test User test.user@g.com 0
foo bob test.user@g.com 0 Test User test.user@g.com 0
foo@origin bob test.user@g.com 0 Test User test.user@g.com 0
foo@upstream alice test.user@g.com 0 Test User test.user@g.com 0
foo@origin - - - - - -
");
}
#[test]
fn test_sort_by_author_email() {
insta::assert_snapshot!(
prepare_data_sort_and_snapshot(&[SortKey::AuthorEmail]), @r"
Name AuthorName AuthorEmail AuthorDate CommitterName CommitterEmail CommitterDate
foo@origin - - - - - -
foo@upstream Test User alice@g.com 0 Test User test.user@g.com 0
foo Test User bob@g.com 0 Test User test.user@g.com 0
foo@origin Test User bob@g.com 0 Test User test.user@g.com 0
foo Test User eve@g.com 0 Test User test.user@g.com 0
");
}
#[test]
fn test_sort_by_author_email_desc() {
insta::assert_snapshot!(
prepare_data_sort_and_snapshot(&[SortKey::AuthorEmailDesc]), @r"
Name AuthorName AuthorEmail AuthorDate CommitterName CommitterEmail CommitterDate
foo Test User eve@g.com 0 Test User test.user@g.com 0
foo Test User bob@g.com 0 Test User test.user@g.com 0
foo@origin Test User bob@g.com 0 Test User test.user@g.com 0
foo@upstream Test User alice@g.com 0 Test User test.user@g.com 0
foo@origin - - - - - -
");
}
#[test]
fn test_sort_by_author_date() {
insta::assert_snapshot!(
prepare_data_sort_and_snapshot(&[SortKey::AuthorDate]), @r"
Name AuthorName AuthorEmail AuthorDate CommitterName CommitterEmail CommitterDate
foo@origin - - - - - -
foo Test User test.user@g.com 1 Test User test.user@g.com 0
foo@upstream Test User test.user@g.com 1 Test User test.user@g.com 0
foo Test User test.user@g.com 2 Test User test.user@g.com 0
foo@origin Test User test.user@g.com 3 Test User test.user@g.com 0
");
}
#[test]
fn test_sort_by_author_date_desc() {
insta::assert_snapshot!(
prepare_data_sort_and_snapshot(&[SortKey::AuthorDateDesc]), @r"
Name AuthorName AuthorEmail AuthorDate CommitterName CommitterEmail CommitterDate
foo@origin Test User test.user@g.com 3 Test User test.user@g.com 0
foo Test User test.user@g.com 2 Test User test.user@g.com 0
foo Test User test.user@g.com 1 Test User test.user@g.com 0
foo@upstream Test User test.user@g.com 1 Test User test.user@g.com 0
foo@origin - - - - - -
");
}
#[test]
fn test_sort_by_committer_name() {
insta::assert_snapshot!(
prepare_data_sort_and_snapshot(&[SortKey::CommitterName]), @r"
Name AuthorName AuthorEmail AuthorDate CommitterName CommitterEmail CommitterDate
foo@origin - - - - - -
foo@upstream Test User test.user@g.com 0 alice test.user@g.com 0
foo Test User test.user@g.com 0 bob test.user@g.com 0
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/forget.rs | cli/src/commands/bookmark/forget.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use itertools::Itertools as _;
use jj_lib::op_store::LocalRemoteRefTarget;
use jj_lib::op_store::RefTarget;
use jj_lib::op_store::RemoteRef;
use jj_lib::ref_name::RefName;
use jj_lib::repo::Repo as _;
use jj_lib::view::View;
use super::warn_unmatched_local_or_remote_bookmarks;
use crate::cli_util::CommandHelper;
use crate::cli_util::default_ignored_remote_name;
use crate::command_error::CommandError;
use crate::complete;
use crate::revset_util::parse_union_name_patterns;
use crate::ui::Ui;
/// Forget a bookmark without marking it as a deletion to be pushed
///
/// If a local bookmark is forgotten, any corresponding remote bookmarks will
/// become untracked to ensure that the forgotten bookmark will not impact
/// remotes on future pushes.
#[derive(clap::Args, Clone, Debug)]
pub struct BookmarkForgetArgs {
/// When forgetting a local bookmark, also forget any corresponding remote
/// bookmarks
///
/// A forgotten remote bookmark will not impact remotes on future pushes. It
/// will be recreated on future fetches if it still exists on the remote. If
/// there is a corresponding Git-tracking remote bookmark, it will also be
/// forgotten.
#[arg(long)]
include_remotes: bool,
/// The bookmarks to forget
///
/// By default, the specified pattern matches bookmark names with glob
/// syntax. You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(required = true)]
#[arg(add = ArgValueCandidates::new(complete::bookmarks))]
names: Vec<String>,
}
pub fn cmd_bookmark_forget(
ui: &mut Ui,
command: &CommandHelper,
args: &BookmarkForgetArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo().clone();
let ignored_remote = default_ignored_remote_name(repo.store());
let matched_bookmarks = find_forgettable_bookmarks(ui, repo.view(), &args.names)?;
if matched_bookmarks.is_empty() {
writeln!(ui.status(), "No bookmarks to forget.")?;
return Ok(());
}
let mut tx = workspace_command.start_transaction();
let mut forgotten_remote: usize = 0;
for (name, bookmark_target) in &matched_bookmarks {
tx.repo_mut()
.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 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
if ignored_remote.is_some_and(|ignored| symbol.remote == ignored) {
continue;
}
tx.repo_mut().untrack_remote_bookmark(symbol);
}
}
writeln!(
ui.status(),
"Forgot {} local bookmarks.",
matched_bookmarks.len()
)?;
if forgotten_remote != 0 {
writeln!(ui.status(), "Forgot {forgotten_remote} remote bookmarks.")?;
}
let forgotten_bookmarks = matched_bookmarks
.iter()
.map(|(name, _)| name.as_symbol())
.join(", ");
tx.finish(ui, format!("forget bookmark {forgotten_bookmarks}"))?;
Ok(())
}
fn find_forgettable_bookmarks<'a>(
ui: &Ui,
view: &'a View,
name_patterns: &[String],
) -> Result<Vec<(&'a RefName, LocalRemoteRefTarget<'a>)>, CommandError> {
let name_expr = parse_union_name_patterns(ui, name_patterns)?;
let name_matcher = name_expr.to_matcher();
let matched_bookmarks = view
.bookmarks()
.filter(|(name, _)| name_matcher.is_match(name.as_str()))
.collect();
warn_unmatched_local_or_remote_bookmarks(ui, view, &name_expr)?;
Ok(matched_bookmarks)
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/mod.rs | cli/src/commands/bookmark/mod.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod create;
mod delete;
mod forget;
mod list;
mod r#move;
mod rename;
mod set;
mod track;
mod untrack;
use std::io;
use itertools::Itertools as _;
use jj_lib::backend::CommitId;
use jj_lib::iter_util::fallible_any;
use jj_lib::op_store::RefTarget;
use jj_lib::op_store::RemoteRef;
use jj_lib::ref_name::RefName;
use jj_lib::ref_name::RemoteName;
use jj_lib::ref_name::RemoteRefSymbol;
use jj_lib::repo::Repo;
use jj_lib::str_util::StringExpression;
use jj_lib::str_util::StringMatcher;
use jj_lib::view::View;
use self::create::BookmarkCreateArgs;
use self::create::cmd_bookmark_create;
use self::delete::BookmarkDeleteArgs;
use self::delete::cmd_bookmark_delete;
use self::forget::BookmarkForgetArgs;
use self::forget::cmd_bookmark_forget;
use self::list::BookmarkListArgs;
use self::list::cmd_bookmark_list;
use self::r#move::BookmarkMoveArgs;
use self::r#move::cmd_bookmark_move;
use self::rename::BookmarkRenameArgs;
use self::rename::cmd_bookmark_rename;
use self::set::BookmarkSetArgs;
use self::set::cmd_bookmark_set;
use self::track::BookmarkTrackArgs;
use self::track::cmd_bookmark_track;
use self::untrack::BookmarkUntrackArgs;
use self::untrack::cmd_bookmark_untrack;
use crate::cli_util::CommandHelper;
use crate::cli_util::RemoteBookmarkNamePattern;
use crate::command_error::CommandError;
use crate::ui::Ui;
// Unlike most other aliases, `b` is defined in the config and can be overridden
// by the user.
/// Manage bookmarks [default alias: b]
///
/// See [`jj help -k bookmarks`] for more information.
///
/// [`jj help -k bookmarks`]:
/// https://docs.jj-vcs.dev/latest/bookmarks
#[derive(clap::Subcommand, Clone, Debug)]
pub enum BookmarkCommand {
#[command(visible_alias("c"))]
Create(BookmarkCreateArgs),
#[command(visible_alias("d"))]
Delete(BookmarkDeleteArgs),
#[command(visible_alias("f"))]
Forget(BookmarkForgetArgs),
#[command(visible_alias("l"))]
List(BookmarkListArgs),
#[command(visible_alias("m"))]
Move(BookmarkMoveArgs),
#[command(visible_alias("r"))]
Rename(BookmarkRenameArgs),
#[command(visible_alias("s"))]
Set(BookmarkSetArgs),
#[command(visible_alias("t"))]
Track(BookmarkTrackArgs),
Untrack(BookmarkUntrackArgs),
}
pub fn cmd_bookmark(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &BookmarkCommand,
) -> Result<(), CommandError> {
match subcommand {
BookmarkCommand::Create(args) => cmd_bookmark_create(ui, command, args),
BookmarkCommand::Delete(args) => cmd_bookmark_delete(ui, command, args),
BookmarkCommand::Forget(args) => cmd_bookmark_forget(ui, command, args),
BookmarkCommand::List(args) => cmd_bookmark_list(ui, command, args),
BookmarkCommand::Move(args) => cmd_bookmark_move(ui, command, args),
BookmarkCommand::Rename(args) => cmd_bookmark_rename(ui, command, args),
BookmarkCommand::Set(args) => cmd_bookmark_set(ui, command, args),
BookmarkCommand::Track(args) => cmd_bookmark_track(ui, command, args),
BookmarkCommand::Untrack(args) => cmd_bookmark_untrack(ui, command, args),
}
}
fn find_trackable_remote_bookmarks<'a>(
ui: &Ui,
view: &'a View,
name_patterns: &[RemoteBookmarkNamePattern],
) -> Result<Vec<(RemoteRefSymbol<'a>, &'a RemoteRef)>, CommandError> {
let mut matching_bookmarks = vec![];
let mut unmatched_symbols = vec![];
for pattern in name_patterns {
let bookmark_matcher = pattern.bookmark.to_matcher();
let remote_matcher = pattern.remote.to_matcher();
let mut matches =
trackable_remote_bookmarks_matching(view, &bookmark_matcher, &remote_matcher)
.peekable();
if matches.peek().is_none() {
unmatched_symbols.extend(pattern.as_exact());
}
matching_bookmarks.extend(matches);
}
matching_bookmarks.sort_unstable_by(|(sym1, _), (sym2, _)| sym1.cmp(sym2));
matching_bookmarks.dedup_by(|(sym1, _), (sym2, _)| sym1 == sym2);
if !unmatched_symbols.is_empty() {
writeln!(
ui.warning_default(),
"No matching remote bookmarks for names: {}",
unmatched_symbols.iter().join(", ")
)?;
}
Ok(matching_bookmarks)
}
fn trackable_remote_bookmarks_matching<'a>(
view: &'a View,
bookmark_matcher: &StringMatcher,
remote_matcher: &StringMatcher,
) -> impl Iterator<Item = (RemoteRefSymbol<'a>, &'a RemoteRef)> {
let present_or_tracked_matches =
view.remote_bookmarks_matching(bookmark_matcher, remote_matcher);
let absent_matches =
view.remote_views_matching(remote_matcher)
.flat_map(move |(remote, remote_view)| {
view.local_bookmarks_matching(bookmark_matcher)
.filter(|&(name, _)| !remote_view.bookmarks.contains_key(name))
.map(|(name, _)| (name.to_remote_symbol(remote), RemoteRef::absent_ref()))
});
itertools::chain(present_or_tracked_matches, absent_matches)
}
fn is_fast_forward(
repo: &dyn Repo,
old_target: &RefTarget,
new_target_id: &CommitId,
) -> Result<bool, CommandError> {
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.
let found = fallible_any(old_target.added_ids(), |old| {
repo.index().is_ancestor(old, new_target_id)
})?;
Ok(found)
} else {
Ok(true)
}
}
/// Warns about exact patterns that don't match local bookmarks.
fn warn_unmatched_local_bookmarks(
ui: &Ui,
view: &View,
name_expr: &StringExpression,
) -> io::Result<()> {
let mut names = name_expr
.exact_strings()
.map(RefName::new)
.filter(|name| view.get_local_bookmark(name).is_absent())
.peekable();
if names.peek().is_none() {
return Ok(());
}
writeln!(
ui.warning_default(),
"No matching bookmarks for names: {}",
names.map(|name| name.as_symbol()).join(", ")
)
}
/// Warns about exact patterns that don't match local or remote bookmarks.
fn warn_unmatched_local_or_remote_bookmarks(
ui: &Ui,
view: &View,
name_expr: &StringExpression,
) -> io::Result<()> {
let mut names = name_expr
.exact_strings()
.map(RefName::new)
.filter(|&name| {
view.get_local_bookmark(name).is_absent()
&& view
.remote_views()
.all(|(_, remote_view)| !remote_view.bookmarks.contains_key(name))
})
.peekable();
if names.peek().is_none() {
return Ok(());
}
writeln!(
ui.warning_default(),
"No matching bookmarks for names: {}",
names.map(|name| name.as_symbol()).join(", ")
)
}
/// Warns about exact patterns that don't match remotes.
fn warn_unmatched_remotes(ui: &Ui, view: &View, name_expr: &StringExpression) -> io::Result<()> {
let mut names = name_expr
.exact_strings()
.map(RemoteName::new)
.filter(|name| view.get_remote_view(name).is_none())
.peekable();
if names.peek().is_none() {
return Ok(());
}
writeln!(
ui.warning_default(),
"No matching remotes for names: {}",
names.map(|name| name.as_symbol()).join(", ")
)
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/set.rs | cli/src/commands/bookmark/set.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use clap_complete::ArgValueCandidates;
use clap_complete::ArgValueCompleter;
use itertools::Itertools as _;
use jj_lib::object_id::ObjectId as _;
use jj_lib::op_store::RefTarget;
use jj_lib::ref_name::RefNameBuf;
use super::is_fast_forward;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::cli_util::has_tracked_remote_bookmarks;
use crate::command_error::CommandError;
use crate::command_error::user_error_with_hint;
use crate::complete;
use crate::revset_util;
use crate::ui::Ui;
/// Create or update a bookmark to point to a certain commit
#[derive(clap::Args, Clone, Debug)]
pub struct BookmarkSetArgs {
/// The bookmark's target revision
#[arg(
long,
short,
default_value = "@",
visible_alias = "to",
value_name = "REVSET"
)]
#[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
revision: RevisionArg,
/// Allow moving the bookmark backwards or sideways
#[arg(long, short = 'B')]
allow_backwards: bool,
/// The bookmarks to update
#[arg(required = true, value_parser = revset_util::parse_bookmark_name)]
#[arg(add = ArgValueCandidates::new(complete::local_bookmarks))]
names: Vec<RefNameBuf>,
}
pub fn cmd_bookmark_set(
ui: &mut Ui,
command: &CommandHelper,
args: &BookmarkSetArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let target_commit = workspace_command.resolve_single_rev(ui, &args.revision)?;
let repo = workspace_command.repo().as_ref();
let bookmark_names = &args.names;
let mut new_bookmarks = HashSet::new();
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 old_target.is_absent() && !has_tracked_remote_bookmarks(repo, name) {
new_bookmarks.insert(name);
} else if old_target.as_normal() != Some(target_commit.id()) {
moved_bookmark_count += 1;
}
if !args.allow_backwards && !is_fast_forward(repo, old_target, target_commit.id())? {
return Err(user_error_with_hint(
format!(
"Refusing to move bookmark backwards or sideways: {name}",
name = name.as_symbol()
),
"Use --allow-backwards to allow it.",
));
}
}
if target_commit.is_discardable(repo)? {
writeln!(ui.warning_default(), "Target revision is empty.")?;
}
let mut tx = workspace_command.start_transaction();
let remote_settings = tx.settings().remote_settings()?;
let remote_auto_track_matchers =
revset_util::parse_remote_auto_track_bookmarks_map(ui, &remote_settings)?;
let readonly_repo = tx.base_repo().clone();
for name in bookmark_names {
tx.repo_mut()
.set_local_bookmark_target(name, RefTarget::normal(target_commit.id().clone()));
if new_bookmarks.contains(name) {
for (remote_name, matcher) in &remote_auto_track_matchers {
if !matcher.is_match(name.as_str()) {
continue;
}
let Some(view) = readonly_repo.view().get_remote_view(remote_name) else {
continue;
};
let symbol = name.to_remote_symbol(remote_name);
if view.bookmarks.contains_key(name) {
writeln!(
ui.warning_default(),
"Auto-tracking bookmark that exists on the remote: {symbol}"
)?;
}
tx.repo_mut().track_remote_bookmark(symbol)?;
}
}
}
if let Some(mut formatter) = ui.status_formatter() {
let new_bookmark_count = new_bookmarks.len();
if new_bookmark_count > 0 {
write!(
formatter,
"Created {new_bookmark_count} bookmarks pointing to "
)?;
tx.write_commit_summary(formatter.as_mut(), &target_commit)?;
writeln!(formatter)?;
}
if moved_bookmark_count > 0 {
write!(formatter, "Moved {moved_bookmark_count} bookmarks to ")?;
tx.write_commit_summary(formatter.as_mut(), &target_commit)?;
writeln!(formatter)?;
}
}
tx.finish(
ui,
format!(
"point bookmark {names} to commit {id}",
names = bookmark_names.iter().map(|n| n.as_symbol()).join(", "),
id = target_commit.id().hex()
),
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/create.rs | cli/src/commands/bookmark/create.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCompleter;
use itertools::Itertools as _;
use jj_lib::object_id::ObjectId as _;
use jj_lib::op_store::RefTarget;
use jj_lib::ref_name::RefNameBuf;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::cli_util::has_tracked_remote_bookmarks;
use crate::command_error::CommandError;
use crate::command_error::user_error_with_hint;
use crate::complete;
use crate::revset_util;
use crate::ui::Ui;
/// Create a new bookmark
#[derive(clap::Args, Clone, Debug)]
pub struct BookmarkCreateArgs {
/// The bookmark's target revision
#[arg(
long,
short,
default_value = "@",
visible_alias = "to",
value_name = "REVSET"
)]
#[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
revision: RevisionArg,
/// The bookmarks to create
#[arg(required = true, value_parser = revset_util::parse_bookmark_name)]
names: Vec<RefNameBuf>,
}
pub fn cmd_bookmark_create(
ui: &mut Ui,
command: &CommandHelper,
args: &BookmarkCreateArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let target_commit = workspace_command.resolve_single_rev(ui, &args.revision)?;
let repo = workspace_command.repo().as_ref();
let view = repo.view();
let bookmark_names = &args.names;
for name in bookmark_names {
if view.get_local_bookmark(name).is_present() {
return Err(user_error_with_hint(
format!("Bookmark already exists: {name}", name = name.as_symbol()),
"Use `jj bookmark set` to update it.",
));
}
if has_tracked_remote_bookmarks(repo, name) {
return Err(user_error_with_hint(
format!(
"Tracked remote bookmarks exist for deleted bookmark: {name}",
name = name.as_symbol()
),
format!(
"Use `jj bookmark set` to recreate the local bookmark. Run `jj bookmark \
untrack {name}` to disassociate them.",
name = name.as_symbol()
),
));
}
}
if target_commit.is_discardable(repo)? {
writeln!(ui.warning_default(), "Target revision is empty.")?;
}
let mut tx = workspace_command.start_transaction();
let remote_settings = tx.settings().remote_settings()?;
let remote_auto_track_matchers =
revset_util::parse_remote_auto_track_bookmarks_map(ui, &remote_settings)?;
let readonly_repo = tx.base_repo().clone();
for name in bookmark_names {
tx.repo_mut()
.set_local_bookmark_target(name, RefTarget::normal(target_commit.id().clone()));
for (remote_name, matcher) in &remote_auto_track_matchers {
if !matcher.is_match(name.as_str()) {
continue;
}
let Some(view) = readonly_repo.view().get_remote_view(remote_name) else {
continue;
};
let symbol = name.to_remote_symbol(remote_name);
if view.bookmarks.contains_key(name) {
writeln!(
ui.warning_default(),
"Auto-tracking bookmark that exists on the remote: {symbol}"
)?;
}
tx.repo_mut().track_remote_bookmark(symbol)?;
}
}
if let Some(mut formatter) = ui.status_formatter() {
write!(
formatter,
"Created {} bookmarks pointing to ",
bookmark_names.len()
)?;
tx.write_commit_summary(formatter.as_mut(), &target_commit)?;
writeln!(formatter)?;
}
tx.finish(
ui,
format!(
"create bookmark {names} pointing to commit {id}",
names = bookmark_names.iter().map(|n| n.as_symbol()).join(", "),
id = target_commit.id().hex()
),
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/bookmark/delete.rs | cli/src/commands/bookmark/delete.rs | // Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use itertools::Itertools as _;
use jj_lib::op_store::RefTarget;
use super::warn_unmatched_local_bookmarks;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::complete;
use crate::revset_util::parse_union_name_patterns;
use crate::ui::Ui;
/// Delete an existing bookmark and propagate the deletion to remotes on the
/// next push
///
/// Revisions referred to by the deleted bookmarks are not abandoned. To delete
/// revisions as well as bookmarks, use `jj abandon`. For example, `jj abandon
/// main..<bookmark>` will abandon revisions belonging to the `<bookmark>`
/// branch (relative to the `main` branch.)
///
/// If you don't want the deletion of the local bookmark to propagate to any
/// tracked remote bookmarks, use `jj bookmark forget` instead.
#[derive(clap::Args, Clone, Debug)]
pub struct BookmarkDeleteArgs {
/// The bookmarks to delete
///
/// By default, the specified pattern matches bookmark names with glob
/// syntax. You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(required = true)]
#[arg(add = ArgValueCandidates::new(complete::local_bookmarks))]
names: Vec<String>,
}
pub fn cmd_bookmark_delete(
ui: &mut Ui,
command: &CommandHelper,
args: &BookmarkDeleteArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo().clone();
let name_expr = parse_union_name_patterns(ui, &args.names)?;
let name_matcher = name_expr.to_matcher();
let matched_bookmarks = repo
.view()
.local_bookmarks_matching(&name_matcher)
.collect_vec();
warn_unmatched_local_bookmarks(ui, repo.view(), &name_expr)?;
if matched_bookmarks.is_empty() {
writeln!(ui.status(), "No bookmarks to delete.")?;
return Ok(());
}
let mut tx = workspace_command.start_transaction();
for (name, _) in &matched_bookmarks {
tx.repo_mut()
.set_local_bookmark_target(name, RefTarget::absent());
}
writeln!(
ui.status(),
"Deleted {} bookmarks.",
matched_bookmarks.len()
)?;
tx.finish(
ui,
format!(
"delete bookmark {}",
matched_bookmarks
.iter()
.map(|(name, _)| name.as_symbol())
.join(", ")
),
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/config/path.rs | cli/src/commands/config/path.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::Write as _;
use jj_lib::file_util;
use tracing::instrument;
use super::ConfigLevelArgs;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::ui::Ui;
/// Print the paths to the config files
///
/// A config file at that path may or may not exist.
///
/// See `jj config edit` if you'd like to immediately edit a file.
#[derive(clap::Args, Clone, Debug)]
pub struct ConfigPathArgs {
#[command(flatten)]
pub level: ConfigLevelArgs,
}
#[instrument(skip_all)]
pub fn cmd_config_path(
ui: &mut Ui,
command: &CommandHelper,
args: &ConfigPathArgs,
) -> Result<(), CommandError> {
for config_path in args.level.config_paths(command.config_env())? {
let path_bytes = file_util::path_to_bytes(config_path).map_err(user_error)?;
ui.stdout().write_all(path_bytes)?;
writeln!(ui.stdout())?;
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/config/list.rs | cli/src/commands/config/list.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use jj_lib::config::ConfigNamePathBuf;
use jj_lib::config::ConfigSource;
use jj_lib::settings::UserSettings;
use tracing::instrument;
use super::ConfigLevelArgs;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::complete;
use crate::config::AnnotatedValue;
use crate::config::resolved_config_values;
use crate::generic_templater;
use crate::generic_templater::GenericTemplateLanguage;
use crate::templater::TemplatePropertyExt as _;
use crate::templater::TemplateRenderer;
use crate::ui::Ui;
/// List variables set in config files, along with their values.
#[derive(clap::Args, Clone, Debug)]
#[command(mut_group("config_level", |g| g.required(false)))]
pub struct ConfigListArgs {
/// An optional name of a specific config option to look up.
#[arg(add = ArgValueCandidates::new(complete::config_keys))]
pub name: Option<ConfigNamePathBuf>,
/// Whether to explicitly include built-in default values in the list.
#[arg(long, conflicts_with = "config_level")]
pub include_defaults: bool,
/// Allow printing overridden values.
#[arg(long)]
pub include_overridden: bool,
#[command(flatten)]
pub level: ConfigLevelArgs,
/// Render each variable using the given template
///
/// The following keywords are available in the template expression:
///
/// * `name: String`: Config name, in [TOML's "dotted key" format].
/// * `value: ConfigValue`: Value to be formatted in TOML syntax.
/// * `overridden: Boolean`: True if the value is shadowed by other.
/// * `source: String`: Source of the value.
/// * `path: String`: Path to the config file.
///
/// Can be overridden by the `templates.config_list` setting. To
/// see a detailed config list, use the `builtin_config_list_detailed`
/// template.
///
/// See [`jj help -k templates`] for more information.
///
/// [TOML's "dotted key" format]: https://toml.io/en/v1.0.0#keys
///
/// [`jj help -k templates`]:
/// https://docs.jj-vcs.dev/latest/templates/
#[arg(long, short = 'T', verbatim_doc_comment)]
#[arg(add = ArgValueCandidates::new(complete::template_aliases))]
template: Option<String>,
}
#[instrument(skip_all)]
pub fn cmd_config_list(
ui: &mut Ui,
command: &CommandHelper,
args: &ConfigListArgs,
) -> Result<(), CommandError> {
let template: TemplateRenderer<AnnotatedValue> = {
let language = config_template_language(command.settings());
let text = match &args.template {
Some(value) => value.to_owned(),
None => command.settings().get_string("templates.config_list")?,
};
command
.parse_template(ui, &language, &text)?
.labeled(["config_list"])
};
let name_path = args.name.clone().unwrap_or_else(ConfigNamePathBuf::root);
let mut annotated_values = resolved_config_values(command.settings().config(), &name_path);
// The default layer could be excluded beforehand as layers[len..], but we
// can't do the same for "annotated.source == target_source" in order for
// resolved_config_values() to mark values overridden by the upper layers.
if let Some(target_source) = args.level.get_source_kind() {
annotated_values.retain(|annotated| annotated.source == target_source);
} else if !args.include_defaults {
annotated_values.retain(|annotated| annotated.source != ConfigSource::Default);
}
if !args.include_overridden {
annotated_values.retain(|annotated| !annotated.is_overridden);
}
if !annotated_values.is_empty() {
ui.request_pager();
let mut formatter = ui.stdout_formatter();
for annotated in &annotated_values {
template.format(annotated, formatter.as_mut())?;
}
} else {
// Note to stderr explaining why output is empty.
if let Some(name) = &args.name {
writeln!(ui.warning_default(), "No matching config key for {name}")?;
} else {
writeln!(ui.warning_default(), "No config to list")?;
}
}
Ok(())
}
type ConfigTemplateLanguage = GenericTemplateLanguage<'static, AnnotatedValue>;
generic_templater::impl_self_property_wrapper!(AnnotatedValue);
// AnnotatedValue will be cloned internally in the templater. If the cloning
// cost matters, wrap it with Rc.
fn config_template_language(settings: &UserSettings) -> ConfigTemplateLanguage {
let mut language = ConfigTemplateLanguage::new(settings);
language.add_keyword("name", |self_property| {
let out_property = self_property.map(|annotated| annotated.name.to_string());
Ok(out_property.into_dyn_wrapped())
});
language.add_keyword("value", |self_property| {
// .decorated("", "") to trim leading/trailing whitespace
let out_property = self_property.map(|annotated| annotated.value.decorated("", ""));
Ok(out_property.into_dyn_wrapped())
});
language.add_keyword("source", |self_property| {
let out_property = self_property.map(|annotated| annotated.source.to_string());
Ok(out_property.into_dyn_wrapped())
});
language.add_keyword("path", |self_property| {
let out_property = self_property.map(|annotated| {
// TODO: maybe add FilePath(PathBuf) template type?
annotated
.path
.as_ref()
.map_or_else(String::new, |path| path.to_string_lossy().into_owned())
});
Ok(out_property.into_dyn_wrapped())
});
language.add_keyword("overridden", |self_property| {
let out_property = self_property.map(|annotated| annotated.is_overridden);
Ok(out_property.into_dyn_wrapped())
});
language
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/config/mod.rs | cli/src/commands/config/mod.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod edit;
mod get;
mod list;
mod path;
mod set;
mod unset;
use std::path::Path;
use itertools::Itertools as _;
use jj_lib::config::ConfigFile;
use jj_lib::config::ConfigSource;
use tracing::instrument;
use self::edit::ConfigEditArgs;
use self::edit::cmd_config_edit;
use self::get::ConfigGetArgs;
use self::get::cmd_config_get;
use self::list::ConfigListArgs;
use self::list::cmd_config_list;
use self::path::ConfigPathArgs;
use self::path::cmd_config_path;
use self::set::ConfigSetArgs;
use self::set::cmd_config_set;
use self::unset::ConfigUnsetArgs;
use self::unset::cmd_config_unset;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::config::ConfigEnv;
use crate::ui::Ui;
#[derive(clap::Args, Clone, Debug)]
#[group(id = "config_level", multiple = false, required = true)]
pub(crate) struct ConfigLevelArgs {
/// Target the user-level config
#[arg(long)]
user: bool,
/// Target the repo-level config
#[arg(long)]
repo: bool,
/// Target the workspace-level config
#[arg(long)]
workspace: bool,
}
impl ConfigLevelArgs {
fn get_source_kind(&self) -> Option<ConfigSource> {
if self.user {
Some(ConfigSource::User)
} else if self.repo {
Some(ConfigSource::Repo)
} else if self.workspace {
Some(ConfigSource::Workspace)
} else {
None
}
}
fn config_paths<'a>(&self, config_env: &'a ConfigEnv) -> Result<Vec<&'a Path>, CommandError> {
if self.user {
let paths = config_env.user_config_paths().collect_vec();
if paths.is_empty() {
return Err(user_error("No user config path found"));
}
Ok(paths)
} else if self.repo {
config_env
.repo_config_path()
.map(|p| vec![p])
.ok_or_else(|| user_error("No repo config path found"))
} else if self.workspace {
config_env
.workspace_config_path()
.map(|p| vec![p])
.ok_or_else(|| user_error("No workspace config path found"))
} else {
panic!("No config_level provided")
}
}
fn edit_config_file(
&self,
ui: &Ui,
command: &CommandHelper,
) -> Result<ConfigFile, CommandError> {
let config_env = command.config_env();
let config = command.raw_config();
let pick_one = |mut files: Vec<ConfigFile>, not_found_error: &str| {
if files.len() > 1 {
let mut choices = vec![];
let mut formatter = ui.stderr_formatter();
for (i, file) in files.iter().enumerate() {
writeln!(formatter, "{}: {}", i + 1, file.path().display())?;
choices.push((i + 1).to_string());
}
drop(formatter);
let index =
ui.prompt_choice("Choose a config file (default 1)", &choices, Some(0))?;
return Ok(files[index].clone());
}
files.pop().ok_or_else(|| user_error(not_found_error))
};
if self.user {
pick_one(
config_env.user_config_files(config)?,
"No user config path found to edit",
)
} else if self.repo {
pick_one(
config_env.repo_config_files(config)?,
"No repo config path found to edit",
)
} else if self.workspace {
pick_one(
config_env.workspace_config_files(config)?,
"No workspace config path found to edit",
)
} else {
panic!("No config_level provided")
}
}
}
/// Manage config options
///
/// Operates on jj configuration, which comes from the config file and
/// environment variables.
///
/// See [`jj help -k config`] to know more about file locations, supported
/// config options, and other details about `jj config`.
///
/// [`jj help -k config`]:
/// https://docs.jj-vcs.dev/latest/config/
#[derive(clap::Subcommand, Clone, Debug)]
pub(crate) enum ConfigCommand {
#[command(visible_alias("e"))]
Edit(ConfigEditArgs),
#[command(visible_alias("g"))]
Get(ConfigGetArgs),
#[command(visible_alias("l"))]
List(ConfigListArgs),
#[command(visible_alias("p"))]
Path(ConfigPathArgs),
#[command(visible_alias("s"))]
Set(ConfigSetArgs),
#[command(visible_alias("u"))]
Unset(ConfigUnsetArgs),
}
#[instrument(skip_all)]
pub(crate) fn cmd_config(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &ConfigCommand,
) -> Result<(), CommandError> {
match subcommand {
ConfigCommand::Edit(args) => cmd_config_edit(ui, command, args),
ConfigCommand::Get(args) => cmd_config_get(ui, command, args),
ConfigCommand::List(args) => cmd_config_list(ui, command, args),
ConfigCommand::Path(args) => cmd_config_path(ui, command, args),
ConfigCommand::Set(args) => cmd_config_set(ui, command, args),
ConfigCommand::Unset(args) => cmd_config_unset(ui, command, args),
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/config/unset.rs | cli/src/commands/config/unset.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use jj_lib::config::ConfigNamePathBuf;
use tracing::instrument;
use super::ConfigLevelArgs;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::command_error::user_error_with_message;
use crate::complete;
use crate::ui::Ui;
/// Update a config file to unset the given option.
#[derive(clap::Args, Clone, Debug)]
pub struct ConfigUnsetArgs {
#[arg(required = true)]
#[arg(add = ArgValueCandidates::new(complete::leaf_config_keys))]
name: ConfigNamePathBuf,
#[command(flatten)]
level: ConfigLevelArgs,
}
#[instrument(skip_all)]
pub fn cmd_config_unset(
ui: &mut Ui,
command: &CommandHelper,
args: &ConfigUnsetArgs,
) -> Result<(), CommandError> {
let mut file = args.level.edit_config_file(ui, command)?;
let old_value = file
.delete_value(&args.name)
.map_err(|err| user_error_with_message(format!("Failed to unset {}", args.name), err))?;
if old_value.is_none() {
return Err(user_error(format!(r#""{}" doesn't exist"#, args.name)));
}
file.save()?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/config/edit.rs | cli/src/commands/config/edit.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use jj_lib::config::ConfigLayer;
use tracing::instrument;
use super::ConfigLevelArgs;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::print_error_sources;
use crate::ui::Ui;
/// Start an editor on a jj config file.
///
/// Creates the file if it doesn't already exist regardless of what the editor
/// does.
#[derive(clap::Args, Clone, Debug)]
pub struct ConfigEditArgs {
#[command(flatten)]
pub level: ConfigLevelArgs,
}
#[instrument(skip_all)]
pub fn cmd_config_edit(
ui: &mut Ui,
command: &CommandHelper,
args: &ConfigEditArgs,
) -> Result<(), CommandError> {
let editor = command.text_editor()?;
let file = args.level.edit_config_file(ui, command)?;
if !file.path().exists() {
file.save()?;
}
// Editing again and again until either of these conditions is met
// 1. The config is OK
// 2. The user restores previous one
writeln!(ui.status(), "Editing file: {}", file.path().display())?;
loop {
editor.edit_file(file.path())?;
// Trying to load back config. If error, prompt to continue editing
if let Err(e) = ConfigLayer::load_from_file(file.layer().source, file.path().to_path_buf())
{
writeln!(
ui.warning_default(),
"An error has been found inside the config:"
)?;
print_error_sources(ui, Some(&e))?;
let continue_editing = ui.prompt_yes_no(
"Do you want to keep editing the file? If not, previous config will be restored.",
Some(true),
)?;
if !continue_editing {
// Saving back previous config
file.save()?;
break;
}
} else {
// config is OK
break;
}
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/config/set.rs | cli/src/commands/config/set.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io;
use clap_complete::ArgValueCandidates;
use jj_lib::commit::Commit;
use jj_lib::config::ConfigNamePathBuf;
use jj_lib::config::ConfigValue;
use jj_lib::repo::Repo as _;
use tracing::instrument;
use super::ConfigLevelArgs;
use crate::cli_util::CommandHelper;
use crate::cli_util::WorkspaceCommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error_with_message;
use crate::complete;
use crate::config::parse_value_or_bare_string;
use crate::ui::Ui;
/// Update a config file to set the given option to a given value.
#[derive(clap::Args, Clone, Debug)]
pub struct ConfigSetArgs {
#[arg(required = true)]
#[arg(add = ArgValueCandidates::new(complete::leaf_config_keys))]
name: ConfigNamePathBuf,
/// New value to set
///
/// The value should be specified as a TOML expression. If string value
/// isn't enclosed by any TOML constructs (such as apostrophes or array
/// notation), quotes can be omitted. Note that the value may also need
/// shell quoting. TOML multi-line strings can be useful if the value
/// contains apostrophes. For example, to set `foo.bar` to the string
/// "{don't}" use `jj config set --user foo.bar "'''{don't}'''"`. This is
/// valid in both Bash and Fish.
///
/// Alternative, e.g. to avoid dealing with shell quoting, use `jj config
/// edit` to edit the TOML file directly.
#[arg(required = true, value_parser = parse_value_or_bare_string)]
value: ConfigValue,
#[command(flatten)]
level: ConfigLevelArgs,
}
/// Denotes a type of author change
enum AuthorChange {
Name,
Email,
}
#[instrument(skip_all)]
pub fn cmd_config_set(
ui: &mut Ui,
command: &CommandHelper,
args: &ConfigSetArgs,
) -> 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 args.name == ConfigNamePathBuf::from_iter(vec!["user", "name"]) {
check_wc_author(ui, command, &args.value, AuthorChange::Name)?;
} else if args.name == ConfigNamePathBuf::from_iter(vec!["user", "email"]) {
check_wc_author(ui, command, &args.value, AuthorChange::Email)?;
};
file.set_value(&args.name, &args.value)
.map_err(|err| user_error_with_message(format!("Failed to set {}", args.name), err))?;
file.save()?;
Ok(())
}
/// Returns the commit of the working copy if it exists.
fn maybe_wc_commit(helper: &WorkspaceCommandHelper) -> Option<Commit> {
let repo = helper.repo();
let id = helper.get_wc_commit_id()?;
repo.store().get_commit(id).ok()
}
/// Check if the working copy author name matches the user's config value
/// If it doesn't, print a warning message
fn check_wc_author(
ui: &mut Ui,
command: &CommandHelper,
new_value: &toml_edit::Value,
author_change: AuthorChange,
) -> io::Result<()> {
let helper = match command.workspace_helper(ui) {
Ok(helper) => helper,
Err(_) => return Ok(()), // config set should work even if cwd isn't a jj repo
};
if let Some(wc_commit) = maybe_wc_commit(&helper) {
let author = wc_commit.author();
let orig_value = match author_change {
AuthorChange::Name => &author.name,
AuthorChange::Email => &author.email,
};
if new_value.as_str() != Some(orig_value) {
warn_wc_author(ui, &author.name, &author.email)?;
}
}
Ok(())
}
/// Prints a warning message about the working copy to the user
fn warn_wc_author(ui: &Ui, user_name: &str, user_email: &str) -> io::Result<()> {
Ok(writeln!(
ui.warning_default(),
"This setting will only impact future commits.\nThe author of the working copy will stay \
\"{user_name} <{user_email}>\".\nTo change the working copy author, use \"jj metaedit \
--update-author\""
)?)
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/config/get.rs | cli/src/commands/config/get.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::Write as _;
use clap_complete::ArgValueCandidates;
use jj_lib::config::ConfigNamePathBuf;
use jj_lib::config::ConfigValue;
use tracing::instrument;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::complete;
use crate::ui::Ui;
/// Get the value of a given config option.
///
/// Unlike `jj config list`, the result of `jj config get` is printed without
/// extra formatting and therefore is usable in scripting. For example:
///
/// $ jj config list user.name
/// user.name="Martin von Zweigbergk"
/// $ jj config get user.name
/// Martin von Zweigbergk
#[derive(clap::Args, Clone, Debug)]
#[command(verbatim_doc_comment)]
pub struct ConfigGetArgs {
#[arg(required = true)]
#[arg(add = ArgValueCandidates::new(complete::leaf_config_keys))]
name: ConfigNamePathBuf,
}
#[instrument(skip_all)]
pub fn cmd_config_get(
ui: &mut Ui,
command: &CommandHelper,
args: &ConfigGetArgs,
) -> Result<(), CommandError> {
let value = command.settings().get_value(&args.name)?;
let stringified = match value {
// Remove extra formatting from a string value
ConfigValue::String(v) => v.into_value(),
// Print other values in TOML syntax (but whitespace trimmed)
ConfigValue::Integer(_)
| ConfigValue::Float(_)
| ConfigValue::Boolean(_)
| ConfigValue::Datetime(_)
| ConfigValue::Array(_)
| ConfigValue::InlineTable(_) => value.decorated("", "").to_string(),
};
writeln!(ui.stdout(), "{stringified}")?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/tag/list.rs | cli/src/commands/tag/list.rs | // Copyright 2020-2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use clap_complete::ArgValueCandidates;
use jj_lib::str_util::StringExpression;
use super::warn_unmatched_local_tags;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::commit_templater::CommitRef;
use crate::complete;
use crate::revset_util::parse_union_name_patterns;
use crate::templater::TemplateRenderer;
use crate::ui::Ui;
/// List tags.
#[derive(clap::Args, Clone, Debug)]
pub struct TagListArgs {
/// Show tags whose local name matches
///
/// By default, the specified pattern matches tag names with glob syntax.
/// You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
pub names: Option<Vec<String>>,
/// Render each tag using the given template
///
/// All 0-argument methods of the [`CommitRef` type] are available as
/// keywords in the template expression. See [`jj help -k templates`]
/// for more information.
///
/// [`CommitRef` type]:
/// https://docs.jj-vcs.dev/latest/templates/#commitref-type
///
/// [`jj help -k templates`]:
/// https://docs.jj-vcs.dev/latest/templates/
#[arg(long, short = 'T')]
#[arg(add = ArgValueCandidates::new(complete::template_aliases))]
template: Option<String>,
}
pub fn cmd_tag_list(
ui: &mut Ui,
command: &CommandHelper,
args: &TagListArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo();
let view = repo.view();
let name_expr = match &args.names {
Some(texts) => parse_union_name_patterns(ui, texts)?,
None => StringExpression::all(),
};
let name_matcher = name_expr.to_matcher();
let template: TemplateRenderer<Rc<CommitRef>> = {
let language = workspace_command.commit_template_language();
let text = match &args.template {
Some(value) => value.to_owned(),
None => workspace_command.settings().get("templates.tag_list")?,
};
workspace_command
.parse_template(ui, &language, &text)?
.labeled(["tag_list"])
};
ui.request_pager();
let mut formatter = ui.stdout_formatter();
for (name, target) in view
.local_tags()
.filter(|(name, _)| name_matcher.is_match(name.as_str()))
{
let commit_ref = CommitRef::local_only(name, target.clone());
template.format(&commit_ref, formatter.as_mut())?;
}
warn_unmatched_local_tags(ui, view, &name_expr)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/tag/mod.rs | cli/src/commands/tag/mod.rs | // Copyright 2020-2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod delete;
mod list;
mod set;
use std::io;
use itertools::Itertools as _;
use jj_lib::ref_name::RefName;
use jj_lib::str_util::StringExpression;
use jj_lib::view::View;
use self::delete::TagDeleteArgs;
use self::delete::cmd_tag_delete;
use self::list::TagListArgs;
use self::list::cmd_tag_list;
use self::set::TagSetArgs;
use self::set::cmd_tag_set;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// Manage tags.
#[derive(clap::Subcommand, Clone, Debug)]
pub enum TagCommand {
#[command(visible_alias("d"))]
Delete(TagDeleteArgs),
#[command(visible_alias("l"))]
List(TagListArgs),
#[command(visible_alias("s"))]
Set(TagSetArgs),
}
pub fn cmd_tag(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &TagCommand,
) -> Result<(), CommandError> {
match subcommand {
TagCommand::Delete(args) => cmd_tag_delete(ui, command, args),
TagCommand::List(args) => cmd_tag_list(ui, command, args),
TagCommand::Set(args) => cmd_tag_set(ui, command, args),
}
}
/// Warns about exact patterns that don't match local tags.
fn warn_unmatched_local_tags(ui: &Ui, view: &View, name_expr: &StringExpression) -> io::Result<()> {
let mut names = name_expr
.exact_strings()
.map(RefName::new)
.filter(|name| view.get_local_tag(name).is_absent())
.peekable();
if names.peek().is_none() {
return Ok(());
}
writeln!(
ui.warning_default(),
"No matching tags for names: {}",
names.map(|name| name.as_symbol()).join(", ")
)
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/tag/set.rs | cli/src/commands/tag/set.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use clap_complete::ArgValueCompleter;
use itertools::Itertools as _;
use jj_lib::op_store::RefTarget;
use jj_lib::ref_name::RefNameBuf;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::command_error::CommandError;
use crate::command_error::user_error_with_hint;
use crate::complete;
use crate::revset_util;
use crate::ui::Ui;
/// Create or update tags
#[derive(clap::Args, Clone, Debug)]
pub struct TagSetArgs {
/// Target revision to point to
#[arg(
long,
short,
default_value = "@",
visible_alias = "to",
value_name = "REVSET"
)]
#[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
revision: RevisionArg,
/// Allow moving existing tags
#[arg(long)]
allow_move: bool,
/// Tag names to create or update
#[arg(required = true, value_parser = revset_util::parse_tag_name)]
#[arg(add = ArgValueCandidates::new(complete::local_tags))]
names: Vec<RefNameBuf>,
}
pub fn cmd_tag_set(
ui: &mut Ui,
command: &CommandHelper,
args: &TagSetArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let target_commit = workspace_command.resolve_single_rev(ui, &args.revision)?;
let repo = workspace_command.repo().as_ref();
let mut new_count = 0;
let mut moved_count = 0;
for name in &args.names {
let old_target = repo.view().get_local_tag(name);
// TODO: If we add support for tracked remote tags, deleted tags should
// be considered present until they get pushed. See cmd_bookmark_set().
if old_target.is_present() && !args.allow_move {
return Err(user_error_with_hint(
format!("Refusing to move tag: {name}", name = name.as_symbol()),
"Use --allow-move to update existing tags.",
));
}
if old_target.is_absent() {
new_count += 1;
} else if old_target.as_normal() != Some(target_commit.id()) {
moved_count += 1;
}
}
if target_commit.is_discardable(repo)? {
writeln!(ui.warning_default(), "Target revision is empty.")?;
}
let mut tx = workspace_command.start_transaction();
for name in &args.names {
tx.repo_mut()
.set_local_tag_target(name, RefTarget::normal(target_commit.id().clone()));
}
if let Some(mut formatter) = ui.status_formatter() {
if new_count > 0 {
write!(formatter, "Created {new_count} tags pointing to ")?;
tx.write_commit_summary(formatter.as_mut(), &target_commit)?;
writeln!(formatter)?;
}
if moved_count > 0 {
write!(formatter, "Moved {moved_count} tags to ")?;
tx.write_commit_summary(formatter.as_mut(), &target_commit)?;
writeln!(formatter)?;
}
}
tx.finish(
ui,
format!(
"set tag {names} to commit {id}",
names = args.names.iter().map(|n| n.as_symbol()).join(", "),
id = target_commit.id()
),
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/tag/delete.rs | cli/src/commands/tag/delete.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap_complete::ArgValueCandidates;
use itertools::Itertools as _;
use jj_lib::op_store::RefTarget;
use super::warn_unmatched_local_tags;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::complete;
use crate::revset_util::parse_union_name_patterns;
use crate::ui::Ui;
/// Delete existing tags
///
/// Revisions referred to by the deleted tags are not abandoned.
#[derive(clap::Args, Clone, Debug)]
pub struct TagDeleteArgs {
/// Tag names to delete
///
/// By default, the specified pattern matches tag names with glob syntax.
/// You can also use other [string pattern syntax].
///
/// [string pattern syntax]:
/// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
#[arg(required = true)]
#[arg(add = ArgValueCandidates::new(complete::local_tags))]
names: Vec<String>,
}
pub fn cmd_tag_delete(
ui: &mut Ui,
command: &CommandHelper,
args: &TagDeleteArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo().clone();
let name_expr = parse_union_name_patterns(ui, &args.names)?;
let name_matcher = name_expr.to_matcher();
let matched_tags = repo.view().local_tags_matching(&name_matcher).collect_vec();
warn_unmatched_local_tags(ui, repo.view(), &name_expr)?;
if matched_tags.is_empty() {
writeln!(ui.status(), "No tags to delete.")?;
return Ok(());
}
let mut tx = workspace_command.start_transaction();
for (name, _) in &matched_tags {
tx.repo_mut()
.set_local_tag_target(name, RefTarget::absent());
}
writeln!(ui.status(), "Deleted {} tags.", matched_tags.len())?;
tx.finish(
ui,
format!(
"delete tag {names}",
names = matched_tags.iter().map(|(n, _)| n.as_symbol()).join(", ")
),
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/watchman.rs | cli/src/commands/debug/watchman.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(feature = "watchman")]
use std::io::Write as _;
use clap::Subcommand;
#[cfg(feature = "watchman")]
use jj_lib::fsmonitor::FsmonitorSettings;
#[cfg(feature = "watchman")]
use jj_lib::fsmonitor::WatchmanConfig;
#[cfg(feature = "watchman")]
use jj_lib::local_working_copy::LocalWorkingCopy;
#[cfg(feature = "watchman")]
use jj_lib::working_copy::WorkingCopy;
#[cfg(feature = "watchman")]
use pollster::FutureExt as _;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::ui::Ui;
#[derive(Subcommand, Clone, Debug)]
pub enum DebugWatchmanCommand {
/// Check whether `watchman` is enabled and whether it's correctly installed
Status,
QueryClock,
QueryChangedFiles,
ResetClock,
}
#[cfg(feature = "watchman")]
pub fn cmd_debug_watchman(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &DebugWatchmanCommand,
) -> Result<(), CommandError> {
use jj_lib::local_working_copy::LockedLocalWorkingCopy;
let mut workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo().clone();
let watchman_config = WatchmanConfig {
// The value is likely irrelevant here. TODO(ilyagr): confirm
register_trigger: false,
};
match subcommand {
DebugWatchmanCommand::Status => {
// TODO(ilyagr): It would be nice to add colors here
let config = match FsmonitorSettings::from_settings(workspace_command.settings())? {
FsmonitorSettings::Watchman(config) => {
writeln!(ui.stdout(), "Watchman is enabled via `fsmonitor.backend`.")?;
writeln!(
ui.stdout(),
"Background snapshotting is {}. Use \
`fsmonitor.watchman.register-snapshot-trigger` to control it.",
if config.register_trigger {
"enabled"
} else {
"disabled"
}
)?;
config
}
FsmonitorSettings::None => {
writeln!(
ui.stdout(),
r#"Watchman is disabled. Set `fsmonitor.backend="watchman"` to enable."#
)?;
writeln!(
ui.stdout(),
"Attempting to contact the `watchman` CLI regardless..."
)?;
watchman_config
}
other_fsmonitor => {
return Err(user_error(format!(
r"This command does not support the currently enabled filesystem monitor: {other_fsmonitor:?}."
)));
}
};
let wc = check_local_disk_wc(workspace_command.working_copy())?;
wc.query_watchman(&config).block_on()?;
writeln!(
ui.stdout(),
"The watchman server seems to be installed and working correctly."
)?;
writeln!(
ui.stdout(),
"Background snapshotting is currently {}.",
if wc.is_watchman_trigger_registered(&config).block_on()? {
"active"
} else {
"inactive"
}
)?;
}
DebugWatchmanCommand::QueryClock => {
let wc = check_local_disk_wc(workspace_command.working_copy())?;
let (clock, _changed_files) = wc.query_watchman(&watchman_config).block_on()?;
writeln!(ui.stdout(), "Clock: {clock:?}")?;
}
DebugWatchmanCommand::QueryChangedFiles => {
let wc = check_local_disk_wc(workspace_command.working_copy())?;
let (_clock, changed_files) = wc.query_watchman(&watchman_config).block_on()?;
writeln!(ui.stdout(), "Changed files: {changed_files:?}")?;
}
DebugWatchmanCommand::ResetClock => {
let (mut locked_ws, _commit) = workspace_command.start_working_copy_mutation()?;
let Some(locked_local_wc): Option<&mut LockedLocalWorkingCopy> =
locked_ws.locked_wc().downcast_mut()
else {
return Err(user_error(
"This command requires a standard local-disk working copy",
));
};
locked_local_wc.reset_watchman()?;
locked_ws.finish(repo.op_id().clone())?;
writeln!(ui.status(), "Reset Watchman clock")?;
}
}
Ok(())
}
#[cfg(not(feature = "watchman"))]
pub fn cmd_debug_watchman(
_ui: &mut Ui,
_command: &CommandHelper,
_subcommand: &DebugWatchmanCommand,
) -> Result<(), CommandError> {
Err(user_error(
"Cannot query Watchman because jj was not compiled with the `watchman` feature",
))
}
#[cfg(feature = "watchman")]
fn check_local_disk_wc(x: &dyn WorkingCopy) -> Result<&LocalWorkingCopy, CommandError> {
x.downcast_ref()
.ok_or_else(|| user_error("This command requires a standard local-disk working copy"))
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/object.rs | cli/src/commands/debug/object.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use clap::Subcommand;
use jj_lib::backend::CommitId;
use jj_lib::backend::FileId;
use jj_lib::backend::SymlinkId;
use jj_lib::backend::TreeId;
use jj_lib::backend::TreeValue;
use jj_lib::op_store::OperationId;
use jj_lib::op_store::ViewId;
use jj_lib::repo_path::RepoPathBuf;
use pollster::FutureExt as _;
use tokio::io::AsyncReadExt as _;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::ui::Ui;
/// Show information about an operation and its view
#[derive(Subcommand, Clone, Debug)]
pub enum DebugObjectArgs {
Commit(DebugObjectCommitArgs),
File(DebugObjectFileArgs),
Operation(DebugObjectOperationArgs),
Symlink(DebugObjectSymlinkArgs),
Tree(DebugObjectTreeArgs),
View(DebugObjectViewArgs),
}
#[derive(clap::Args, Clone, Debug)]
pub struct DebugObjectCommitArgs {
id: String,
}
#[derive(clap::Args, Clone, Debug)]
pub struct DebugObjectFileArgs {
#[arg(value_hint = clap::ValueHint::FilePath)]
path: String,
id: String,
}
#[derive(clap::Args, Clone, Debug)]
pub struct DebugObjectOperationArgs {
id: String,
}
#[derive(clap::Args, Clone, Debug)]
pub struct DebugObjectSymlinkArgs {
#[arg(value_hint = clap::ValueHint::FilePath)]
path: String,
id: String,
}
#[derive(clap::Args, Clone, Debug)]
#[command(group(clap::ArgGroup::new("target").required(true)))]
pub struct DebugObjectTreeArgs {
#[arg(value_hint = clap::ValueHint::DirPath)]
dir: String,
#[arg(group = "target")]
id: Option<String>,
#[arg(long, short, group = "target")]
revision: Option<RevisionArg>,
}
#[derive(clap::Args, Clone, Debug)]
#[command(group(clap::ArgGroup::new("target").required(true)))]
pub struct DebugObjectViewArgs {
#[arg(group = "target")]
id: Option<String>,
#[arg(long, group = "target")]
op: Option<String>,
}
pub fn cmd_debug_object(
ui: &mut Ui,
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.
let workspace = command.load_workspace()?;
let repo_loader = workspace.repo_loader();
match args {
DebugObjectArgs::Commit(args) => {
let id = CommitId::try_from_hex(&args.id)
.ok_or_else(|| user_error("Invalid hex commit id"))?;
let commit = repo_loader.store().get_commit(&id)?;
writeln!(ui.stdout(), "{:#?}", commit.store_commit())?;
}
DebugObjectArgs::File(args) => {
let id =
FileId::try_from_hex(&args.id).ok_or_else(|| user_error("Invalid hex file id"))?;
let path = RepoPathBuf::from_internal_string(&args.path).map_err(user_error)?;
let mut contents = repo_loader.store().read_file(&path, &id).block_on()?;
let mut buf = vec![];
contents.read_to_end(&mut buf).block_on()?;
ui.stdout().write_all(&buf)?;
}
DebugObjectArgs::Operation(args) => {
let id = OperationId::try_from_hex(&args.id)
.ok_or_else(|| user_error("Invalid hex operation id"))?;
let operation = repo_loader.op_store().read_operation(&id).block_on()?;
writeln!(ui.stdout(), "{operation:#?}")?;
}
DebugObjectArgs::Symlink(args) => {
let id = SymlinkId::try_from_hex(&args.id)
.ok_or_else(|| user_error("Invalid hex symlink id"))?;
let path = RepoPathBuf::from_internal_string(&args.path).map_err(user_error)?;
let target = repo_loader.store().read_symlink(&path, &id).block_on()?;
writeln!(ui.stdout(), "{target}")?;
}
DebugObjectArgs::Tree(args) => {
let dir = RepoPathBuf::from_internal_string(&args.dir).map_err(user_error)?;
let id = if let Some(rev) = &args.revision {
let workspace_command = command.workspace_helper_no_snapshot(ui)?;
let commit = workspace_command.resolve_single_rev(ui, rev)?;
let tree_value = commit.tree().path_value(&dir)?;
if let Some(Some(TreeValue::Tree(id))) = tree_value.as_resolved() {
id.clone()
} else {
return Err(user_error("The path is not a single tree in the commit"));
}
} else {
TreeId::try_from_hex(args.id.as_ref().unwrap())
.ok_or_else(|| user_error("Invalid hex tree id"))?
};
let tree = repo_loader.store().get_tree(dir, &id)?;
writeln!(ui.stdout(), "{:#?}", tree.data())?;
}
DebugObjectArgs::View(args) => {
let id = if let Some(op_string) = &args.op {
let workspace_command = command.workspace_helper_no_snapshot(ui)?;
let op = workspace_command.resolve_single_op(op_string)?;
op.view_id().clone()
} else {
ViewId::try_from_hex(args.id.as_ref().unwrap())
.ok_or_else(|| user_error("Invalid hex view id"))?
};
let view = repo_loader.op_store().read_view(&id).block_on()?;
writeln!(ui.stdout(), "{view:#?}")?;
}
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/reindex.rs | cli/src/commands/debug/reindex.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use jj_lib::default_index::DefaultIndexStore;
use pollster::FutureExt as _;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::internal_error;
use crate::command_error::user_error;
use crate::ui::Ui;
/// Rebuild commit index
#[derive(clap::Args, Clone, Debug)]
pub struct DebugReindexArgs {}
pub fn cmd_debug_reindex(
ui: &mut Ui,
command: &CommandHelper,
_args: &DebugReindexArgs,
) -> Result<(), CommandError> {
// Resolve the operation without loading the repo. The index might have to
// be rebuilt while loading the repo.
let workspace = command.load_workspace()?;
let repo_loader = workspace.repo_loader();
let op = command.resolve_operation(ui, repo_loader)?;
let index_store = repo_loader.index_store();
if let Some(default_index_store) = index_store.downcast_ref::<DefaultIndexStore>() {
default_index_store.reinit().map_err(internal_error)?;
let default_index = default_index_store
.build_index_at_operation(&op, repo_loader.store())
.block_on()
.map_err(internal_error)?;
writeln!(
ui.status(),
"Finished indexing {} commits.",
default_index.num_commits()
)?;
} else {
return Err(user_error(format!(
"Cannot reindex indexes of type '{}'",
index_store.name()
)));
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/index.rs | cli/src/commands/debug/index.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use jj_lib::default_index::DefaultReadonlyIndex;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::internal_error;
use crate::command_error::user_error;
use crate::ui::Ui;
/// Show commit index stats
#[derive(clap::Args, Clone, Debug)]
pub struct DebugIndexArgs {}
pub fn cmd_debug_index(
ui: &mut Ui,
command: &CommandHelper,
_args: &DebugIndexArgs,
) -> Result<(), CommandError> {
// Resolve the operation without loading the repo, so this command won't
// update the index.
let workspace = command.load_workspace()?;
let repo_loader = workspace.repo_loader();
let op = command.resolve_operation(ui, repo_loader)?;
let index_store = repo_loader.index_store();
let index = index_store
.get_index_at_op(&op, repo_loader.store())
.map_err(internal_error)?;
if let Some(default_index) = index.downcast_ref::<DefaultReadonlyIndex>() {
let stats = default_index.stats();
writeln!(ui.stdout(), "=== Commits ===")?;
writeln!(ui.stdout(), "Number of commits: {}", stats.num_commits)?;
writeln!(ui.stdout(), "Number of merges: {}", stats.num_merges)?;
writeln!(
ui.stdout(),
"Max generation number: {}",
stats.max_generation_number
)?;
writeln!(ui.stdout(), "Number of heads: {}", stats.num_heads)?;
writeln!(ui.stdout(), "Number of changes: {}", stats.num_changes)?;
writeln!(ui.stdout(), "Stats per level:")?;
for (i, level) in stats.commit_levels.iter().enumerate() {
writeln!(ui.stdout(), " Level {i}:")?;
writeln!(ui.stdout(), " Number of commits: {}", level.num_commits)?;
writeln!(ui.stdout(), " Name: {}", level.name)?;
}
writeln!(ui.stdout(), "=== Changed paths ===")?;
if let Some(range) = &stats.changed_path_commits_range {
writeln!(ui.stdout(), "Indexed commits: {range:?}")?;
} else {
writeln!(ui.stdout(), "Indexed commits: none")?;
}
writeln!(ui.stdout(), "Stats per level:")?;
for (i, level) in stats.changed_path_levels.iter().enumerate() {
writeln!(ui.stdout(), " Level {i}:")?;
writeln!(ui.stdout(), " Number of commits: {}", level.num_commits)?;
writeln!(
ui.stdout(),
" Number of changed paths: {}",
level.num_changed_paths
)?;
writeln!(ui.stdout(), " Number of paths: {}", level.num_paths)?;
writeln!(ui.stdout(), " Name: {}", level.name)?;
}
} else {
return Err(user_error(format!(
"Cannot get stats for indexes of type '{}'",
index_store.name()
)));
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/stacked_table.rs | cli/src/commands/debug/stacked_table.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::Write as _;
use std::path::PathBuf;
use itertools::Itertools as _;
use jj_lib::stacked_table::TableSegment as _;
use jj_lib::stacked_table::TableStore;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error_with_message;
use crate::ui::Ui;
/// Show stats of stacked table
#[derive(clap::Args, Clone, Debug)]
pub struct DebugStackedTableArgs {
/// Path to table store directory
#[arg(value_hint = clap::ValueHint::DirPath)]
dir: String,
/// Key size in bytes
#[arg(long, short = 'n')]
key_size: usize,
}
pub fn cmd_debug_stacked_table(
ui: &mut Ui,
_command: &CommandHelper,
args: &DebugStackedTableArgs,
) -> Result<(), CommandError> {
let store = TableStore::load(PathBuf::from(&args.dir), args.key_size);
let table = store
.get_head()
.map_err(|err| user_error_with_message("Failed to load stacked table", err))?;
let mut table_segments = table.ancestor_segments().collect_vec();
table_segments.reverse();
let total_num_entries: usize = table_segments
.iter()
.map(|table| table.segment_num_entries())
.sum();
writeln!(ui.stdout(), "Number of entries: {total_num_entries}")?;
writeln!(ui.stdout(), "Stats per level:")?;
for (i, table) in table_segments.iter().enumerate() {
writeln!(ui.stdout(), " Level {i}:")?;
writeln!(
ui.stdout(),
" Number of entries: {}",
table.segment_num_entries()
)?;
writeln!(ui.stdout(), " Name: {}", table.name())?;
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/template.rs | cli/src/commands/debug/template.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::template_parser;
use crate::ui::Ui;
/// Parse a template
#[derive(clap::Args, Clone, Debug)]
pub struct DebugTemplateArgs {
template: String,
}
pub fn cmd_debug_template(
ui: &mut Ui,
_command: &CommandHelper,
args: &DebugTemplateArgs,
) -> Result<(), CommandError> {
let node = template_parser::parse_template(&args.template)?;
writeln!(ui.stdout(), "{node:#?}")?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/fileset.rs | cli/src/commands/debug/fileset.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use jj_lib::fileset;
use jj_lib::fileset::FilesetDiagnostics;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::print_parse_diagnostics;
use crate::ui::Ui;
/// Parse fileset expression
#[derive(clap::Args, Clone, Debug)]
pub struct DebugFilesetArgs {
#[arg(value_hint = clap::ValueHint::AnyPath)]
path: String,
}
pub fn cmd_debug_fileset(
ui: &mut Ui,
command: &CommandHelper,
args: &DebugFilesetArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let path_converter = workspace_command.path_converter();
let mut diagnostics = FilesetDiagnostics::new();
let expression = fileset::parse_maybe_bare(&mut diagnostics, &args.path, path_converter)?;
print_parse_diagnostics(ui, "In fileset expression", &diagnostics)?;
writeln!(ui.stdout(), "-- Parsed:")?;
writeln!(ui.stdout(), "{expression:#?}")?;
writeln!(ui.stdout())?;
let matcher = expression.to_matcher();
writeln!(ui.stdout(), "-- Matcher:")?;
writeln!(ui.stdout(), "{matcher:#?}")?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/tree.rs | cli/src/commands/debug/tree.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use jj_lib::backend::BackendResult;
use jj_lib::backend::TreeId;
use jj_lib::merge::Merge;
use jj_lib::merge::MergedTreeValue;
use jj_lib::repo::Repo as _;
use jj_lib::repo_path::RepoPathBuf;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::ui::Ui;
/// List the recursive entries of a tree.
#[derive(clap::Args, Clone, Debug)]
pub struct DebugTreeArgs {
#[arg(long, short = 'r', value_name = "REVSET")]
revision: Option<RevisionArg>,
#[arg(long, conflicts_with = "revision")]
id: Option<String>,
#[arg(long, requires = "id")]
dir: Option<String>,
#[arg(value_name = "FILESETS")]
paths: Vec<String>,
// TODO: Add an option to include trees that are ancestors of the matched paths
}
pub fn cmd_debug_tree(
ui: &mut Ui,
command: &CommandHelper,
args: &DebugTreeArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let matcher = workspace_command
.parse_file_patterns(ui, &args.paths)?
.to_matcher();
let entries: Box<dyn Iterator<Item = (RepoPathBuf, BackendResult<MergedTreeValue>)>> =
if let Some(tree_id_hex) = &args.id {
let tree_id =
TreeId::try_from_hex(tree_id_hex).ok_or_else(|| user_error("Invalid tree id"))?;
let dir = if let Some(dir_str) = &args.dir {
workspace_command.parse_file_path(dir_str)?
} else {
RepoPathBuf::root()
};
let store = workspace_command.repo().store();
let tree = store.get_tree(dir, &tree_id)?;
// 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)))),
)
} else {
let commit = workspace_command
.resolve_single_rev(ui, args.revision.as_ref().unwrap_or(&RevisionArg::AT))?;
let tree = commit.tree();
Box::new(tree.entries_matching(matcher.as_ref()))
};
for (path, value) in entries {
let ui_path = workspace_command.format_file_path(&path);
writeln!(ui.stdout(), "{ui_path}: {value:?}")?;
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/local_working_copy.rs | cli/src/commands/debug/local_working_copy.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use jj_lib::working_copy::WorkingCopy as _;
use super::check_local_disk_wc;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// Show information about the local working copy state
///
/// This command only works with a standard local-disk working copy.
#[derive(clap::Args, Clone, Debug)]
pub struct DebugLocalWorkingCopyArgs {}
pub fn cmd_debug_local_working_copy(
ui: &mut Ui,
command: &CommandHelper,
_args: &DebugLocalWorkingCopyArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let wc = check_local_disk_wc(workspace_command.working_copy())?;
writeln!(ui.stdout(), "Current operation: {:?}", wc.operation_id())?;
writeln!(ui.stdout(), "Current tree: {:?}", wc.tree()?)?;
for (file, state) in wc.file_states()? {
writeln!(
ui.stdout(),
"{:?} {:13?} {:10?} {:?} {:?}",
state.file_type,
state.size,
state.mtime.0,
state.materialized_conflict_data,
file
)?;
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/revset.rs | cli/src/commands/debug/revset.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use jj_lib::object_id::ObjectId as _;
use jj_lib::revset;
use jj_lib::revset::RevsetDiagnostics;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::print_parse_diagnostics;
use crate::revset_util;
use crate::ui::Ui;
/// Evaluate revset to full commit IDs
#[derive(clap::Args, Clone, Debug)]
pub struct DebugRevsetArgs {
revision: String,
/// Do not resolve and evaluate expression
#[arg(long)]
no_resolve: bool,
/// Do not rewrite expression to optimized form
#[arg(long)]
no_optimize: bool,
}
pub fn cmd_debug_revset(
ui: &mut Ui,
command: &CommandHelper,
args: &DebugRevsetArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let workspace_ctx = workspace_command.env().revset_parse_context();
let repo = workspace_command.repo().as_ref();
let mut diagnostics = RevsetDiagnostics::new();
let expression = revset::parse(&mut diagnostics, &args.revision, &workspace_ctx)?;
print_parse_diagnostics(ui, "In revset expression", &diagnostics)?;
writeln!(ui.stdout(), "-- Parsed:")?;
writeln!(ui.stdout(), "{expression:#?}")?;
writeln!(ui.stdout())?;
if args.no_resolve && args.no_optimize {
return Ok(());
} else if args.no_resolve {
let expression = revset::optimize(expression);
writeln!(ui.stdout(), "-- Optimized:")?;
writeln!(ui.stdout(), "{expression:#?}")?;
writeln!(ui.stdout())?;
return Ok(());
}
let symbol_resolver = revset_util::default_symbol_resolver(
repo,
command.revset_extensions().symbol_resolvers(),
workspace_command.id_prefix_context(),
);
let mut expression = expression.resolve_user_expression(repo, &symbol_resolver)?;
writeln!(ui.stdout(), "-- Resolved:")?;
writeln!(ui.stdout(), "{expression:#?}")?;
writeln!(ui.stdout())?;
if !args.no_optimize {
expression = revset::optimize(expression);
writeln!(ui.stdout(), "-- Optimized:")?;
writeln!(ui.stdout(), "{expression:#?}")?;
writeln!(ui.stdout())?;
}
let backend_expression = expression.to_backend_expression(repo);
writeln!(ui.stdout(), "-- Backend:")?;
writeln!(ui.stdout(), "{backend_expression:#?}")?;
writeln!(ui.stdout())?;
let revset = expression.evaluate_unoptimized(repo)?;
writeln!(ui.stdout(), "-- Evaluated:")?;
writeln!(ui.stdout(), "{revset:#?}")?;
writeln!(ui.stdout())?;
writeln!(ui.stdout(), "-- Commit IDs:")?;
for commit_id in revset.iter() {
writeln!(ui.stdout(), "{}", commit_id?.hex())?;
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/index_changed_paths.rs | cli/src/commands/debug/index_changed_paths.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use jj_lib::default_index::DefaultIndexStore;
use jj_lib::repo::Repo as _;
use pollster::FutureExt as _;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::internal_error;
use crate::command_error::user_error;
use crate::ui::Ui;
/// Build changed-path index
#[derive(clap::Args, Clone, Debug)]
pub struct DebugIndexChangedPathsArgs {
/// Limit number of revisions to index
#[arg(long, short = 'n', default_value_t = u32::MAX)]
limit: u32,
}
pub fn cmd_debug_index_changed_paths(
ui: &mut Ui,
command: &CommandHelper,
args: &DebugIndexChangedPathsArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo();
let repo_loader = workspace_command.workspace().repo_loader();
let index_store = repo_loader.index_store();
let Some(default_index_store) = index_store.downcast_ref::<DefaultIndexStore>() else {
return Err(user_error(format!(
"Unsupported index type '{}'",
index_store.name()
)));
};
let index = default_index_store
.build_changed_path_index_at_operation(repo.op_id(), repo.store(), args.limit)
.block_on()
.map_err(internal_error)?;
let stats = index.stats();
writeln!(
ui.status(),
"Finished indexing {:?} commits.",
stats.changed_path_commits_range.unwrap()
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/copy_detection.rs | cli/src/commands/debug/copy_detection.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use futures::executor::block_on_stream;
use jj_lib::backend::CopyRecord;
use jj_lib::repo::Repo as _;
use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// Show information about file copies detected
#[derive(clap::Args, Clone, Debug)]
pub struct CopyDetectionArgs {
/// Show file copies detected in changed files in this revision, compared to
/// its parent(s)
#[arg(default_value = "@", value_name = "REVSET")]
revision: RevisionArg,
}
pub fn cmd_debug_copy_detection(
ui: &mut Ui,
command: &CommandHelper,
args: &CopyDetectionArgs,
) -> Result<(), CommandError> {
let ws = command.workspace_helper(ui)?;
let store = ws.repo().store();
let commit = ws.resolve_single_rev(ui, &args.revision)?;
for parent_id in commit.parent_ids() {
for CopyRecord { target, source, .. } in
block_on_stream(store.get_copy_records(None, parent_id, commit.id())?)
.filter_map(|r| r.ok())
{
writeln!(
ui.stdout(),
"{} -> {}",
source.as_internal_file_string(),
target.as_internal_file_string()
)?;
}
}
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/mod.rs | cli/src/commands/debug/mod.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod copy_detection;
mod fileset;
mod index;
mod index_changed_paths;
mod init_simple;
mod local_working_copy;
mod object;
mod reindex;
mod revset;
mod snapshot;
mod stacked_table;
mod template;
mod tree;
mod watchman;
mod working_copy;
use clap::Subcommand;
use jj_lib::local_working_copy::LocalWorkingCopy;
use jj_lib::working_copy::WorkingCopy;
use self::copy_detection::CopyDetectionArgs;
use self::copy_detection::cmd_debug_copy_detection;
use self::fileset::DebugFilesetArgs;
use self::fileset::cmd_debug_fileset;
use self::index::DebugIndexArgs;
use self::index::cmd_debug_index;
use self::index_changed_paths::DebugIndexChangedPathsArgs;
use self::index_changed_paths::cmd_debug_index_changed_paths;
use self::init_simple::DebugInitSimpleArgs;
use self::init_simple::cmd_debug_init_simple;
use self::local_working_copy::DebugLocalWorkingCopyArgs;
use self::local_working_copy::cmd_debug_local_working_copy;
use self::object::DebugObjectArgs;
use self::object::cmd_debug_object;
use self::reindex::DebugReindexArgs;
use self::reindex::cmd_debug_reindex;
use self::revset::DebugRevsetArgs;
use self::revset::cmd_debug_revset;
use self::snapshot::DebugSnapshotArgs;
use self::snapshot::cmd_debug_snapshot;
use self::stacked_table::DebugStackedTableArgs;
use self::stacked_table::cmd_debug_stacked_table;
use self::template::DebugTemplateArgs;
use self::template::cmd_debug_template;
use self::tree::DebugTreeArgs;
use self::tree::cmd_debug_tree;
use self::watchman::DebugWatchmanCommand;
use self::watchman::cmd_debug_watchman;
use self::working_copy::DebugWorkingCopyArgs;
use self::working_copy::cmd_debug_working_copy;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::ui::Ui;
/// Low-level commands not intended for users
#[derive(Subcommand, Clone, Debug)]
#[command(hide = true)]
pub enum DebugCommand {
CopyDetection(CopyDetectionArgs),
Fileset(DebugFilesetArgs),
Index(DebugIndexArgs),
IndexChangedPaths(DebugIndexChangedPathsArgs),
InitSimple(DebugInitSimpleArgs),
LocalWorkingCopy(DebugLocalWorkingCopyArgs),
#[command(subcommand)]
Object(DebugObjectArgs),
Reindex(DebugReindexArgs),
Revset(DebugRevsetArgs),
Snapshot(DebugSnapshotArgs),
StackedTable(DebugStackedTableArgs),
Template(DebugTemplateArgs),
Tree(DebugTreeArgs),
#[command(subcommand)]
Watchman(DebugWatchmanCommand),
WorkingCopy(DebugWorkingCopyArgs),
}
pub fn cmd_debug(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &DebugCommand,
) -> Result<(), CommandError> {
match subcommand {
DebugCommand::CopyDetection(args) => cmd_debug_copy_detection(ui, command, args),
DebugCommand::Fileset(args) => cmd_debug_fileset(ui, command, args),
DebugCommand::Index(args) => cmd_debug_index(ui, command, args),
DebugCommand::IndexChangedPaths(args) => cmd_debug_index_changed_paths(ui, command, args),
DebugCommand::InitSimple(args) => cmd_debug_init_simple(ui, command, args),
DebugCommand::LocalWorkingCopy(args) => cmd_debug_local_working_copy(ui, command, args),
DebugCommand::Object(args) => cmd_debug_object(ui, command, args),
DebugCommand::Reindex(args) => cmd_debug_reindex(ui, command, args),
DebugCommand::Revset(args) => cmd_debug_revset(ui, command, args),
DebugCommand::Snapshot(args) => cmd_debug_snapshot(ui, command, args),
DebugCommand::StackedTable(args) => cmd_debug_stacked_table(ui, command, args),
DebugCommand::Template(args) => cmd_debug_template(ui, command, args),
DebugCommand::Tree(args) => cmd_debug_tree(ui, command, args),
DebugCommand::Watchman(args) => cmd_debug_watchman(ui, command, args),
DebugCommand::WorkingCopy(args) => cmd_debug_working_copy(ui, command, args),
}
}
fn check_local_disk_wc(x: &dyn WorkingCopy) -> Result<&LocalWorkingCopy, CommandError> {
x.downcast_ref()
.ok_or_else(|| user_error("This command requires a standard local-disk working copy"))
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/init_simple.rs | cli/src/commands/debug/init_simple.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::Write as _;
use jj_lib::file_util;
use jj_lib::workspace::Workspace;
use tracing::instrument;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::command_error::cli_error;
use crate::command_error::user_error_with_message;
use crate::ui::Ui;
/// Create a new repo in the given directory using the proof-of-concept simple
/// backend
///
/// The simple backend does not support cloning, fetching, or pushing.
///
/// This command is otherwise analogous to `jj git init`. If the given directory
/// does not exist, it will be created. If no directory is given, the current
/// directory is used.
#[derive(clap::Args, Clone, Debug)]
pub(crate) struct DebugInitSimpleArgs {
/// The destination directory
#[arg(default_value = ".", value_hint = clap::ValueHint::DirPath)]
destination: String,
}
#[instrument(skip_all)]
pub(crate) fn cmd_debug_init_simple(
ui: &mut Ui,
command: &CommandHelper,
args: &DebugInitSimpleArgs,
) -> Result<(), CommandError> {
if command.global_args().ignore_working_copy {
return Err(cli_error("--ignore-working-copy is not respected"));
}
if command.global_args().at_operation.is_some() {
return Err(cli_error("--at-op is not respected"));
}
let cwd = command.cwd();
let wc_path = cwd.join(&args.destination);
let wc_path = file_util::create_or_reuse_dir(&wc_path)
.and_then(|_| dunce::canonicalize(wc_path))
.map_err(|e| user_error_with_message("Failed to create workspace", e))?;
Workspace::init_simple(&command.settings_for_new_workspace(&wc_path)?, &wc_path)?;
let relative_wc_path = file_util::relative_path(cwd, &wc_path);
writeln!(
ui.status(),
"Initialized repo in \"{}\"",
relative_wc_path.display()
)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/working_copy.rs | cli/src/commands/debug/working_copy.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::io::Write as _;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// Show information about the working copy state
#[derive(clap::Args, Clone, Debug)]
pub struct DebugWorkingCopyArgs {}
pub fn cmd_debug_working_copy(
ui: &mut Ui,
command: &CommandHelper,
_args: &DebugWorkingCopyArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper_no_snapshot(ui)?;
let wc = workspace_command.working_copy();
writeln!(ui.stdout(), "Type: {:?}", wc.name())?;
writeln!(ui.stdout(), "Current operation: {:?}", wc.operation_id())?;
writeln!(ui.stdout(), "Current tree: {:?}", wc.tree()?)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/commands/debug/snapshot.rs | cli/src/commands/debug/snapshot.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use crate::cli_util::CommandHelper;
use crate::command_error::CommandError;
use crate::ui::Ui;
/// Trigger a snapshot in the op log
#[derive(clap::Args, Clone, Debug)]
pub struct DebugSnapshotArgs {}
pub fn cmd_debug_snapshot(
ui: &mut Ui,
command: &CommandHelper,
_args: &DebugSnapshotArgs,
) -> Result<(), CommandError> {
// workspace helper will snapshot as needed
command.workspace_helper(ui)?;
Ok(())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/merge_tools/external.rs | cli/src/merge_tools/external.rs | use std::collections::HashMap;
use std::io;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::process::ExitStatus;
use std::process::Stdio;
use std::sync::Arc;
use bstr::BString;
use itertools::Itertools as _;
use jj_lib::backend::CopyId;
use jj_lib::backend::TreeValue;
use jj_lib::conflicts;
use jj_lib::conflicts::ConflictMarkerStyle;
use jj_lib::conflicts::ConflictMaterializeOptions;
use jj_lib::conflicts::MIN_CONFLICT_MARKER_LEN;
use jj_lib::conflicts::choose_materialized_conflict_marker_len;
use jj_lib::conflicts::materialize_merge_result_to_bytes;
use jj_lib::gitignore::GitIgnoreFile;
use jj_lib::matchers::Matcher;
use jj_lib::merge::Diff;
use jj_lib::merge::Merge;
use jj_lib::merged_tree::MergedTree;
use jj_lib::merged_tree::MergedTreeBuilder;
use jj_lib::repo_path::RepoPathUiConverter;
use jj_lib::store::Store;
use pollster::FutureExt as _;
use thiserror::Error;
use super::ConflictResolveError;
use super::DiffEditError;
use super::DiffGenerateError;
use super::MergeToolFile;
use super::MergeToolPartialResolutionError;
use super::diff_working_copies::DiffEditWorkingCopies;
use super::diff_working_copies::DiffType;
use super::diff_working_copies::check_out_trees;
use super::diff_working_copies::new_utf8_temp_dir;
use super::diff_working_copies::set_readonly_recursively;
use crate::config::CommandNameAndArgs;
use crate::config::find_all_variables;
use crate::config::interpolate_variables;
use crate::ui::Ui;
/// Merge/diff tool loaded from the settings.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct ExternalMergeTool {
/// Program to execute. Must be defined; defaults to the tool name
/// if not specified in the config.
pub program: String,
/// Arguments to pass to the program when generating diffs.
/// `$left` and `$right` are replaced with the corresponding directories.
pub diff_args: Vec<String>,
/// Exit codes to be treated as success when generating diffs.
pub diff_expected_exit_codes: Vec<i32>,
/// Whether to execute the tool with a pair of directories or individual
/// files.
pub diff_invocation_mode: DiffToolMode,
/// Whether to execute the tool in the temporary diff directory
pub diff_do_chdir: bool,
/// Arguments to pass to the program when editing diffs.
/// `$left` and `$right` are replaced with the corresponding directories.
pub edit_args: Vec<String>,
/// Arguments to pass to the program when resolving 3-way conflicts.
/// `$left`, `$right`, `$base`, and `$output` are replaced with
/// paths to the corresponding files.
pub merge_args: Vec<String>,
/// By default, if a merge tool exits with a non-zero exit code, then the
/// merge will be canceled. Some merge tools allow leaving some conflicts
/// unresolved, in which case they will be left as conflict markers in the
/// output file. In that case, the merge tool may exit with a non-zero exit
/// code to indicate that not all conflicts were resolved. Adding an exit
/// code to this array will tell `jj` to interpret that exit code as
/// indicating that the `$output` file should contain conflict markers.
pub merge_conflict_exit_codes: Vec<i32>,
/// If false (default), the `$output` file starts out empty and is accepted
/// as a full conflict resolution as-is by `jj` after the merge tool is
/// done with it. If true, the `$output` file starts out with the
/// contents of the conflict, with the configured conflict markers. After
/// the merge tool is done, any remaining conflict markers in the
/// file are parsed and taken to mean that the conflict was only partially
/// resolved.
pub merge_tool_edits_conflict_markers: bool,
/// If provided, overrides the normal conflict marker style setting. This is
/// useful if a tool parses conflict markers, and so it requires a specific
/// format, or if a certain format is more readable than another.
pub conflict_marker_style: Option<ConflictMarkerStyle>,
}
#[derive(serde::Deserialize, Copy, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum DiffToolMode {
/// Invoke the diff tool on a temp directory of the modified files.
Dir,
/// Invoke the diff tool on each of the modified files individually.
FileByFile,
}
impl Default for ExternalMergeTool {
fn default() -> Self {
Self {
program: String::new(),
// TODO(ilyagr): There should be a way to explicitly specify that a
// certain tool (e.g. vscode as of this writing) cannot be used as a
// diff editor (or a diff tool). A possible TOML syntax would be
// `edit-args = false`, or `edit-args = []`, or `edit = { disabled =
// true }` to go with `edit = { args = [...] }`.
diff_args: ["$left", "$right"].map(ToOwned::to_owned).to_vec(),
diff_expected_exit_codes: vec![0],
edit_args: ["$left", "$right"].map(ToOwned::to_owned).to_vec(),
merge_args: vec![],
merge_conflict_exit_codes: vec![],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
diff_do_chdir: true,
diff_invocation_mode: DiffToolMode::Dir,
}
}
}
impl ExternalMergeTool {
pub fn with_program(program: impl Into<String>) -> Self {
Self {
program: program.into(),
..Default::default()
}
}
pub fn with_diff_args(command_args: &CommandNameAndArgs) -> Self {
Self::with_args_inner(command_args, |tool| &mut tool.diff_args)
}
pub fn with_edit_args(command_args: &CommandNameAndArgs) -> Self {
Self::with_args_inner(command_args, |tool| &mut tool.edit_args)
}
pub fn with_merge_args(command_args: &CommandNameAndArgs) -> Self {
Self::with_args_inner(command_args, |tool| &mut tool.merge_args)
}
fn with_args_inner(
command_args: &CommandNameAndArgs,
get_mut_args: impl FnOnce(&mut Self) -> &mut Vec<String>,
) -> Self {
let (name, args) = command_args.split_name_and_args();
let mut tool = Self {
program: name.into_owned(),
..Default::default()
};
if !args.is_empty() {
*get_mut_args(&mut tool) = args.to_vec();
}
tool
}
}
#[derive(Debug, Error)]
pub enum ExternalToolError {
#[error("Error setting up temporary directory")]
SetUpDir(#[source] std::io::Error),
// TODO: Remove the "(run with --debug to see the exact invocation)"
// from this and other errors. Print it as a hint but only if --debug is *not* set.
#[error("Error executing '{tool_binary}' (run with --debug to see the exact invocation)")]
FailedToExecute {
tool_binary: String,
#[source]
source: std::io::Error,
},
#[error("Tool exited with {exit_status} (run with --debug to see the exact invocation)")]
ToolAborted { exit_status: ExitStatus },
#[error(
"Tool exited with {exit_status}, but did not produce valid conflict markers (run with \
--debug to see the exact invocation)"
)]
InvalidConflictMarkers { exit_status: ExitStatus },
#[error("I/O error")]
Io(#[source] std::io::Error),
}
fn run_mergetool_external_single_file(
editor: &ExternalMergeTool,
store: &Store,
merge_tool_file: &MergeToolFile,
default_conflict_marker_style: ConflictMarkerStyle,
tree_builder: &mut MergedTreeBuilder,
) -> Result<(), ConflictResolveError> {
let MergeToolFile {
repo_path,
conflict,
file,
} = merge_tool_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.
let conflict_marker_len = if editor.merge_tool_edits_conflict_markers || uses_marker_length {
choose_materialized_conflict_marker_len(&file.contents)
} else {
MIN_CONFLICT_MARKER_LEN
};
let initial_output_content = if editor.merge_tool_edits_conflict_markers {
let options = ConflictMaterializeOptions {
marker_style: editor
.conflict_marker_style
.unwrap_or(default_conflict_marker_style),
marker_len: Some(conflict_marker_len),
merge: store.merge_options().clone(),
};
materialize_merge_result_to_bytes(&file.contents, &file.labels, &options)
} else {
BString::default()
};
assert_eq!(file.contents.num_sides(), 2);
let files: HashMap<&str, &[u8]> = maplit::hashmap! {
"base" => file.contents.get_remove(0).unwrap().as_slice(),
"left" => file.contents.get_add(0).unwrap().as_slice(),
"right" => file.contents.get_add(1).unwrap().as_slice(),
"output" => initial_output_content.as_slice(),
};
let temp_dir = new_utf8_temp_dir("jj-resolve-").map_err(ExternalToolError::SetUpDir)?;
let suffix = if let Some(filename) = repo_path.components().next_back() {
let name = filename
.to_fs_name()
.map_err(|err| err.with_path(repo_path))?;
format!("_{name}")
} else {
// This should never actually trigger, but we support it just in case
// resolving the root path ever makes sense.
"".to_owned()
};
let mut variables: HashMap<&str, _> = files
.iter()
.map(|(role, contents)| -> Result<_, ConflictResolveError> {
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.
set_readonly_recursively(&path).map_err(ExternalToolError::SetUpDir)?;
}
Ok((
*role,
path.into_os_string()
.into_string()
.expect("temp_dir should be valid utf-8"),
))
})
.try_collect()?;
variables.insert("marker_length", conflict_marker_len.to_string());
variables.insert("path", repo_path.as_internal_file_string().to_string());
let mut cmd = Command::new(&editor.program);
cmd.args(interpolate_variables(&editor.merge_args, &variables));
tracing::info!(?cmd, "Invoking the external merge tool:");
let exit_status = cmd
.status()
.map_err(|e| ExternalToolError::FailedToExecute {
tool_binary: editor.program.clone(),
source: e,
})?;
tracing::info!(%exit_status);
// 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));
if !exit_status.success() && !exit_status_implies_conflict {
return Err(ConflictResolveError::from(ExternalToolError::ToolAborted {
exit_status,
}));
}
let output_file_contents: Vec<u8> =
std::fs::read(variables.get("output").unwrap()).map_err(ExternalToolError::Io)?;
if output_file_contents.is_empty() || output_file_contents == initial_output_content {
return Err(ConflictResolveError::EmptyOrUnchanged);
}
let new_file_ids = if editor.merge_tool_edits_conflict_markers || exit_status_implies_conflict {
tracing::info!(
?exit_status_implies_conflict,
"jj is reparsing output for conflicts, `merge-tool-edits-conflict-markers = {}` in \
TOML config;",
editor.merge_tool_edits_conflict_markers
);
conflicts::update_from_content(
&file.unsimplified_ids,
store,
repo_path,
output_file_contents.as_slice(),
conflict_marker_len,
)
.block_on()?
} else {
let new_file_id = store
.write_file(repo_path, &mut output_file_contents.as_slice())
.block_on()?;
Merge::normal(new_file_id)
};
// 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.
if exit_status_implies_conflict && new_file_ids.is_resolved() {
return Err(ConflictResolveError::ExternalTool(
ExternalToolError::InvalidConflictMarkers { exit_status },
));
}
let new_tree_value = match new_file_ids.into_resolved() {
Ok(file_id) => {
let executable = file.executable.expect("should have been resolved");
Merge::resolved(file_id.map(|id| TreeValue::File {
id,
executable,
copy_id: CopyId::placeholder(),
}))
}
// Update the file ids only, leaving the executable flags unchanged
Err(file_ids) => conflict.with_new_file_ids(&file_ids),
};
tree_builder.set_or_remove(repo_path.to_owned(), new_tree_value);
Ok(())
}
pub fn run_mergetool_external(
ui: &Ui,
path_converter: &RepoPathUiConverter,
editor: &ExternalMergeTool,
tree: &MergedTree,
merge_tool_files: &[MergeToolFile],
default_conflict_marker_style: ConflictMarkerStyle,
) -> Result<(MergedTree, Option<MergeToolPartialResolutionError>), ConflictResolveError> {
// TODO: add support for "dir" invocation mode, similar to the
// "diff-invocation-mode" config option for diffs
let mut tree_builder = MergedTreeBuilder::new(tree.clone());
let mut partial_resolution_error = None;
for (i, merge_tool_file) in merge_tool_files.iter().enumerate() {
writeln!(
ui.status(),
"Resolving conflicts in: {}",
path_converter.format_file_path(&merge_tool_file.repo_path)
)?;
match run_mergetool_external_single_file(
editor,
tree.store(),
merge_tool_file,
default_conflict_marker_style,
&mut tree_builder,
) {
Ok(()) => {}
Err(err) if i == 0 => {
// If the first resolution fails, just return the error normally
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.
partial_resolution_error = Some(MergeToolPartialResolutionError {
source: err,
resolved_count: i,
});
break;
}
}
}
let new_tree = tree_builder.write_tree()?;
Ok((new_tree, partial_resolution_error))
}
pub fn edit_diff_external(
editor: &ExternalMergeTool,
trees: Diff<&MergedTree>,
matcher: &dyn Matcher,
instructions: Option<&str>,
base_ignores: Arc<GitIgnoreFile>,
default_conflict_marker_style: ConflictMarkerStyle,
) -> Result<MergedTree, DiffEditError> {
let conflict_marker_style = editor
.conflict_marker_style
.unwrap_or(default_conflict_marker_style);
let got_output_field = find_all_variables(&editor.edit_args).contains(&"output");
let diff_type = if got_output_field {
DiffType::ThreeWay
} else {
DiffType::TwoWay
};
let diffedit_wc = DiffEditWorkingCopies::check_out(
trees,
matcher,
diff_type,
instructions,
conflict_marker_style,
)?;
let patterns = diffedit_wc.working_copies.to_command_variables(false);
let mut cmd = Command::new(&editor.program);
cmd.args(interpolate_variables(&editor.edit_args, &patterns));
tracing::info!(?cmd, "Invoking the external diff editor:");
let exit_status = cmd
.status()
.map_err(|e| ExternalToolError::FailedToExecute {
tool_binary: editor.program.clone(),
source: e,
})?;
if !exit_status.success() {
return Err(DiffEditError::from(ExternalToolError::ToolAborted {
exit_status,
}));
}
diffedit_wc.snapshot_results(base_ignores)
}
/// Generates textual diff by the specified `tool` and writes into `writer`.
pub fn generate_diff(
ui: &Ui,
writer: &mut dyn Write,
trees: Diff<&MergedTree>,
matcher: &dyn Matcher,
tool: &ExternalMergeTool,
default_conflict_marker_style: ConflictMarkerStyle,
width: usize,
) -> Result<(), DiffGenerateError> {
let conflict_marker_style = tool
.conflict_marker_style
.unwrap_or(default_conflict_marker_style);
let diff_wc = check_out_trees(trees, matcher, DiffType::TwoWay, conflict_marker_style)?;
diff_wc.set_left_readonly()?;
diff_wc.set_right_readonly()?;
let mut patterns = diff_wc.to_command_variables(true);
patterns.insert("width", width.to_string());
invoke_external_diff(ui, writer, tool, diff_wc.temp_dir(), &patterns)
}
/// Invokes the specified `tool` directing its output into `writer`.
pub fn invoke_external_diff(
ui: &Ui,
writer: &mut dyn Write,
tool: &ExternalMergeTool,
diff_dir: &Path,
patterns: &HashMap<&str, String>,
) -> Result<(), DiffGenerateError> {
// TODO: Somehow propagate --color to the external command?
let mut cmd = Command::new(&tool.program);
let mut patterns = patterns.clone();
if !tool.diff_do_chdir {
let absolute_left_path = Path::new(diff_dir).join(&patterns["left"]);
let absolute_right_path = Path::new(diff_dir).join(&patterns["right"]);
patterns.insert(
"left",
absolute_left_path
.into_os_string()
.into_string()
.expect("temp_dir should be valid utf-8"),
);
patterns.insert(
"right",
absolute_right_path
.into_os_string()
.into_string()
.expect("temp_dir should be valid utf-8"),
);
} else {
cmd.current_dir(diff_dir);
}
cmd.args(interpolate_variables(&tool.diff_args, &patterns));
tracing::info!(?cmd, "Invoking the external diff generator:");
let mut child = cmd
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(ui.stderr_for_child().map_err(ExternalToolError::Io)?)
.spawn()
.map_err(|source| ExternalToolError::FailedToExecute {
tool_binary: tool.program.clone(),
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.
let exit_status = child.wait().map_err(ExternalToolError::Io)?;
tracing::info!(?cmd, ?exit_status, "The external diff generator exited:");
let exit_ok = exit_status
.code()
.is_some_and(|status| tool.diff_expected_exit_codes.contains(&status));
if !exit_ok {
writeln!(
ui.warning_default(),
"Tool exited with {exit_status} (run with --debug to see the exact invocation)",
)
.ok();
}
copy_result.map_err(ExternalToolError::Io)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_interpolate_variables() {
let patterns = maplit::hashmap! {
"left" => "LEFT",
"right" => "RIGHT",
"left_right" => "$left $right",
};
assert_eq!(
interpolate_variables(
&["$left", "$1", "$right", "$2"].map(ToOwned::to_owned),
&patterns
),
["LEFT", "$1", "RIGHT", "$2"],
);
// Option-like
assert_eq!(
interpolate_variables(&["-o$left$right".to_owned()], &patterns),
["-oLEFTRIGHT"],
);
// Sexp-like
assert_eq!(
interpolate_variables(&["($unknown $left $right)".to_owned()], &patterns),
["($unknown LEFT RIGHT)"],
);
// Not a word "$left"
assert_eq!(
interpolate_variables(&["$lefty".to_owned()], &patterns),
["$lefty"],
);
// Patterns in pattern: not expanded recursively
assert_eq!(
interpolate_variables(&["$left_right".to_owned()], &patterns),
["$left $right"],
);
}
#[test]
fn test_find_all_variables() {
assert_eq!(
find_all_variables(
&[
"$left",
"$right",
"--two=$1 and $2",
"--can-be-part-of-string=$output",
"$NOT_CAPITALS",
"--can-repeat=$right"
]
.map(ToOwned::to_owned),
)
.collect_vec(),
["left", "right", "1", "2", "output", "right"],
);
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/merge_tools/diff_working_copies.rs | cli/src/merge_tools/diff_working_copies.rs | use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::Write as _;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use futures::StreamExt as _;
use jj_lib::conflicts::ConflictMarkerStyle;
use jj_lib::fsmonitor::FsmonitorSettings;
use jj_lib::gitignore::GitIgnoreFile;
use jj_lib::local_working_copy::EolConversionMode;
use jj_lib::local_working_copy::ExecChangeSetting;
use jj_lib::local_working_copy::TreeState;
use jj_lib::local_working_copy::TreeStateError;
use jj_lib::local_working_copy::TreeStateSettings;
use jj_lib::matchers::EverythingMatcher;
use jj_lib::matchers::Matcher;
use jj_lib::matchers::NothingMatcher;
use jj_lib::merge::Diff;
use jj_lib::merged_tree::MergedTree;
use jj_lib::merged_tree::TreeDiffEntry;
use jj_lib::working_copy::CheckoutError;
use jj_lib::working_copy::SnapshotOptions;
use pollster::FutureExt as _;
use tempfile::TempDir;
use thiserror::Error;
use super::DiffEditError;
use super::external::ExternalToolError;
#[derive(Debug, Error)]
pub enum DiffCheckoutError {
#[error("Failed to write directories to diff")]
Checkout(#[from] CheckoutError),
#[error("Error setting up temporary directory")]
SetUpDir(#[source] std::io::Error),
#[error(transparent)]
TreeState(#[from] TreeStateError),
}
pub(crate) struct DiffWorkingCopies {
_temp_dir: TempDir, // Temp dir will be deleted when this is dropped
left: TreeState,
right: TreeState,
output: Option<TreeState>,
}
impl DiffWorkingCopies {
pub fn set_left_readonly(&self) -> Result<(), ExternalToolError> {
set_readonly_recursively(self.left.working_copy_path()).map_err(ExternalToolError::SetUpDir)
}
pub fn set_right_readonly(&self) -> Result<(), ExternalToolError> {
set_readonly_recursively(self.right.working_copy_path())
.map_err(ExternalToolError::SetUpDir)
}
pub fn temp_dir(&self) -> &Path {
self._temp_dir.path()
}
pub fn to_command_variables(&self, relative: bool) -> HashMap<&'static str, String> {
let mut left_wc_dir = self.left.working_copy_path();
let mut right_wc_dir = self.right.working_copy_path();
if relative {
left_wc_dir = left_wc_dir
.strip_prefix(self.temp_dir())
.expect("path should be relative to temp_dir");
right_wc_dir = right_wc_dir
.strip_prefix(self.temp_dir())
.expect("path should be relative to temp_dir");
}
let mut result = maplit::hashmap! {
"left" => left_wc_dir.to_str().expect("temp_dir should be valid utf-8").to_owned(),
"right" => right_wc_dir.to_str().expect("temp_dir should be valid utf-8").to_owned(),
};
if let Some(output_state) = &self.output {
result.insert(
"output",
output_state
.working_copy_path()
.to_str()
.expect("temp_dir should be valid utf-8")
.to_owned(),
);
}
result
}
}
pub(crate) fn new_utf8_temp_dir(prefix: &str) -> io::Result<TempDir> {
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
let message = format!("path {:?} is not valid UTF-8", temp_dir.path());
return Err(io::Error::new(io::ErrorKind::InvalidData, message));
}
Ok(temp_dir)
}
pub(crate) fn set_readonly_recursively(path: &Path) -> Result<(), std::io::Error> {
// 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()? {
set_readonly_recursively(&entry?.path())?;
}
Ok(())
} else if metadata.is_file() {
let mut perms = metadata.permissions();
perms.set_readonly(true);
std::fs::set_permissions(path, perms)
} else {
Ok(())
}
}
/// How to prepare tree states from the working copy for a diff viewer/editor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DiffType {
/// Prepare a left and right tree.
TwoWay,
/// Prepare left, right, and output trees.
ThreeWay,
}
/// Check out the two trees in temporary directories. Only include changed files
/// in the sparse checkout patterns.
pub(crate) fn check_out_trees(
trees: Diff<&MergedTree>,
matcher: &dyn Matcher,
diff_type: DiffType,
conflict_marker_style: ConflictMarkerStyle,
) -> Result<DiffWorkingCopies, DiffCheckoutError> {
let store = trees.before.store();
let changed_files: Vec<_> = trees
.before
.diff_stream(trees.after, matcher)
.map(|TreeDiffEntry { path, .. }| path)
.collect()
.block_on();
let temp_dir = new_utf8_temp_dir("jj-diff-").map_err(DiffCheckoutError::SetUpDir)?;
let temp_path = temp_dir.path();
// Checkout a tree into our temp directory with the given prefix.
let check_out = |name: &str, tree| -> Result<TreeState, DiffCheckoutError> {
let wc_path = temp_path.join(name);
let state_dir = temp_path.join(format!("{name}_state"));
std::fs::create_dir(&wc_path).map_err(DiffCheckoutError::SetUpDir)?;
std::fs::create_dir(&state_dir).map_err(DiffCheckoutError::SetUpDir)?;
let tree_state_settings = TreeStateSettings {
conflict_marker_style,
eol_conversion_mode: EolConversionMode::None,
exec_change_setting: ExecChangeSetting::Auto,
fsmonitor_settings: FsmonitorSettings::None,
};
let mut state = TreeState::init(store.clone(), wc_path, state_dir, &tree_state_settings)?;
state.set_sparse_patterns(changed_files.clone())?;
state.check_out(tree)?;
Ok(state)
};
let left = check_out("left", trees.before)?;
let right = check_out("right", trees.after)?;
let output = match diff_type {
DiffType::TwoWay => None,
DiffType::ThreeWay => Some(check_out("output", trees.after)?),
};
Ok(DiffWorkingCopies {
_temp_dir: temp_dir,
left,
right,
output,
})
}
pub(crate) struct DiffEditWorkingCopies {
pub working_copies: DiffWorkingCopies,
instructions_path_to_cleanup: Option<PathBuf>,
}
impl DiffEditWorkingCopies {
/// Checks out the trees, populates JJ_INSTRUCTIONS, and makes appropriate
/// sides readonly.
pub fn check_out(
trees: Diff<&MergedTree>,
matcher: &dyn Matcher,
diff_type: DiffType,
instructions: Option<&str>,
conflict_marker_style: ConflictMarkerStyle,
) -> Result<Self, DiffEditError> {
let working_copies = check_out_trees(trees, matcher, diff_type, conflict_marker_style)?;
working_copies.set_left_readonly()?;
if diff_type == DiffType::ThreeWay {
working_copies.set_right_readonly()?;
}
let instructions_path_to_cleanup =
Self::write_edit_instructions(&working_copies, instructions)?;
Ok(Self {
working_copies,
instructions_path_to_cleanup,
})
}
fn write_edit_instructions(
working_copies: &DiffWorkingCopies,
instructions: Option<&str>,
) -> Result<Option<PathBuf>, DiffEditError> {
let Some(instructions) = instructions else {
return Ok(None);
};
let (right_wc_path, output_wc_path) = match &working_copies.output {
Some(output) => (
Some(working_copies.right.working_copy_path()),
output.working_copy_path(),
),
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.
if output_instructions_path.exists() {
return Ok(None);
}
let mut output_instructions_file =
File::create(&output_instructions_path).map_err(ExternalToolError::SetUpDir)?;
// Write out our experimental three-way merge instructions first.
if let Some(right_wc_path) = right_wc_path {
let mut right_instructions_file = File::create(right_wc_path.join("JJ-INSTRUCTIONS"))
.map_err(ExternalToolError::SetUpDir)?;
right_instructions_file
.write_all(
b"\
The content of this pane should NOT be edited. Any edits will be
lost.
You are using the experimental 3-pane diff editor config. Some of
the following instructions may have been written with a 2-pane
diff editing in mind and be a little inaccurate.
",
)
.map_err(ExternalToolError::SetUpDir)?;
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.
output_instructions_file
.write_all(
b"\
Please make your edits in this pane.
You are using the experimental 3-pane diff editor config. Some of
the following instructions may have been written with a 2-pane
diff editing in mind and be a little inaccurate.
",
)
.map_err(ExternalToolError::SetUpDir)?;
}
// Now write the passed-in instructions.
output_instructions_file
.write_all(instructions.as_bytes())
.map_err(ExternalToolError::SetUpDir)?;
Ok(Some(output_instructions_path))
}
pub fn snapshot_results(
self,
base_ignores: Arc<GitIgnoreFile>,
) -> Result<MergedTree, DiffEditError> {
if let Some(path) = self.instructions_path_to_cleanup {
std::fs::remove_file(path).ok();
}
let diff_wc = self.working_copies;
// Snapshot changes in the temporary output directory.
let mut output_tree_state = diff_wc.output.unwrap_or(diff_wc.right);
output_tree_state
.snapshot(&SnapshotOptions {
base_ignores,
progress: None,
start_tracking_matcher: &EverythingMatcher,
force_tracking_matcher: &NothingMatcher,
max_new_file_size: u64::MAX,
})
.block_on()?;
Ok(output_tree_state.current_tree().clone())
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/merge_tools/mod.rs | cli/src/merge_tools/mod.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod builtin;
mod diff_working_copies;
mod external;
use std::sync::Arc;
use itertools::Itertools as _;
use jj_lib::backend::BackendError;
use jj_lib::backend::CopyId;
use jj_lib::backend::TreeValue;
use jj_lib::config::ConfigGetError;
use jj_lib::config::ConfigGetResultExt as _;
use jj_lib::config::ConfigNamePathBuf;
use jj_lib::conflicts::ConflictMarkerStyle;
use jj_lib::conflicts::MaterializedFileConflictValue;
use jj_lib::conflicts::try_materialize_file_conflict_value;
use jj_lib::gitignore::GitIgnoreFile;
use jj_lib::matchers::Matcher;
use jj_lib::merge::Diff;
use jj_lib::merge::Merge;
use jj_lib::merge::MergedTreeValue;
use jj_lib::merged_tree::MergedTree;
use jj_lib::merged_tree::MergedTreeBuilder;
use jj_lib::repo_path::InvalidRepoPathError;
use jj_lib::repo_path::RepoPath;
use jj_lib::repo_path::RepoPathBuf;
use jj_lib::repo_path::RepoPathUiConverter;
use jj_lib::settings::UserSettings;
use jj_lib::working_copy::SnapshotError;
use pollster::FutureExt as _;
use thiserror::Error;
use self::builtin::BuiltinToolError;
use self::builtin::edit_diff_builtin;
use self::builtin::edit_merge_builtin;
use self::diff_working_copies::DiffCheckoutError;
pub(crate) use self::diff_working_copies::new_utf8_temp_dir;
pub use self::external::DiffToolMode;
pub use self::external::ExternalMergeTool;
use self::external::ExternalToolError;
use self::external::edit_diff_external;
pub use self::external::generate_diff;
pub use self::external::invoke_external_diff;
use crate::config::CommandNameAndArgs;
use crate::ui::Ui;
const BUILTIN_EDITOR_NAME: &str = ":builtin";
const OURS_TOOL_NAME: &str = ":ours";
const THEIRS_TOOL_NAME: &str = ":theirs";
#[derive(Debug, Error)]
pub enum DiffEditError {
#[error(transparent)]
InternalTool(#[from] Box<BuiltinToolError>),
#[error(transparent)]
ExternalTool(#[from] ExternalToolError),
#[error(transparent)]
DiffCheckoutError(#[from] DiffCheckoutError),
#[error("Failed to snapshot changes")]
Snapshot(#[from] SnapshotError),
#[error(transparent)]
Config(#[from] ConfigGetError),
}
#[derive(Debug, Error)]
pub enum DiffGenerateError {
#[error(transparent)]
ExternalTool(#[from] ExternalToolError),
#[error(transparent)]
DiffCheckoutError(#[from] DiffCheckoutError),
}
#[derive(Debug, Error)]
pub enum ConflictResolveError {
#[error(transparent)]
InternalTool(#[from] Box<BuiltinToolError>),
#[error(transparent)]
ExternalTool(#[from] ExternalToolError),
#[error(transparent)]
InvalidRepoPath(#[from] InvalidRepoPathError),
#[error("Couldn't find the path {0:?} in this revision")]
PathNotFound(RepoPathBuf),
#[error("Couldn't find any conflicts at {0:?} in this revision")]
NotAConflict(RepoPathBuf),
#[error(
"Only conflicts that involve normal files (not symlinks, etc.) are supported. Conflict \
summary for {path:?}:\n{summary}",
summary = summary.trim_end()
)]
NotNormalFiles { path: RepoPathBuf, summary: String },
#[error("The conflict at {path:?} has {sides} sides. At most 2 sides are supported.")]
ConflictTooComplicated { path: RepoPathBuf, sides: usize },
#[error("{path:?} has conflicts in executable bit\n{summary}", summary = summary.trim_end())]
ExecutableConflict { path: RepoPathBuf, summary: String },
#[error(
"The output file is either unchanged or empty after the editor quit (run with --debug to \
see the exact invocation)."
)]
EmptyOrUnchanged,
#[error(transparent)]
Backend(#[from] jj_lib::backend::BackendError),
#[error(transparent)]
Io(#[from] std::io::Error),
}
#[derive(Debug, Error)]
#[error("Stopped due to error after resolving {resolved_count} conflicts")]
pub struct MergeToolPartialResolutionError {
pub source: ConflictResolveError,
pub resolved_count: usize,
}
#[derive(Debug, Error)]
pub enum MergeToolConfigError {
#[error(transparent)]
Config(#[from] ConfigGetError),
#[error("The tool `{tool_name}` cannot be used as a merge tool with `jj resolve`")]
MergeArgsNotConfigured { tool_name: String },
#[error("The tool `{tool_name}` cannot be used as a diff editor")]
EditArgsNotConfigured { tool_name: String },
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MergeTool {
Builtin,
Ours,
Theirs,
// Boxed because ExternalMergeTool is big compared to the Builtin variant.
External(Box<ExternalMergeTool>),
}
impl MergeTool {
fn external(tool: ExternalMergeTool) -> Self {
Self::External(Box::new(tool))
}
/// Resolves builtin merge tool names or loads external tool options from
/// `[merge-tools.<name>]`.
fn get_tool_config(
settings: &UserSettings,
name: &str,
) -> Result<Option<Self>, MergeToolConfigError> {
match name {
BUILTIN_EDITOR_NAME => Ok(Some(Self::Builtin)),
OURS_TOOL_NAME => Ok(Some(Self::Ours)),
THEIRS_TOOL_NAME => Ok(Some(Self::Theirs)),
_ => Ok(get_external_tool_config(settings, name)?.map(Self::external)),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DiffEditTool {
Builtin,
// Boxed because ExternalMergeTool is big compared to the Builtin variant.
External(Box<ExternalMergeTool>),
}
impl DiffEditTool {
fn external(tool: ExternalMergeTool) -> Self {
Self::External(Box::new(tool))
}
/// Resolves builtin merge tool name or loads external tool options from
/// `[merge-tools.<name>]`.
fn get_tool_config(
settings: &UserSettings,
name: &str,
) -> Result<Option<Self>, MergeToolConfigError> {
match name {
BUILTIN_EDITOR_NAME => Ok(Some(Self::Builtin)),
_ => Ok(get_external_tool_config(settings, name)?.map(Self::external)),
}
}
}
/// Finds the appropriate tool for diff editing or merges
fn editor_args_from_settings(
ui: &Ui,
settings: &UserSettings,
key: &'static str,
) -> Result<CommandNameAndArgs, ConfigGetError> {
// 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 {
let default_editor = BUILTIN_EDITOR_NAME;
writeln!(
ui.hint_default(),
"Using default editor '{default_editor}'; run `jj config set --user {key} :builtin` \
to disable this message."
)
.ok();
Ok(default_editor.into())
}
}
/// List configured merge tools (diff editors, diff tools, merge editors)
pub fn configured_merge_tools(settings: &UserSettings) -> impl Iterator<Item = &str> {
settings.table_keys("merge-tools")
}
/// Loads external diff/merge tool options from `[merge-tools.<name>]`.
pub fn get_external_tool_config(
settings: &UserSettings,
name: &str,
) -> Result<Option<ExternalMergeTool>, ConfigGetError> {
let full_name = ConfigNamePathBuf::from_iter(["merge-tools", name]);
let Some(mut tool) = settings.get::<ExternalMergeTool>(&full_name).optional()? else {
return Ok(None);
};
if tool.program.is_empty() {
tool.program = name.to_owned();
};
Ok(Some(tool))
}
/// Configured diff editor.
#[derive(Clone, Debug)]
pub struct DiffEditor {
tool: DiffEditTool,
base_ignores: Arc<GitIgnoreFile>,
use_instructions: bool,
conflict_marker_style: ConflictMarkerStyle,
}
impl DiffEditor {
/// Creates diff editor of the given name, and loads parameters from the
/// settings.
pub fn with_name(
name: &str,
settings: &UserSettings,
base_ignores: Arc<GitIgnoreFile>,
conflict_marker_style: ConflictMarkerStyle,
) -> Result<Self, MergeToolConfigError> {
let tool = DiffEditTool::get_tool_config(settings, name)?
.unwrap_or_else(|| DiffEditTool::external(ExternalMergeTool::with_program(name)));
Self::new_inner(name, tool, settings, base_ignores, conflict_marker_style)
}
/// Loads the default diff editor from the settings.
pub fn from_settings(
ui: &Ui,
settings: &UserSettings,
base_ignores: Arc<GitIgnoreFile>,
conflict_marker_style: ConflictMarkerStyle,
) -> Result<Self, MergeToolConfigError> {
let args = editor_args_from_settings(ui, settings, "ui.diff-editor")?;
let tool = if let Some(name) = args.as_str() {
DiffEditTool::get_tool_config(settings, name)?
} else {
None
}
.unwrap_or_else(|| DiffEditTool::external(ExternalMergeTool::with_edit_args(&args)));
Self::new_inner(&args, tool, settings, base_ignores, conflict_marker_style)
}
fn new_inner(
name: impl ToString,
tool: DiffEditTool,
settings: &UserSettings,
base_ignores: Arc<GitIgnoreFile>,
conflict_marker_style: ConflictMarkerStyle,
) -> Result<Self, MergeToolConfigError> {
if let DiffEditTool::External(mergetool) = &tool
&& mergetool.edit_args.is_empty()
{
return Err(MergeToolConfigError::EditArgsNotConfigured {
tool_name: name.to_string(),
});
}
Ok(Self {
tool,
base_ignores,
use_instructions: settings.get_bool("ui.diff-instructions")?,
conflict_marker_style,
})
}
/// Starts a diff editor on the two directories.
pub fn edit(
&self,
trees: Diff<&MergedTree>,
matcher: &dyn Matcher,
format_instructions: impl FnOnce() -> String,
) -> Result<MergedTree, DiffEditError> {
match &self.tool {
DiffEditTool::Builtin => {
Ok(
edit_diff_builtin(trees, matcher, self.conflict_marker_style)
.map_err(Box::new)?,
)
}
DiffEditTool::External(editor) => {
let instructions = self.use_instructions.then(format_instructions);
edit_diff_external(
editor,
trees,
matcher,
instructions.as_deref(),
self.base_ignores.clone(),
self.conflict_marker_style,
)
}
}
}
}
/// A file to be merged by a merge tool.
struct MergeToolFile {
repo_path: RepoPathBuf,
conflict: MergedTreeValue,
file: MaterializedFileConflictValue,
}
impl MergeToolFile {
fn from_tree_and_path(
tree: &MergedTree,
repo_path: &RepoPath,
) -> Result<Self, ConflictResolveError> {
let conflict = match tree.path_value(repo_path)?.into_resolved() {
Err(conflict) => conflict,
Ok(Some(_)) => return Err(ConflictResolveError::NotAConflict(repo_path.to_owned())),
Ok(None) => return Err(ConflictResolveError::PathNotFound(repo_path.to_owned())),
};
let file =
try_materialize_file_conflict_value(tree.store(), repo_path, &conflict, tree.labels())
.block_on()?
.ok_or_else(|| ConflictResolveError::NotNormalFiles {
path: repo_path.to_owned(),
summary: conflict.describe(tree.labels()),
})?;
// We only support conflicts with 2 sides (3-way conflicts)
if file.ids.num_sides() > 2 {
return Err(ConflictResolveError::ConflictTooComplicated {
path: repo_path.to_owned(),
sides: file.ids.num_sides(),
});
};
if file.executable.is_none() {
return Err(ConflictResolveError::ExecutableConflict {
path: repo_path.to_owned(),
summary: conflict.describe(tree.labels()),
});
}
Ok(Self {
repo_path: repo_path.to_owned(),
conflict,
file,
})
}
}
/// Configured 3-way merge editor.
#[derive(Clone, Debug)]
pub struct MergeEditor {
tool: MergeTool,
path_converter: RepoPathUiConverter,
conflict_marker_style: ConflictMarkerStyle,
}
impl MergeEditor {
/// Creates 3-way merge editor of the given name, and loads parameters from
/// the settings.
pub fn with_name(
name: &str,
settings: &UserSettings,
path_converter: RepoPathUiConverter,
conflict_marker_style: ConflictMarkerStyle,
) -> Result<Self, MergeToolConfigError> {
let tool = MergeTool::get_tool_config(settings, name)?
.unwrap_or_else(|| MergeTool::external(ExternalMergeTool::with_program(name)));
Self::new_inner(name, tool, path_converter, conflict_marker_style)
}
/// Loads the default 3-way merge editor from the settings.
pub fn from_settings(
ui: &Ui,
settings: &UserSettings,
path_converter: RepoPathUiConverter,
conflict_marker_style: ConflictMarkerStyle,
) -> Result<Self, MergeToolConfigError> {
let args = editor_args_from_settings(ui, settings, "ui.merge-editor")?;
let tool = if let Some(name) = args.as_str() {
MergeTool::get_tool_config(settings, name)?
} else {
None
}
.unwrap_or_else(|| MergeTool::external(ExternalMergeTool::with_merge_args(&args)));
Self::new_inner(&args, tool, path_converter, conflict_marker_style)
}
fn new_inner(
name: impl ToString,
tool: MergeTool,
path_converter: RepoPathUiConverter,
conflict_marker_style: ConflictMarkerStyle,
) -> Result<Self, MergeToolConfigError> {
if let MergeTool::External(mergetool) = &tool
&& mergetool.merge_args.is_empty()
{
return Err(MergeToolConfigError::MergeArgsNotConfigured {
tool_name: name.to_string(),
});
}
Ok(Self {
tool,
path_converter,
conflict_marker_style,
})
}
/// Starts a merge editor for the specified files.
pub fn edit_files(
&self,
ui: &Ui,
tree: &MergedTree,
repo_paths: &[&RepoPath],
) -> Result<(MergedTree, Option<MergeToolPartialResolutionError>), ConflictResolveError> {
let merge_tool_files: Vec<MergeToolFile> = repo_paths
.iter()
.map(|&repo_path| MergeToolFile::from_tree_and_path(tree, repo_path))
.try_collect()?;
match &self.tool {
MergeTool::Builtin => {
let tree = edit_merge_builtin(tree, &merge_tool_files).map_err(Box::new)?;
Ok((tree, None))
}
MergeTool::Ours => {
let tree = pick_conflict_side(tree, &merge_tool_files, 0)?;
Ok((tree, None))
}
MergeTool::Theirs => {
let tree = pick_conflict_side(tree, &merge_tool_files, 1)?;
Ok((tree, None))
}
MergeTool::External(editor) => external::run_mergetool_external(
ui,
&self.path_converter,
editor,
tree,
&merge_tool_files,
self.conflict_marker_style,
),
}
}
}
fn pick_conflict_side(
tree: &MergedTree,
merge_tool_files: &[MergeToolFile],
add_index: usize,
) -> Result<MergedTree, BackendError> {
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.
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");
let new_tree_value = Merge::resolved(file_id.clone().map(|id| TreeValue::File {
id,
executable,
copy_id: CopyId::placeholder(),
}));
tree_builder.set_or_remove(merge_tool_file.repo_path.clone(), new_tree_value);
}
tree_builder.write_tree()
}
#[cfg(test)]
mod tests {
use jj_lib::config::ConfigLayer;
use jj_lib::config::ConfigSource;
use jj_lib::config::StackedConfig;
use super::*;
fn config_from_string(text: &str) -> StackedConfig {
let mut config = StackedConfig::with_defaults();
// Load defaults to test the default args lookup
config.extend_layers(crate::config::default_config_layers());
config.add_layer(ConfigLayer::parse(ConfigSource::User, text).unwrap());
config
}
#[test]
fn test_get_diff_editor_with_name() {
let get = |name, config_text| {
let config = config_from_string(config_text);
let settings = UserSettings::from_config(config).unwrap();
DiffEditor::with_name(
name,
&settings,
GitIgnoreFile::empty(),
ConflictMarkerStyle::Diff,
)
.map(|editor| editor.tool)
};
insta::assert_debug_snapshot!(get(":builtin", "").unwrap(), @"Builtin");
// Just program name, edit_args are filled by default
insta::assert_debug_snapshot!(get("my diff", "").unwrap(), @r#"
External(
ExternalMergeTool {
program: "my diff",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"$left",
"$right",
],
merge_args: [],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// Pick from merge-tools
insta::assert_debug_snapshot!(get(
"foo bar", r#"
[merge-tools."foo bar"]
edit-args = ["--edit", "args", "$left", "$right"]
"#,
).unwrap(), @r#"
External(
ExternalMergeTool {
program: "foo bar",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"--edit",
"args",
"$left",
"$right",
],
merge_args: [],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
}
#[test]
fn test_get_diff_editor_from_settings() {
let get = |text| {
let config = config_from_string(text);
let ui = Ui::with_config(&config).unwrap();
let settings = UserSettings::from_config(config).unwrap();
DiffEditor::from_settings(
&ui,
&settings,
GitIgnoreFile::empty(),
ConflictMarkerStyle::Diff,
)
.map(|editor| editor.tool)
};
// Default
insta::assert_debug_snapshot!(get("").unwrap(), @"Builtin");
// Just program name, edit_args are filled by default
insta::assert_debug_snapshot!(get(r#"ui.diff-editor = "my-diff""#).unwrap(), @r#"
External(
ExternalMergeTool {
program: "my-diff",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"$left",
"$right",
],
merge_args: [],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// String args (with interpolation variables)
insta::assert_debug_snapshot!(
get(r#"ui.diff-editor = "my-diff -l $left -r $right""#).unwrap(), @r#"
External(
ExternalMergeTool {
program: "my-diff",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"-l",
"$left",
"-r",
"$right",
],
merge_args: [],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// List args (with interpolation variables)
insta::assert_debug_snapshot!(
get(r#"ui.diff-editor = ["my-diff", "--diff", "$left", "$right"]"#).unwrap(), @r#"
External(
ExternalMergeTool {
program: "my-diff",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"--diff",
"$left",
"$right",
],
merge_args: [],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// Pick from merge-tools
insta::assert_debug_snapshot!(get(
r#"
ui.diff-editor = "foo bar"
[merge-tools."foo bar"]
edit-args = ["--edit", "args", "$left", "$right"]
diff-args = [] # Should not cause an error, since we're getting the diff *editor*
"#,
).unwrap(), @r#"
External(
ExternalMergeTool {
program: "foo bar",
diff_args: [],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"--edit",
"args",
"$left",
"$right",
],
merge_args: [],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// Pick from merge-tools, but no edit-args specified
insta::assert_debug_snapshot!(get(
r#"
ui.diff-editor = "my-diff"
[merge-tools.my-diff]
program = "MyDiff"
"#,
).unwrap(), @r#"
External(
ExternalMergeTool {
program: "MyDiff",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"$left",
"$right",
],
merge_args: [],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// 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 {
program: "meld",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"$left",
"$right",
],
merge_args: [],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// Invalid type
assert!(get(r#"ui.diff-editor.k = 0"#).is_err());
// Explicitly empty edit-args cause an error
insta::assert_debug_snapshot!(get(
r#"
ui.diff-editor = "my-diff"
[merge-tools.my-diff]
program = "MyDiff"
edit-args = []
"#,
), @r#"
Err(
EditArgsNotConfigured {
tool_name: "my-diff",
},
)
"#);
}
#[test]
fn test_get_merge_editor_with_name() {
let get = |name, config_text| {
let config = config_from_string(config_text);
let settings = UserSettings::from_config(config).unwrap();
let path_converter = RepoPathUiConverter::Fs {
cwd: "".into(),
base: "".into(),
};
MergeEditor::with_name(name, &settings, path_converter, ConflictMarkerStyle::Diff)
.map(|editor| editor.tool)
};
insta::assert_debug_snapshot!(get(":builtin", "").unwrap(), @"Builtin");
// Just program name
insta::assert_debug_snapshot!(get("my diff", "").unwrap_err(), @r#"
MergeArgsNotConfigured {
tool_name: "my diff",
}
"#);
// Pick from merge-tools
insta::assert_debug_snapshot!(get(
"foo bar", r#"
[merge-tools."foo bar"]
merge-args = ["$base", "$left", "$right", "$output"]
"#,
).unwrap(), @r#"
External(
ExternalMergeTool {
program: "foo bar",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"$left",
"$right",
],
merge_args: [
"$base",
"$left",
"$right",
"$output",
],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
}
#[test]
fn test_get_merge_editor_from_settings() {
let get = |text| {
let config = config_from_string(text);
let ui = Ui::with_config(&config).unwrap();
let settings = UserSettings::from_config(config).unwrap();
let path_converter = RepoPathUiConverter::Fs {
cwd: "".into(),
base: "".into(),
};
MergeEditor::from_settings(&ui, &settings, path_converter, ConflictMarkerStyle::Diff)
.map(|editor| editor.tool)
};
// Default
insta::assert_debug_snapshot!(get("").unwrap(), @"Builtin");
// Just program name
insta::assert_debug_snapshot!(get(r#"ui.merge-editor = "my-merge""#).unwrap_err(), @r#"
MergeArgsNotConfigured {
tool_name: "my-merge",
}
"#);
// String args
insta::assert_debug_snapshot!(
get(r#"ui.merge-editor = "my-merge $left $base $right $output""#).unwrap(), @r#"
External(
ExternalMergeTool {
program: "my-merge",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"$left",
"$right",
],
merge_args: [
"$left",
"$base",
"$right",
"$output",
],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// List args
insta::assert_debug_snapshot!(
get(
r#"ui.merge-editor = ["my-merge", "$left", "$base", "$right", "$output"]"#,
).unwrap(), @r#"
External(
ExternalMergeTool {
program: "my-merge",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"$left",
"$right",
],
merge_args: [
"$left",
"$base",
"$right",
"$output",
],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// Pick from merge-tools
insta::assert_debug_snapshot!(get(
r#"
ui.merge-editor = "foo bar"
[merge-tools."foo bar"]
merge-args = ["$base", "$left", "$right", "$output"]
"#,
).unwrap(), @r#"
External(
ExternalMergeTool {
program: "foo bar",
diff_args: [
"$left",
"$right",
],
diff_expected_exit_codes: [
0,
],
diff_invocation_mode: Dir,
diff_do_chdir: true,
edit_args: [
"$left",
"$right",
],
merge_args: [
"$base",
"$left",
"$right",
"$output",
],
merge_conflict_exit_codes: [],
merge_tool_edits_conflict_markers: false,
conflict_marker_style: None,
},
)
"#);
// List args should never be a merge-tools key
insta::assert_debug_snapshot!(
get(r#"ui.merge-editor = ["meld"]"#).unwrap_err(), @r#"
MergeArgsNotConfigured {
tool_name: "meld",
}
"#);
// Invalid type
assert!(get(r#"ui.merge-editor.k = 0"#).is_err());
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/src/merge_tools/builtin.rs | cli/src/merge_tools/builtin.rs | use std::borrow::Cow;
use std::path::Path;
use std::sync::Arc;
use futures::StreamExt as _;
use futures::stream::BoxStream;
use itertools::Itertools as _;
use jj_lib::backend::BackendResult;
use jj_lib::backend::CopyId;
use jj_lib::backend::TreeValue;
use jj_lib::conflicts;
use jj_lib::conflicts::ConflictMarkerStyle;
use jj_lib::conflicts::ConflictMaterializeOptions;
use jj_lib::conflicts::MIN_CONFLICT_MARKER_LEN;
use jj_lib::conflicts::MaterializedTreeValue;
use jj_lib::conflicts::materialize_merge_result_to_bytes;
use jj_lib::conflicts::materialized_diff_stream;
use jj_lib::copies::CopiesTreeDiffEntry;
use jj_lib::copies::CopyRecords;
use jj_lib::diff::ContentDiff;
use jj_lib::diff::DiffHunkKind;
use jj_lib::files;
use jj_lib::files::MergeResult;
use jj_lib::matchers::Matcher;
use jj_lib::merge::Diff;
use jj_lib::merge::Merge;
use jj_lib::merge::MergedTreeValue;
use jj_lib::merged_tree::MergedTree;
use jj_lib::merged_tree::MergedTreeBuilder;
use jj_lib::object_id::ObjectId as _;
use jj_lib::repo_path::RepoPath;
use jj_lib::repo_path::RepoPathBuf;
use jj_lib::store::Store;
use jj_lib::tree_merge::MergeOptions;
use pollster::FutureExt as _;
use thiserror::Error;
use super::MergeToolFile;
#[derive(Debug, Error)]
pub enum BuiltinToolError {
#[error("Failed to record changes")]
Record(#[from] scm_record::RecordError),
#[error("Failed to decode UTF-8 text for item {item} (this should not happen)")]
DecodeUtf8 {
source: std::str::Utf8Error,
item: &'static str,
},
#[error("Rendering {item} {id} is unimplemented for the builtin difftool/mergetool")]
Unimplemented { item: &'static str, id: String },
#[error("Backend error")]
BackendError(#[from] jj_lib::backend::BackendError),
}
#[derive(Clone, Debug)]
enum FileContents {
Absent,
Text {
contents: String,
hash: Option<String>,
num_bytes: u64,
},
Binary {
hash: Option<String>,
num_bytes: u64,
},
}
impl FileContents {
fn describe(&self) -> Option<String> {
match self {
Self::Absent => None,
Self::Text {
contents: _,
hash,
num_bytes,
}
| Self::Binary { hash, num_bytes } => match hash {
Some(hash) => Some(format!("{hash} ({num_bytes}B)")),
None => Some(format!("({num_bytes}B)")),
},
}
}
}
/// Information about a file that was read from disk. Note that the file may not
/// have existed, in which case its contents will be marked as absent.
#[derive(Clone, Debug)]
pub struct FileInfo {
file_mode: scm_record::FileMode,
contents: FileContents,
}
/// File modes according to the Git file mode conventions. used for display
/// purposes and equality comparison.
///
/// TODO: let `scm-record` accept strings instead of numbers for file modes? Or
/// figure out some other way to represent file mode changes in a jj-compatible
/// manner?
mod mode {
pub const ABSENT: scm_record::FileMode = scm_record::FileMode::Absent;
pub const NORMAL: scm_record::FileMode = scm_record::FileMode::Unix(0o100644);
pub const EXECUTABLE: scm_record::FileMode = scm_record::FileMode::Unix(0o100755);
pub const SYMLINK: scm_record::FileMode = scm_record::FileMode::Unix(0o120000);
}
fn buf_to_file_contents(hash: Option<String>, buf: Vec<u8>) -> FileContents {
let num_bytes: u64 = buf.len().try_into().unwrap();
let text = if buf.contains(&0) {
None
} else {
String::from_utf8(buf).ok()
};
match text {
Some(text) => FileContents::Text {
contents: text,
hash,
num_bytes,
},
None => FileContents::Binary { hash, num_bytes },
}
}
fn read_file_contents(
materialized_value: MaterializedTreeValue,
path: &RepoPath,
materialize_options: &ConflictMaterializeOptions,
) -> Result<FileInfo, BuiltinToolError> {
match materialized_value {
MaterializedTreeValue::Absent => Ok(FileInfo {
file_mode: mode::ABSENT,
contents: FileContents::Absent,
}),
MaterializedTreeValue::AccessDenied(err) => Ok(FileInfo {
file_mode: mode::NORMAL,
contents: FileContents::Text {
contents: format!("Access denied: {err}"),
hash: None,
num_bytes: 0,
},
}),
MaterializedTreeValue::File(mut file) => {
let buf = file.read_all(path).block_on()?;
let file_mode = if file.executable {
mode::EXECUTABLE
} else {
mode::NORMAL
};
let contents = buf_to_file_contents(Some(file.id.hex()), buf);
Ok(FileInfo {
file_mode,
contents,
})
}
MaterializedTreeValue::Symlink { id, target } => {
let file_mode = mode::SYMLINK;
let num_bytes = target.len().try_into().unwrap();
Ok(FileInfo {
file_mode,
contents: FileContents::Text {
contents: target,
hash: Some(id.hex()),
num_bytes,
},
})
}
MaterializedTreeValue::Tree(tree_id) => {
unreachable!("list of changed files included a tree: {tree_id:?}");
}
MaterializedTreeValue::GitSubmodule(id) => Err(BuiltinToolError::Unimplemented {
item: "git submodule",
id: id.hex(),
}),
MaterializedTreeValue::FileConflict(file) => {
// Since scm_record doesn't support diffs of conflicts, file
// conflicts are compared in materialized form. The UI would look
// scary, but it can at least allow squashing resolved hunks.
let buf = materialize_merge_result_to_bytes(
&file.contents,
&file.labels,
materialize_options,
)
.into();
// TODO: Render the ID somehow?
let contents = buf_to_file_contents(None, buf);
Ok(FileInfo {
file_mode: mode::NORMAL,
contents,
})
}
MaterializedTreeValue::OtherConflict { id, labels } => {
// TODO: Non-file conflict shouldn't be rendered as a normal file
// TODO: Render the ID somehow?
let contents = buf_to_file_contents(None, id.describe(&labels).into_bytes());
Ok(FileInfo {
file_mode: mode::NORMAL,
contents,
})
}
}
}
fn make_section_changed_lines(
contents: &str,
change_type: scm_record::ChangeType,
) -> Vec<scm_record::SectionChangedLine<'static>> {
contents
.split_inclusive('\n')
.map(|line| scm_record::SectionChangedLine {
is_checked: false,
change_type,
line: Cow::Owned(line.to_owned()),
})
.collect()
}
fn make_diff_sections(
left_contents: &str,
right_contents: &str,
) -> Result<Vec<scm_record::Section<'static>>, BuiltinToolError> {
let diff = ContentDiff::by_line([left_contents.as_bytes(), right_contents.as_bytes()]);
let mut sections = Vec::new();
for hunk in diff.hunks() {
match hunk.kind {
DiffHunkKind::Matching => {
debug_assert!(hunk.contents.iter().all_equal());
let text = hunk.contents[0];
let text = str::from_utf8(text).map_err(|err| BuiltinToolError::DecodeUtf8 {
source: err,
item: "matching text in diff hunk",
})?;
sections.push(scm_record::Section::Unchanged {
lines: text
.split_inclusive('\n')
.map(|line| Cow::Owned(line.to_owned()))
.collect(),
});
}
DiffHunkKind::Different => {
let sides = &hunk.contents;
assert_eq!(sides.len(), 2, "only two inputs were provided to the diff");
let left_side =
str::from_utf8(sides[0]).map_err(|err| BuiltinToolError::DecodeUtf8 {
source: err,
item: "left side of diff hunk",
})?;
let right_side =
str::from_utf8(sides[1]).map_err(|err| BuiltinToolError::DecodeUtf8 {
source: err,
item: "right side of diff hunk",
})?;
sections.push(scm_record::Section::Changed {
lines: [
make_section_changed_lines(left_side, scm_record::ChangeType::Removed),
make_section_changed_lines(right_side, scm_record::ChangeType::Added),
]
.concat(),
});
}
}
}
Ok(sections)
}
async fn make_diff_files(
store: &Arc<Store>,
trees: Diff<&MergedTree>,
tree_diff: BoxStream<'_, CopiesTreeDiffEntry>,
marker_style: ConflictMarkerStyle,
) -> Result<(Vec<RepoPathBuf>, Vec<scm_record::File<'static>>), BuiltinToolError> {
let materialize_options = ConflictMaterializeOptions {
marker_style,
marker_len: None,
merge: store.merge_options().clone(),
};
let conflict_labels = trees.map(MergedTree::labels);
let mut diff_stream = materialized_diff_stream(store, tree_diff, conflict_labels);
let mut changed_files = Vec::new();
let mut files = Vec::new();
while let Some(entry) = diff_stream.next().await {
let left_path = entry.path.source();
let right_path = entry.path.target();
let values = entry.values?;
let left_info = read_file_contents(values.before, left_path, &materialize_options)?;
let right_info = read_file_contents(values.after, right_path, &materialize_options)?;
let mut sections = Vec::new();
if left_info.file_mode != right_info.file_mode {
sections.push(scm_record::Section::FileMode {
is_checked: false,
mode: right_info.file_mode,
});
}
match (left_info.contents, right_info.contents) {
(FileContents::Absent, FileContents::Absent) => {}
// In this context, `Absent` means the file doesn't exist. If it only
// exists on one side, we will render a mode change section above.
// The next two patterns are to avoid also rendering an empty
// changed lines section that clutters the UI.
(
FileContents::Absent,
FileContents::Text {
contents: _,
hash: _,
num_bytes: 0,
},
) => {}
(
FileContents::Text {
contents: _,
hash: _,
num_bytes: 0,
},
FileContents::Absent,
) => {}
(
FileContents::Absent,
FileContents::Text {
contents,
hash: _,
num_bytes: _,
},
) => sections.push(scm_record::Section::Changed {
lines: make_section_changed_lines(&contents, scm_record::ChangeType::Added),
}),
(
FileContents::Text {
contents,
hash: _,
num_bytes: _,
},
FileContents::Absent,
) => sections.push(scm_record::Section::Changed {
lines: make_section_changed_lines(&contents, scm_record::ChangeType::Removed),
}),
(
FileContents::Text {
contents: old_contents,
hash: _,
num_bytes: _,
},
FileContents::Text {
contents: new_contents,
hash: _,
num_bytes: _,
},
) => {
sections.extend(make_diff_sections(&old_contents, &new_contents)?);
}
(
FileContents::Binary {
hash: Some(left_hash),
..
},
FileContents::Binary {
hash: Some(right_hash),
..
},
) if left_hash == right_hash => {
// Binary file contents have not changed.
}
(left, right @ FileContents::Binary { .. })
| (left @ FileContents::Binary { .. }, right) => {
sections.push(scm_record::Section::Binary {
is_checked: false,
old_description: left.describe().map(Cow::Owned),
new_description: right.describe().map(Cow::Owned),
});
}
}
files.push(scm_record::File {
old_path: None,
// Path for displaying purposes, not for file access.
path: Cow::Owned(right_path.to_fs_path_unchecked(Path::new(""))),
file_mode: left_info.file_mode,
sections,
});
changed_files.push(entry.path.target);
}
Ok((changed_files, files))
}
fn apply_diff_builtin(
store: &Arc<Store>,
left_tree: &MergedTree,
right_tree: &MergedTree,
changed_files: Vec<RepoPathBuf>,
files: &[scm_record::File],
) -> BackendResult<MergedTree> {
// Start with the right tree to match external tool behavior.
// This ensures unmatched paths keep their values from the right tree.
let mut tree_builder = MergedTreeBuilder::new(right_tree.clone());
// First, revert all changed files to their left versions
for path in &changed_files {
let left_value = left_tree.path_value(path)?;
tree_builder.set_or_remove(path.clone(), left_value);
}
// Then apply only the selected changes
apply_changes(
&mut tree_builder,
changed_files,
files,
|path| left_tree.path_value(path),
|path| right_tree.path_value(path),
|path, contents, executable, copy_id| {
let old_value = left_tree.path_value(path)?;
let new_value = if old_value.is_resolved() {
let id = store.write_file(path, &mut &contents[..]).block_on()?;
Merge::normal(TreeValue::File {
id,
executable,
copy_id,
})
} else if let Some(old_file_ids) = old_value.to_file_merge() {
// TODO: should error out if conflicts couldn't be parsed?
let new_file_ids = conflicts::update_from_content(
&old_file_ids,
store,
path,
contents,
MIN_CONFLICT_MARKER_LEN, // TODO: use the materialization parameter
)
.block_on()?;
match new_file_ids.into_resolved() {
Ok(id) => Merge::resolved(id.map(|id| TreeValue::File {
id,
executable,
copy_id: CopyId::placeholder(),
})),
Err(file_ids) => old_value.with_new_file_ids(&file_ids),
}
} else {
panic!("unexpected content change at {path:?}: {old_value:?}");
};
Ok(new_value)
},
)?;
tree_builder.write_tree()
}
fn apply_changes(
tree_builder: &mut MergedTreeBuilder,
changed_files: Vec<RepoPathBuf>,
files: &[scm_record::File],
select_left: impl Fn(&RepoPath) -> BackendResult<MergedTreeValue>,
select_right: impl Fn(&RepoPath) -> BackendResult<MergedTreeValue>,
write_file: impl Fn(&RepoPath, &[u8], bool, CopyId) -> BackendResult<MergedTreeValue>,
) -> BackendResult<()> {
assert_eq!(
changed_files.len(),
files.len(),
"result had a different number of files"
);
// TODO: Write files concurrently
for (path, file) in changed_files.into_iter().zip(files) {
let file_mode_change_selected = file
.sections
.iter()
.find_map(|sec| match sec {
scm_record::Section::FileMode { is_checked, .. } => Some(*is_checked),
_ => None,
})
.unwrap_or(false);
let (
scm_record::SelectedChanges {
contents,
file_mode,
},
_unselected,
) = file.get_selected_contents();
if file_mode == mode::ABSENT {
// The file is not present in the selected changes.
// Either a file mode change was selected to delete an existing file, so we
// should remove it from the tree,
if file_mode_change_selected {
tree_builder.set_or_remove(path, Merge::absent());
}
// or the file's creation has been split out of the change, in which case we
// don't need to change the tree.
// In either case, we're done with this file afterwards.
continue;
}
let executable = file_mode == mode::EXECUTABLE;
match contents {
scm_record::SelectedContents::Unchanged => {
if file_mode_change_selected {
// File contents haven't changed, but file mode needs to be updated on the tree.
let value = override_file_executable_bit(select_left(&path)?, executable);
tree_builder.set_or_remove(path, value);
} else {
// Neither file mode, nor contents changed => Do nothing.
}
}
scm_record::SelectedContents::Binary {
old_description: _,
new_description: Some(_),
} => {
let value = override_file_executable_bit(select_right(&path)?, executable);
tree_builder.set_or_remove(path, value);
}
scm_record::SelectedContents::Binary {
old_description: _,
new_description: None,
} => {
// File contents emptied out, but file mode is not absent => write empty file.
let copy_id = CopyId::placeholder();
let value = write_file(&path, &[], executable, copy_id)?;
tree_builder.set_or_remove(path, value);
}
scm_record::SelectedContents::Text { contents } => {
let copy_id = CopyId::placeholder();
let value = write_file(&path, contents.as_bytes(), executable, copy_id)?;
tree_builder.set_or_remove(path, value);
}
}
}
Ok(())
}
fn override_file_executable_bit(
mut merged_tree_value: MergedTreeValue,
new_executable_bit: bool,
) -> MergedTreeValue {
for tree_value in merged_tree_value.iter_mut().flatten() {
let TreeValue::File { executable, .. } = tree_value else {
panic!("incompatible update: expected a TreeValue::File, got {tree_value:?}");
};
*executable = new_executable_bit;
}
merged_tree_value
}
pub fn edit_diff_builtin(
trees: Diff<&MergedTree>,
matcher: &dyn Matcher,
conflict_marker_style: ConflictMarkerStyle,
) -> Result<MergedTree, BuiltinToolError> {
let store = trees.before.store().clone();
// TODO: handle copy tracking
let copy_records = CopyRecords::default();
let tree_diff = trees
.before
.diff_stream_with_copies(trees.after, matcher, ©_records);
let (changed_files, files) =
make_diff_files(&store, trees, tree_diff, conflict_marker_style).block_on()?;
let mut input = scm_record::helpers::CrosstermInput;
let recorder = scm_record::Recorder::new(
scm_record::RecordState {
is_read_only: false,
files,
commits: Default::default(),
},
&mut input,
);
let result = recorder.run().map_err(BuiltinToolError::Record)?;
apply_diff_builtin(
&store,
trees.before,
trees.after,
changed_files,
&result.files,
)
.map_err(BuiltinToolError::BackendError)
}
fn make_merge_sections(
merge_result: MergeResult,
) -> Result<Vec<scm_record::Section<'static>>, BuiltinToolError> {
let mut sections = Vec::new();
match merge_result {
MergeResult::Resolved(buf) => {
let contents = buf_to_file_contents(None, buf.into());
let section = match contents {
FileContents::Absent => None,
FileContents::Text {
contents,
hash: _,
num_bytes: _,
} => Some(scm_record::Section::Unchanged {
lines: contents
.split_inclusive('\n')
.map(|line| Cow::Owned(line.to_owned()))
.collect(),
}),
FileContents::Binary { .. } => Some(scm_record::Section::Binary {
// TODO: Perhaps, this should be an "unchanged" section?
is_checked: false,
old_description: None,
new_description: contents.describe().map(Cow::Owned),
}),
};
if let Some(section) = section {
sections.push(section);
}
}
MergeResult::Conflict(hunks) => {
for hunk in hunks {
let section = match hunk.into_resolved() {
Ok(contents) => {
let contents = str::from_utf8(&contents).map_err(|err| {
BuiltinToolError::DecodeUtf8 {
source: err,
item: "unchanged hunk",
}
})?;
scm_record::Section::Unchanged {
lines: contents
.split_inclusive('\n')
.map(|line| Cow::Owned(line.to_owned()))
.collect(),
}
}
Err(merge) => {
let lines: Vec<scm_record::SectionChangedLine> = merge
.iter()
.zip(
[
scm_record::ChangeType::Added,
scm_record::ChangeType::Removed,
]
.into_iter()
.cycle(),
)
.map(|(contents, change_type)| -> Result<_, BuiltinToolError> {
let contents = str::from_utf8(contents).map_err(|err| {
BuiltinToolError::DecodeUtf8 {
source: err,
item: "conflicting hunk",
}
})?;
let changed_lines =
make_section_changed_lines(contents, change_type);
Ok(changed_lines)
})
.flatten_ok()
.try_collect()?;
scm_record::Section::Changed { lines }
}
};
sections.push(section);
}
}
}
Ok(sections)
}
fn make_merge_file(
merge_tool_file: &MergeToolFile,
options: &MergeOptions,
) -> Result<scm_record::File<'static>, BuiltinToolError> {
let file = &merge_tool_file.file;
let file_mode = if file.executable.expect("should have been resolved") {
mode::EXECUTABLE
} else {
mode::NORMAL
};
// TODO: Maybe we should test binary contents here, and generate per-file
// Binary section to select either "our" or "their" file.
let merge_result = files::merge_hunks(&file.contents, options);
let sections = make_merge_sections(merge_result)?;
Ok(scm_record::File {
old_path: None,
// Path for displaying purposes, not for file access.
path: Cow::Owned(
merge_tool_file
.repo_path
.to_fs_path_unchecked(Path::new("")),
),
file_mode,
sections,
})
}
pub fn edit_merge_builtin(
tree: &MergedTree,
merge_tool_files: &[MergeToolFile],
) -> Result<MergedTree, BuiltinToolError> {
let store = tree.store();
let mut input = scm_record::helpers::CrosstermInput;
let recorder = scm_record::Recorder::new(
scm_record::RecordState {
is_read_only: false,
files: merge_tool_files
.iter()
.map(|f| make_merge_file(f, store.merge_options()))
.try_collect()?,
commits: Default::default(),
},
&mut input,
);
let state = recorder.run()?;
let mut tree_builder = MergedTreeBuilder::new(tree.clone());
apply_changes(
&mut tree_builder,
merge_tool_files
.iter()
.map(|file| file.repo_path.clone())
.collect_vec(),
&state.files,
|path| tree.path_value(path),
// FIXME: It doesn't make sense to select a new value from the source tree.
// Presently, `select_right` is never actually called, since it is used to select binary
// sections, but `make_merge_file` does not produce `Binary` sections for conflicted files.
// This needs to be revisited when the UI becomes capable of representing binary conflicts.
|path| tree.path_value(path),
|path, contents, executable, copy_id| {
let id = store.write_file(path, &mut &contents[..]).block_on()?;
Ok(Merge::normal(TreeValue::File {
id,
executable,
copy_id,
}))
},
)?;
Ok(tree_builder.write_tree()?)
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use jj_lib::backend::FileId;
use jj_lib::conflict_labels::ConflictLabels;
use jj_lib::conflicts::extract_as_single_hunk;
use jj_lib::matchers::EverythingMatcher;
use jj_lib::matchers::FilesMatcher;
use jj_lib::repo::Repo as _;
use proptest::prelude::*;
use proptest_state_machine::ReferenceStateMachine;
use proptest_state_machine::StateMachineTest;
use proptest_state_machine::prop_state_machine;
use testutils::TestRepo;
use testutils::assert_tree_eq;
use testutils::dump_tree;
use testutils::proptest::Transition;
use testutils::proptest::WorkingCopyReferenceStateMachine;
use testutils::repo_path;
use testutils::repo_path_component;
use super::*;
fn make_diff(
store: &Arc<Store>,
left_tree: &MergedTree,
right_tree: &MergedTree,
) -> (Vec<RepoPathBuf>, Vec<scm_record::File<'static>>) {
make_diff_with_matcher(store, left_tree, right_tree, &EverythingMatcher)
}
fn make_diff_with_matcher(
store: &Arc<Store>,
left_tree: &MergedTree,
right_tree: &MergedTree,
matcher: &dyn Matcher,
) -> (Vec<RepoPathBuf>, Vec<scm_record::File<'static>>) {
let copy_records = CopyRecords::default();
let tree_diff = left_tree.diff_stream_with_copies(right_tree, matcher, ©_records);
make_diff_files(
store,
Diff::new(left_tree, right_tree),
tree_diff,
ConflictMarkerStyle::Diff,
)
.block_on()
.unwrap()
}
fn apply_diff(
store: &Arc<Store>,
left_tree: &MergedTree,
right_tree: &MergedTree,
changed_files: &[RepoPathBuf],
files: &[scm_record::File],
) -> MergedTree {
apply_diff_builtin(store, left_tree, right_tree, changed_files.to_vec(), files).unwrap()
}
#[test]
fn test_edit_diff_builtin() {
let test_repo = TestRepo::init();
let store = test_repo.repo.store();
let unchanged = repo_path("unchanged");
let changed_path = repo_path("changed");
let added_path = repo_path("added");
let left_tree = testutils::create_tree(
&test_repo.repo,
&[
(unchanged, "unchanged\n"),
(changed_path, "line1\nline2\nline3\n"),
],
);
let right_tree = testutils::create_tree(
&test_repo.repo,
&[
(unchanged, "unchanged\n"),
(changed_path, "line1\nchanged1\nchanged2\nline3\nadded1\n"),
(added_path, "added\n"),
],
);
let (changed_files, files) = make_diff(store, &left_tree, &right_tree);
insta::assert_debug_snapshot!(changed_files, @r#"
[
"added",
"changed",
]
"#);
insta::assert_debug_snapshot!(files, @r#"
[
File {
old_path: None,
path: "added",
file_mode: Absent,
sections: [
FileMode {
is_checked: false,
mode: Unix(
33188,
),
},
Changed {
lines: [
SectionChangedLine {
is_checked: false,
change_type: Added,
line: "added\n",
},
],
},
],
},
File {
old_path: None,
path: "changed",
file_mode: Unix(
33188,
),
sections: [
Unchanged {
lines: [
"line1\n",
],
},
Changed {
lines: [
SectionChangedLine {
is_checked: false,
change_type: Removed,
line: "line2\n",
},
SectionChangedLine {
is_checked: false,
change_type: Added,
line: "changed1\n",
},
SectionChangedLine {
is_checked: false,
change_type: Added,
line: "changed2\n",
},
],
},
Unchanged {
lines: [
"line3\n",
],
},
Changed {
lines: [
SectionChangedLine {
is_checked: false,
change_type: Added,
line: "added1\n",
},
],
},
],
},
]
"#);
let no_changes_tree = apply_diff(store, &left_tree, &right_tree, &changed_files, &files);
assert_tree_eq!(left_tree, no_changes_tree, "no-changes tree was different");
let mut files = files;
for file in &mut files {
file.toggle_all();
}
let all_changes_tree = apply_diff(store, &left_tree, &right_tree, &changed_files, &files);
assert_tree_eq!(
right_tree,
all_changes_tree,
"all-changes tree was different",
);
}
#[test]
fn test_edit_diff_builtin_add_empty_file() {
let test_repo = TestRepo::init();
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_resolve_command.rs | cli/tests/test_resolve_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use indoc::indoc;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit_with_files;
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
work_dir.run_jj(["log", "-T", "bookmarks"])
}
#[test]
fn test_resolution() {
let mut test_env = TestEnvironment::default();
let editor_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
create_commit_with_files(&work_dir, "a", &["base"], &[("file", "a\n")]);
create_commit_with_files(&work_dir, "b", &["base"], &[("file", "b\n")]);
create_commit_with_files(&work_dir, "conflict", &["a", "b"], &[]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ conflict
โโโฎ
โ โ b
โ โ a
โโโฏ
โ base
โ
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
file 2-sided conflict
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: zsuskuln 45537d53 "a"
-base
+a
+++++++ royxmykx 89d1b299 "b"
b
>>>>>>> conflict 1 of 1 ends
"#);
let setup_opid = work_dir.current_operation_id();
// Check that output file starts out empty and resolve the conflict
std::fs::write(
&editor_script,
["dump editor0", "write\nresolution\n"].join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["resolve"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Resolving conflicts in: file
Working copy (@) now at: vruxwmqv 741263c9 conflict | conflict
Parent commit (@-) : zsuskuln 45537d53 a | a
Parent commit (@-) : royxmykx 89d1b299 b | b
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor0")).unwrap(), @"");
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @r#"
diff --git a/file b/file
index 0000000000..88425ec521 100644
--- a/file
+++ b/file
@@ -1,8 +1,1 @@
-<<<<<<< conflict 1 of 1
-%%%%%%% diff from: rlvkpnrz 1792382a "base"
-\\\\\\\ to: zsuskuln 45537d53 "a"
--base
-+a
-+++++++ royxmykx 89d1b299 "b"
-b
->>>>>>> conflict 1 of 1 ends
+resolution
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
------- stderr -------
Error: No conflicts found at this revision
[EOF]
[exit status: 2]
");
// Try again with --tool=<name>
work_dir.run_jj(["op", "restore", &setup_opid]).success();
std::fs::write(&editor_script, "write\nresolution\n").unwrap();
let output = work_dir.run_jj([
"resolve",
"--config=ui.merge-editor='false'",
"--tool=fake-editor",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Resolving conflicts in: file
Working copy (@) now at: vruxwmqv 1f8a36f7 conflict | conflict
Parent commit (@-) : zsuskuln 45537d53 a | a
Parent commit (@-) : royxmykx 89d1b299 b | b
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @r#"
diff --git a/file b/file
index 0000000000..88425ec521 100644
--- a/file
+++ b/file
@@ -1,8 +1,1 @@
-<<<<<<< conflict 1 of 1
-%%%%%%% diff from: rlvkpnrz 1792382a "base"
-\\\\\\\ to: zsuskuln 45537d53 "a"
--base
-+a
-+++++++ royxmykx 89d1b299 "b"
-b
->>>>>>> conflict 1 of 1 ends
+resolution
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
------- stderr -------
Error: No conflicts found at this revision
[EOF]
[exit status: 2]
");
// Check that the output file starts with conflict markers if
// `merge-tool-edits-conflict-markers=true`
work_dir.run_jj(["op", "restore", &setup_opid]).success();
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @"");
std::fs::write(
&editor_script,
["dump editor1", "write\nresolution\n"].join("\0"),
)
.unwrap();
work_dir
.run_jj([
"resolve",
"--config=merge-tools.fake-editor.merge-tool-edits-conflict-markers=true",
])
.success();
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor1")).unwrap(), @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: zsuskuln 45537d53 "a"
-base
+a
+++++++ royxmykx 89d1b299 "b"
b
>>>>>>> conflict 1 of 1 ends
"#);
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @r#"
diff --git a/file b/file
index 0000000000..88425ec521 100644
--- a/file
+++ b/file
@@ -1,8 +1,1 @@
-<<<<<<< conflict 1 of 1
-%%%%%%% diff from: rlvkpnrz 1792382a "base"
-\\\\\\\ to: zsuskuln 45537d53 "a"
--base
-+a
-+++++++ royxmykx 89d1b299 "b"
-b
->>>>>>> conflict 1 of 1 ends
+resolution
[EOF]
"#);
// Check that if merge tool leaves conflict markers in output file and
// `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(
&editor_script,
[
"dump editor2",
indoc! {"
write
<<<<<<<
%%%%%%%
-some
+fake
+++++++
conflict
>>>>>>>
"},
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj([
"resolve",
"--config=merge-tools.fake-editor.merge-tool-edits-conflict-markers=true",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Resolving conflicts in: file
Working copy (@) now at: vruxwmqv 8f3421d9 conflict | (conflict) conflict
Parent commit (@-) : zsuskuln 45537d53 a | a
Parent commit (@-) : royxmykx 89d1b299 b | b
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict
New conflicts appeared in 1 commits:
vruxwmqv 8f3421d9 conflict | (conflict) conflict
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new vruxwmqv
Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved, you can inspect the result with `jj diff`.
Then run `jj squash` to move the resolution into the conflicted commit.
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor2")).unwrap(), @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: zsuskuln 45537d53 "a"
-base
+a
+++++++ royxmykx 89d1b299 "b"
b
>>>>>>> conflict 1 of 1 ends
"#);
// Note the "Modified" below
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @r#"
diff --git a/file b/file
--- a/file
+++ b/file
@@ -1,8 +1,8 @@
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: zsuskuln 45537d53 "a"
--base
-+a
+-some
++fake
+++++++ royxmykx 89d1b299 "b"
-b
+conflict
>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
file 2-sided conflict
[EOF]
");
// Check that if merge tool leaves conflict markers in output file but
// `merge-tool-edits-conflict-markers=false` or is not specified,
// `jj` considers the conflict resolved.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @"");
std::fs::write(
&editor_script,
[
"dump editor3",
indoc! {"
write
<<<<<<<
%%%%%%%
-some
+fake
+++++++
conflict
>>>>>>>
"},
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["resolve"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Resolving conflicts in: file
Working copy (@) now at: vruxwmqv 2cc7f5e3 conflict | conflict
Parent commit (@-) : zsuskuln 45537d53 a | a
Parent commit (@-) : royxmykx 89d1b299 b | b
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor3")).unwrap(), @"");
// Note the "Resolved" below
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @r#"
diff --git a/file b/file
index 0000000000..0610716cc1 100644
--- a/file
+++ b/file
@@ -1,8 +1,7 @@
-<<<<<<< conflict 1 of 1
-%%%%%%% diff from: rlvkpnrz 1792382a "base"
-\\\\\\\ to: zsuskuln 45537d53 "a"
--base
-+a
-+++++++ royxmykx 89d1b299 "b"
-b
->>>>>>> conflict 1 of 1 ends
+<<<<<<<
+%%%%%%%
+-some
++fake
++++++++
+conflict
+>>>>>>>
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
------- stderr -------
Error: No conflicts found at this revision
[EOF]
[exit status: 2]
");
// 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(
&editor_script,
[
"dump editor4",
indoc! {"
write
<<<<<<<
some
|||||||
fake
=======
conflict
>>>>>>>
"},
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj([
"resolve",
"--config=merge-tools.fake-editor.merge-tool-edits-conflict-markers=true",
"--config=merge-tools.fake-editor.conflict-marker-style=git",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Resolving conflicts in: file
Working copy (@) now at: vruxwmqv 7abbf396 conflict | (conflict) conflict
Parent commit (@-) : zsuskuln 45537d53 a | a
Parent commit (@-) : royxmykx 89d1b299 b | b
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict
New conflicts appeared in 1 commits:
vruxwmqv 7abbf396 conflict | (conflict) conflict
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new vruxwmqv
Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved, you can inspect the result with `jj diff`.
Then run `jj squash` to move the resolution into the conflicted commit.
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor4")).unwrap(), @r#"
<<<<<<< zsuskuln 45537d53 "a"
a
||||||| rlvkpnrz 1792382a "base"
base
=======
b
>>>>>>> royxmykx 89d1b299 "b"
"#);
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @r#"
diff --git a/file b/file
--- a/file
+++ b/file
@@ -1,8 +1,8 @@
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: zsuskuln 45537d53 "a"
--base
-+a
+-fake
++some
+++++++ royxmykx 89d1b299 "b"
-b
+conflict
>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
file 2-sided conflict
[EOF]
");
// Check that merge tool can leave conflict markers by returning exit code 1
// when using `merge-conflict-exit-codes = [1]`. The Git "diff3" conflict
// markers should also be parsed correctly.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @"");
std::fs::write(
&editor_script,
[
"dump editor5",
indoc! {"
write
<<<<<<<
some
|||||||
fake
=======
conflict
>>>>>>>
"},
"fail",
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj([
"resolve",
"--config=merge-tools.fake-editor.merge-conflict-exit-codes=[1]",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Resolving conflicts in: file
Working copy (@) now at: vruxwmqv c7b8c740 conflict | (conflict) conflict
Parent commit (@-) : zsuskuln 45537d53 a | a
Parent commit (@-) : royxmykx 89d1b299 b | b
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict
New conflicts appeared in 1 commits:
vruxwmqv c7b8c740 conflict | (conflict) conflict
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new vruxwmqv
Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved, you can inspect the result with `jj diff`.
Then run `jj squash` to move the resolution into the conflicted commit.
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor5")).unwrap(), @"");
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @r#"
diff --git a/file b/file
--- a/file
+++ b/file
@@ -1,8 +1,8 @@
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: zsuskuln 45537d53 "a"
--base
-+a
+-fake
++some
+++++++ royxmykx 89d1b299 "b"
-b
+conflict
>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
file 2-sided conflict
[EOF]
");
// 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.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @"");
std::fs::write(
&editor_script,
[
indoc! {"
write
<<<<<<< this isn't diff3 style!
some
=======
conflict
>>>>>>>
"},
"fail",
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj([
"resolve",
"--config=merge-tools.fake-editor.merge-conflict-exit-codes=[1]",
]);
insta::assert_snapshot!(output.normalize_stderr_exit_status(), @r"
------- stderr -------
Resolving conflicts in: file
Error: Failed to resolve conflicts
Caused by: Tool exited with exit status: 1, but did not produce valid conflict markers (run with --debug to see the exact invocation)
[EOF]
[exit status: 1]
");
}
#[test]
fn test_files_still_have_conflicts() {
let mut test_env = TestEnvironment::default();
let editor_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// set up the commit graph
create_commit_with_files(
&work_dir,
"base",
&[],
&[("file1", "base\n"), ("file2", "base\n")],
);
create_commit_with_files(
&work_dir,
"a",
&["base"],
&[("file1", "a\n"), ("file2", "a\n")],
);
create_commit_with_files(
&work_dir,
"b",
&["base"],
&[("file1", "b\n"), ("file2", "b\n")],
);
create_commit_with_files(&work_dir, "conflict", &["a", "b"], &[]);
create_commit_with_files(&work_dir, "c", &["conflict"], &[]);
create_commit_with_files(&work_dir, "d", &["base"], &[]);
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d
โ ร c
โ ร conflict
โ โโโฎ
โ โ โ b
โโโโโฏ
โ โ a
โโโฏ
โ base
โ
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// partially resolve the conflict from an unaffected sibling
std::fs::write(&editor_script, "write\nresolution\n").unwrap();
let output = work_dir.run_jj([
"resolve",
"-r",
"conflict",
"file1",
"--config",
"hints.resolving-conflicts=false",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Resolving conflicts in: file1
Rebased 1 descendant commits
New conflicts appeared in 1 commits:
vruxwmqv 33dabe14 conflict | (conflict) conflict
Warning: After this operation, some files at this revision still have conflicts:
file2 2-sided conflict
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// partially resolve the conflict from a descendant
work_dir.run_jj(["edit", "c"]).success();
let output = work_dir.run_jj([
"resolve",
"-r",
"conflict",
"file1",
"--config",
"hints.resolving-conflicts=false",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Resolving conflicts in: file1
Rebased 1 descendant commits
Working copy (@) now at: znkkpsqq 0c56f122 c | (conflict) (empty) c
Parent commit (@-) : vruxwmqv f3962c75 conflict | (conflict) conflict
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file2 2-sided conflict
New conflicts appeared in 1 commits:
vruxwmqv f3962c75 conflict | (conflict) conflict
Warning: After this operation, some files at this revision still have conflicts:
file2 2-sided conflict
[EOF]
");
}
fn check_resolve_produces_input_file(
test_env: &mut TestEnvironment,
root: impl AsRef<Path>,
filename: &str,
role: &str,
expected_content: &str,
) {
let editor_script = test_env.set_up_fake_editor();
let work_dir = test_env.work_dir(root);
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.
let output = work_dir.run_jj(["resolve", "--config", &merge_arg_config, filename]);
insta::allow_duplicates! {
insta::assert_snapshot!(
output.normalize_stderr_with(|s| s.replacen(filename, "$FILENAME", 1)), @r"
------- stderr -------
Resolving conflicts in: $FILENAME
Error: Failed to resolve conflicts
Caused by: The output file is either unchanged or empty after the editor quit (run with --debug to see the exact invocation).
[EOF]
[exit status: 1]
");
}
}
#[test]
fn test_normal_conflict_input_files() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
create_commit_with_files(&work_dir, "a", &["base"], &[("file", "a\n")]);
create_commit_with_files(&work_dir, "b", &["base"], &[("file", "b\n")]);
create_commit_with_files(&work_dir, "conflict", &["a", "b"], &[]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ conflict
โโโฎ
โ โ b
โ โ a
โโโฏ
โ base
โ
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
file 2-sided conflict
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: zsuskuln 45537d53 "a"
-base
+a
+++++++ royxmykx 89d1b299 "b"
b
>>>>>>> conflict 1 of 1 ends
"#);
check_resolve_produces_input_file(&mut test_env, "repo", "file", "base", "base\n");
check_resolve_produces_input_file(&mut test_env, "repo", "file", "left", "a\n");
check_resolve_produces_input_file(&mut test_env, "repo", "file", "right", "b\n");
}
#[test]
fn test_baseless_conflict_input_files() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "base", &[], &[]);
create_commit_with_files(&work_dir, "a", &["base"], &[("file", "a\n")]);
create_commit_with_files(&work_dir, "b", &["base"], &[("file", "b\n")]);
create_commit_with_files(&work_dir, "conflict", &["a", "b"], &[]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ conflict
โโโฎ
โ โ b
โ โ a
โโโฏ
โ base
โ
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
file 2-sided conflict
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 2308e5a2 "base"
\\\\\\\ to: zsuskuln e3c7222d "a"
+a
+++++++ royxmykx 1f2c13ec "b"
b
>>>>>>> conflict 1 of 1 ends
"#);
check_resolve_produces_input_file(&mut test_env, "repo", "file", "base", "");
check_resolve_produces_input_file(&mut test_env, "repo", "file", "left", "a\n");
check_resolve_produces_input_file(&mut test_env, "repo", "file", "right", "b\n");
}
#[test]
fn test_too_many_parents() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
create_commit_with_files(&work_dir, "a", &["base"], &[("file", "a\n")]);
create_commit_with_files(&work_dir, "b", &["base"], &[("file", "b\n")]);
create_commit_with_files(&work_dir, "c", &["base"], &[("file", "c\n")]);
create_commit_with_files(&work_dir, "conflict", &["a", "b", "c"], &[]);
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
file 3-sided conflict
[EOF]
");
// Test warning color
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list", "--color=always"]), @r"
file [38;5;1m3-sided[38;5;3m conflict[39m
[EOF]
");
let output = work_dir.run_jj(["resolve"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Hint: Using default editor ':builtin'; run `jj config set --user ui.merge-editor :builtin` to disable this message.
Error: Failed to resolve conflicts
Caused by: The conflict at "file" has 3 sides. At most 2 sides are supported.
Hint: Edit the conflict markers manually to resolve this.
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_simplify_conflict_sides() {
let mut test_env = TestEnvironment::default();
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
// fileB: A - A + A - A + B - C + D
create_commit_with_files(
&work_dir,
"base",
&[],
&[("fileA", "base\n"), ("fileB", "base\n")],
);
create_commit_with_files(&work_dir, "a1", &["base"], &[("fileA", "1\n")]);
create_commit_with_files(&work_dir, "a2", &["base"], &[("fileA", "2\n")]);
create_commit_with_files(&work_dir, "b1", &["base"], &[("fileB", "1\n")]);
create_commit_with_files(&work_dir, "b2", &["base"], &[("fileB", "2\n")]);
create_commit_with_files(&work_dir, "conflictA", &["a1", "a2"], &[]);
create_commit_with_files(&work_dir, "conflictB", &["b1", "b2"], &[]);
create_commit_with_files(&work_dir, "conflict", &["conflictA", "conflictB"], &[]);
// Even though the tree-level conflict is a 4-sided conflict, each file is
// materialized as a 2-sided conflict.
insta::assert_snapshot!(work_dir.run_jj(["debug", "tree"]), @r#"
fileA: Ok(Conflicted([Some(File { id: FileId("d00491fd7e5bb6fa28c517a0bb32b8b506539d4d"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("0cfbf08886fca9a91cb753ec8734c84fcbe52c9f"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") })]))
fileB: Ok(Conflicted([Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("d00491fd7e5bb6fa28c517a0bb32b8b506539d4d"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("0cfbf08886fca9a91cb753ec8734c84fcbe52c9f"), executable: false, copy_id: CopyId("") })]))
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
fileA 2-sided conflict
fileB 2-sided conflict
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("fileA"), @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz ca4643d3 "base"
\\\\\\\ to: zsuskuln f302fbd1 "a1"
-base
+1
+++++++ royxmykx 128a2559 "a2"
2
>>>>>>> conflict 1 of 1 ends
"#);
insta::assert_snapshot!(work_dir.read_file("fileB"), @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz ca4643d3 "base"
\\\\\\\ to: vruxwmqv 5be2d37a "b1"
-base
+1
+++++++ znkkpsqq bd8e6328 "b2"
2
>>>>>>> conflict 1 of 1 ends
"#);
// 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");
check_resolve_produces_input_file(&mut test_env, "repo", "fileB", "base", "base\n");
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`.
let editor_script = test_env.set_up_fake_editor();
std::fs::write(
editor_script,
indoc! {"
write
<<<<<<< conflict 1 of 1
%%%%%%% diff from base to side #1
-base_edited
+1_edited
+++++++ side #2
2_edited
>>>>>>> conflict 1 of 1 ends
"},
)
.unwrap();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj([
"resolve",
"--config=merge-tools.fake-editor.merge-tool-edits-conflict-markers=true",
"fileB",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Resolving conflicts in: fileB
Working copy (@) now at: nkmrtpmo e8ca5990 conflict | (conflict) conflict
Parent commit (@-) : kmkuslsw 0fb57c44 conflictA | (conflict) (empty) conflictA
Parent commit (@-) : lylxulpl 4ec7381a conflictB | (conflict) (empty) conflictB
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
fileA 2-sided conflict
fileB 2-sided conflict
New conflicts appeared in 1 commits:
nkmrtpmo e8ca5990 conflict | (conflict) conflict
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new nkmrtpmo
Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved, you can inspect the result with `jj diff`.
Then run `jj squash` to move the resolution into the conflicted commit.
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("fileB"), @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz ca4643d3 "base"
\\\\\\\ to: vruxwmqv 5be2d37a "b1"
-base_edited
+1_edited
+++++++ znkkpsqq bd8e6328 "b2"
2_edited
>>>>>>> conflict 1 of 1 ends
"#);
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
fileA 2-sided conflict
fileB 2-sided conflict
[EOF]
");
}
#[test]
fn test_edit_delete_conflict_input_files() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
create_commit_with_files(&work_dir, "a", &["base"], &[("file", "a\n")]);
create_commit_with_files(&work_dir, "b", &["base"], &[]);
work_dir.remove_file("file");
create_commit_with_files(&work_dir, "conflict", &["a", "b"], &[]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ conflict
โโโฎ
โ โ b
โ โ a
โโโฏ
โ base
โ
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["resolve", "--list"]), @r"
file 2-sided conflict including 1 deletion
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @r#"
<<<<<<< conflict 1 of 1
+++++++ zsuskuln 45537d53 "a"
a
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: royxmykx d213fd81 "b"
-base
>>>>>>> conflict 1 of 1 ends
"#);
check_resolve_produces_input_file(&mut test_env, "repo", "file", "base", "base\n");
check_resolve_produces_input_file(&mut test_env, "repo", "file", "left", "a\n");
check_resolve_produces_input_file(&mut test_env, "repo", "file", "right", "");
}
#[test]
fn test_file_vs_dir() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_git_colocation.rs | cli/tests/test_git_colocation.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[must_use]
fn get_colocation_status(work_dir: &TestWorkDir) -> CommandOutput {
work_dir.run_jj([
"git",
"colocation",
"status",
"--ignore-working-copy",
"--quiet", // suppress hint
])
}
fn read_git_target(workspace_root: &std::path::Path) -> String {
let mut path = workspace_root.to_path_buf();
path.extend([".jj", "repo", "store", "git_target"]);
std::fs::read_to_string(path).unwrap()
}
#[test]
fn test_git_colocation_enable_success() {
let test_env = TestEnvironment::default();
// Initialize a non-colocated Jujutsu/Git workspace
test_env
.run_jj_in(
test_env.env_root(),
["git", "init", "--no-colocate", "repo"],
)
.success();
let work_dir = test_env.work_dir("repo");
let workspace_root = work_dir.root();
// Need at least one commit to be able to set git HEAD later
work_dir.run_jj(["new"]).success();
// Verify it's not colocated initially
assert!(!workspace_root.join(".git").exists());
assert_eq!(read_git_target(workspace_root), "git");
// And that there is no Git HEAD yet
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently not colocated with Git.
Last imported/exported Git HEAD: (none)
[EOF]
");
// Run colocate command
let output = work_dir.run_jj(["git", "colocation", "enable"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Workspace successfully converted into a colocated Jujutsu/Git workspace.
[EOF]
");
// Verify colocate succeeded
assert!(workspace_root.join(".git").exists());
assert!(
!workspace_root
.join(".jj")
.join("repo")
.join("store")
.join("git")
.exists()
);
assert_eq!(read_git_target(workspace_root), "../../../.git");
// Verify .jj/.gitignore was created
let gitignore_content =
std::fs::read_to_string(workspace_root.join(".jj").join(".gitignore")).unwrap();
assert_eq!(gitignore_content, "/*\n");
// Verify that Git HEAD was set correctly
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: e8849ae12c709f2321908879bc724fdb2ab8a781
[EOF]
");
}
#[test]
fn test_git_colocation_enable_already_colocated() {
let test_env = TestEnvironment::default();
// Initialize a colocated Jujutsu/Git repo
test_env
.run_jj_in(test_env.env_root(), ["git", "init", "--colocate", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
// Try to colocate it again - should fail
let output = work_dir.run_jj(["git", "colocation", "enable"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Workspace is already colocated with Git.
[EOF]
");
}
#[test]
fn test_git_colocation_enable_with_existing_git_dir() {
let test_env = TestEnvironment::default();
// Initialize a non-colocated Jujutsu/Git repo
test_env
.run_jj_in(
test_env.env_root(),
["git", "init", "--no-colocate", "repo"],
)
.success();
let work_dir = test_env.work_dir("repo");
let workspace_root = work_dir.root();
// Create a .git directory manually
std::fs::create_dir(workspace_root.join(".git")).unwrap();
std::fs::write(workspace_root.join(".git").join("dummy"), "dummy").unwrap();
// Try to colocate - should fail
let output = work_dir.run_jj(["git", "colocation", "enable"]);
insta::assert_snapshot!(output.strip_stderr_last_line(), @r"
------- stderr -------
Error: A .git directory already exists in the workspace root. Cannot colocate.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_colocation_disable_success() {
let test_env = TestEnvironment::default();
// Create a colocated Jujutsu/Git repo
test_env
.run_jj_in(test_env.env_root(), ["git", "init", "--colocate", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
let workspace_root = work_dir.root();
// Need at least one commit to be able to set git HEAD later
work_dir.run_jj(["new"]).success();
// Verify that Git HEAD is set
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: e8849ae12c709f2321908879bc724fdb2ab8a781
[EOF]
");
// Verify it's colocated
assert!(workspace_root.join(".git").exists());
assert_eq!(read_git_target(workspace_root), "../../../.git");
// Disable colocation
let output = work_dir.run_jj(["git", "colocation", "disable"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Workspace successfully converted into a non-colocated Jujutsu/Git workspace.
[EOF]
");
// Verify that disable colocation succeeded
assert!(!workspace_root.join(".git").exists());
assert!(
workspace_root
.join(".jj")
.join("repo")
.join("store")
.join("git")
.exists()
);
assert_eq!(read_git_target(workspace_root), "git");
assert!(!workspace_root.join(".jj").join(".gitignore").exists());
// Verify that Git HEAD was removed correctly
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently not colocated with Git.
Last imported/exported Git HEAD: (none)
[EOF]
");
}
#[test]
fn test_git_colocation_disable_not_colocated() {
let test_env = TestEnvironment::default();
// Initialize a non-colocated Jujutsu/Git repo
test_env
.run_jj_in(
test_env.env_root(),
["git", "init", "--no-colocate", "repo"],
)
.success();
let work_dir = test_env.work_dir("repo");
// Try to disable colocation when not colocated - should fail
let output = work_dir.run_jj(["git", "colocation", "disable"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Workspace is already not colocated with Git.
[EOF]
");
}
#[test]
fn test_git_colocation_status_non_colocated() {
let test_env = TestEnvironment::default();
// Initialize a non-colocated Jujutsu/Git repo
test_env
.run_jj_in(
test_env.env_root(),
["git", "init", "--no-colocate", "repo"],
)
.success();
let work_dir = test_env.work_dir("repo");
// Check status - should show non-colocated
let output = work_dir.run_jj(["git", "colocation", "status"]);
insta::assert_snapshot!(output, @r"
Workspace is currently not colocated with Git.
Last imported/exported Git HEAD: (none)
[EOF]
------- stderr -------
Hint: To enable colocation, run: `jj git colocation enable`
[EOF]
");
}
#[test]
fn test_git_colocation_status_colocated() {
let test_env = TestEnvironment::default();
// Initialize a colocated jj repo
test_env
.run_jj_in(test_env.env_root(), ["git", "init", "--colocate", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
// Check status - should show colocated
let output = work_dir.run_jj(["git", "colocation", "status"]);
insta::assert_snapshot!(output, @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: (none)
[EOF]
------- stderr -------
Hint: To disable colocation, run: `jj git colocation disable`
[EOF]
");
}
#[test]
fn test_git_colocation_in_secondary_workspace() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--no-colocate", "main"])
.success();
let main_dir = test_env.work_dir("main");
main_dir
.run_jj(["workspace", "add", "../secondary"])
.success();
let secondary_dir = test_env.work_dir("secondary");
let output = secondary_dir.run_jj(["git", "colocation", "status"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: This command cannot be used in a non-main Jujutsu workspace
[EOF]
[exit status: 1]
");
let output = secondary_dir.run_jj(["git", "colocation", "enable"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: This command cannot be used in a non-main Jujutsu workspace
[EOF]
[exit status: 1]
");
let output = secondary_dir.run_jj(["git", "colocation", "disable"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: This command cannot be used in a non-main Jujutsu workspace
[EOF]
[exit status: 1]
");
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_file_track_untrack_commands.rs | cli/tests/test_file_track_untrack_commands.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::TestEnvironment;
#[test]
fn test_track_untrack() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "initial");
work_dir.write_file("file1.bak", "initial");
work_dir.write_file("file2.bak", "initial");
let target_dir = work_dir.create_dir("target");
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
work_dir.run_jj(["st"]).success();
work_dir.write_file(".gitignore", "*.bak\n");
let files_before = work_dir.run_jj(["file", "list"]).success();
// Errors out when not run at the head operation
let output = work_dir.run_jj(["file", "untrack", "file1", "--at-op", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: This command must be able to update the working copy.
Hint: Don't use --at-op.
[EOF]
[exit status: 1]
");
// Errors out when no path is specified
let output = work_dir.run_jj(["file", "untrack"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the following required arguments were not provided:
<FILESETS>...
Usage: jj file untrack <FILESETS>...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Errors out when a specified file is not ignored
let output = work_dir.run_jj(["file", "untrack", "file1", "file1.bak"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: 'file1' is not ignored.
Hint: Files that are not ignored will be added back by the next command.
Make sure they're ignored, then try again.
[EOF]
[exit status: 1]
");
let files_after = work_dir.run_jj(["file", "list"]).success();
// There should be no changes to the state when there was an error
assert_eq!(files_after, files_before);
// Can untrack a single file
assert!(files_before.stdout.raw().contains("file1.bak\n"));
let output = work_dir.run_jj(["file", "untrack", "file1.bak"]);
insta::assert_snapshot!(output, @"");
let files_after = work_dir.run_jj(["file", "list"]).success();
// The file is no longer tracked
assert!(!files_after.stdout.raw().contains("file1.bak"));
// Other files that match the ignore pattern are not untracked
assert!(files_after.stdout.raw().contains("file2.bak"));
// The files still exist on disk
assert!(work_dir.root().join("file1.bak").exists());
assert!(work_dir.root().join("file2.bak").exists());
// Warns if path doesn't exist
let output = work_dir.run_jj(["file", "untrack", "nonexistent"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
[EOF]
");
// Errors out when multiple specified files are not ignored
let output = work_dir.run_jj(["file", "untrack", "target"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
------- stderr -------
Error: 'target/file2' and 1 other files are not ignored.
Hint: Files that are not ignored will be added back by the next command.
Make sure they're ignored, then try again.
[EOF]
[exit status: 1]
");
// Can untrack after adding to ignore patterns
work_dir.write_file(".gitignore", "*.bak\ntarget/\n");
let output = work_dir.run_jj(["file", "untrack", "target"]);
insta::assert_snapshot!(output, @"");
let files_after = work_dir.run_jj(["file", "list"]).success();
assert!(!files_after.stdout.raw().contains("target"));
}
#[test]
fn test_track_untrack_sparse() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "contents");
work_dir.write_file("file2", "contents");
// When untracking a file that's not included in the sparse working copy, it
// doesn't need to be ignored (because it won't be automatically added
// back).
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
file1
file2
[EOF]
");
work_dir
.run_jj(["sparse", "set", "--clear", "--add", "file1"])
.success();
let output = work_dir.run_jj(["file", "untrack", "file2"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
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
let output = work_dir.run_jj(["file", "track", "file2"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
file1
[EOF]
");
}
#[test]
fn test_auto_track() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"snapshot.auto-track = 'glob:*.rs'"#);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1.rs", "initial");
work_dir.write_file("file2.md", "initial");
work_dir.write_file("file3.md", "initial");
// Only configured paths get auto-tracked
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
file1.rs
[EOF]
");
// Can manually track paths
let output = work_dir.run_jj(["file", "track", "file3.md"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
file1.rs
file3.md
[EOF]
");
// Can manually untrack paths
let output = work_dir.run_jj(["file", "untrack", "file3.md"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
file1.rs
[EOF]
");
// 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"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
../file1.rs
[EOF]
");
// But `jj file track` wants CWD-relative paths
let output = sub_dir.run_jj(["file", "track", "file1.rs"]);
insta::assert_snapshot!(output, @"");
let output = sub_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
../file1.rs
file1.rs
[EOF]
");
}
#[test]
fn test_track_ignored() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"snapshot.auto-track = 'none()'"#);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Trackable files exist but auto-tracking is not enabled
work_dir.write_file(".gitignore", "*.bak\n");
work_dir.write_file("file1", "initial");
work_dir.write_file("file1.bak", "initial");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @"");
// Create a descendant, updates will be seen as rebases
work_dir.run_jj(["new", "--no-edit"]).success();
// Track an unignored path
// TODO: fix GH #8298 so tracking is immediate
let output = work_dir.run_jj(["file", "track", "file1"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @"
file1
[EOF]
------- stderr -------
Rebased 1 descendant commits onto updated working copy
[EOF]
");
// Track another unignored path
work_dir.write_file("file2", "initial");
let output = work_dir.run_jj(["file", "track", "file2"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @"
file1
file2
[EOF]
------- stderr -------
Rebased 1 descendant commits onto updated working copy
[EOF]
");
// Now untrack the file; eviction is immediate and affects descendants
let output = work_dir.run_jj(["file", "untrack", "file2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
[EOF]
");
// Track an ignored path without --include-ignored (should not work)
let output = work_dir.run_jj(["file", "track", "file1.bak"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
file1
[EOF]
");
}
#[test]
fn test_track_ignored_with_flag() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file(".gitignore", "*.ignored\n");
work_dir.write_file("file1.txt", "content");
work_dir.write_file("file2.ignored", "ignored content");
// Test the setup
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
.gitignore
file1.txt
[EOF]
");
// Track ignored file with --include-ignored
let output = work_dir.run_jj(["file", "track", "--include-ignored", "file2.ignored"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
.gitignore
file1.txt
file2.ignored
[EOF]
");
}
#[test]
fn test_track_large_file_with_flag() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"snapshot.max-new-file-size = "10""#);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("small.txt", "small");
work_dir.write_file("large.txt", "a".repeat(20).as_str());
// Test the setup
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
small.txt
[EOF]
------- stderr -------
Warning: Refused to snapshot some files:
large.txt: 20.0B (20 bytes); the maximum size allowed is 10.0B (10 bytes)
Hint: This is to prevent large files from being added by accident. You can fix this by:
- Adding the file to `.gitignore`
- Run `jj config set --repo snapshot.max-new-file-size 20`
This will increase the maximum file size allowed for new files, in this repository only.
- Run `jj --config snapshot.max-new-file-size=20 st`
This will increase the maximum file size allowed for new files, for this command only.
[EOF]
");
// Track large file with --include-ignored
let output = work_dir.run_jj(["file", "track", "--include-ignored", "large.txt"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Refused to snapshot some files:
large.txt: 20.0B (20 bytes); the maximum size allowed is 10.0B (10 bytes)
Hint: This is to prevent large files from being added by accident. You can fix this by:
- Adding the file to `.gitignore`
- Run `jj config set --repo snapshot.max-new-file-size 20`
This will increase the maximum file size allowed for new files, in this repository only.
- Run `jj --config snapshot.max-new-file-size=20 file track large.txt`
This will increase the maximum file size allowed for new files, for this command only.
- Run `jj file track --include-ignored large.txt`
This will track the files even though they exceed the size limit.
[EOF]
");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
large.txt
small.txt
[EOF]
");
}
#[test]
fn test_track_ignored_directory() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file(".gitignore", "ignored_dir/\n");
let ignored_dir = work_dir.create_dir("ignored_dir");
ignored_dir.write_file("file1.txt", "content1");
ignored_dir.write_file("file2.txt", "content2");
// Test the setup
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
.gitignore
[EOF]
");
// Track ignored directory with --include-ignored
let output = work_dir.run_jj(["file", "track", "--include-ignored", "ignored_dir"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
.gitignore
ignored_dir/file1.txt
ignored_dir/file2.txt
[EOF]
");
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_parallelize_command.rs | cli/tests/test_parallelize_command.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_parallelize_no_descendants() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
for n in 1..6 {
work_dir.run_jj(["commit", &format!("-m{n}")]).success();
}
work_dir.run_jj(["describe", "-m=6"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e12cca0818cd 6 parents: 5
โ 44f4686efbe9 5 parents: 4
โ 6858f6e16a6c 4 parents: 3
โ 8cfb27e238c8 3 parents: 2
โ 320daf48ba58 2 parents: 1
โ 884fe9b9c656 1 parents:
โ 000000000000 parents:
[EOF]
");
work_dir.run_jj(["parallelize", "subject(1)::"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 22b8a32d1949 6 parents:
โ โ 436e81ced43f 5 parents:
โโโฏ
โ โ 823bf930aefb 4 parents:
โโโฏ
โ โ 3b6586259aa9 3 parents:
โโโฏ
โ โ dfd927ce07c0 2 parents:
โโโฏ
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
// Only the head commit has descendants.
#[test]
fn test_parallelize_with_descendants_simple() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
for n in 1..6 {
work_dir.run_jj(["commit", &format!("-m{n}")]).success();
}
work_dir.run_jj(["describe", "-m=6"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e12cca0818cd 6 parents: 5
โ 44f4686efbe9 5 parents: 4
โ 6858f6e16a6c 4 parents: 3
โ 8cfb27e238c8 3 parents: 2
โ 320daf48ba58 2 parents: 1
โ 884fe9b9c656 1 parents:
โ 000000000000 parents:
[EOF]
");
work_dir
.run_jj(["parallelize", "subject(1)::subject(4)"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 75ac07d7dedc 6 parents: 5
โ 39791a4c42c5 5 parents: 1 2 3 4
โโโฌโโฌโโฎ
โ โ โ โ 823bf930aefb 4 parents:
โ โ โ โ 3b6586259aa9 3 parents:
โ โ โโโฏ
โ โ โ dfd927ce07c0 2 parents:
โ โโโฏ
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
// One of the commits being parallelized has a child that isn't being
// parallelized. That child will become a merge of any ancestors which are being
// parallelized.
#[test]
fn test_parallelize_where_interior_has_non_target_children() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
for n in 1..6 {
work_dir.run_jj(["commit", &format!("-m{n}")]).success();
}
work_dir.run_jj(["new", "subject(2)", "-m=2c"]).success();
work_dir.run_jj(["new", "subject(5)", "-m=6"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 9554e07afe42 6 parents: 5
โ 44f4686efbe9 5 parents: 4
โ 6858f6e16a6c 4 parents: 3
โ 8cfb27e238c8 3 parents: 2
โ โ a5a460ad9943 2c parents: 2
โโโฏ
โ 320daf48ba58 2 parents: 1
โ 884fe9b9c656 1 parents:
โ 000000000000 parents:
[EOF]
");
work_dir
.run_jj(["parallelize", "subject(1)::subject(4)"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 8bbff9ba415a 6 parents: 5
โ 3bfb6f7542f6 5 parents: 1 2 3 4
โโโฌโโฌโโฎ
โ โ โ โ 486dfbb53401 4 parents:
โ โ โ โ 71c114f0dd4d 3 parents:
โ โ โโโฏ
โ โ โ โ 154d3801414a 2c parents: 1 2
โญโโฌโโโโฏ
โ โ โ 7c8f6e529b52 2 parents:
โ โโโฏ
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_where_root_has_non_target_children() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
for n in 1..4 {
work_dir.run_jj(["commit", &format!("-m{n}")]).success();
}
work_dir.run_jj(["new", "subject(1)", "-m=1c"]).success();
work_dir.run_jj(["new", "subject(3)", "-m=4"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 4c392c2965f0 4 parents: 3
โ 8cfb27e238c8 3 parents: 2
โ 320daf48ba58 2 parents: 1
โ โ 2935e6f82e54 1c parents: 1
โโโฏ
โ 884fe9b9c656 1 parents:
โ 000000000000 parents:
[EOF]
");
work_dir
.run_jj(["parallelize", "subject(1)::subject(3)"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ a5d4e90a54bf 4 parents: 1 2 3
โโโฌโโฎ
โ โ โ 1d9fa9e05929 3 parents:
โ โ โ f773cf087413 2 parents:
โ โโโฏ
โ โ โ 2935e6f82e54 1c parents: 1
โโโโโฏ
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
// One of the commits being parallelized has a child that is a merge commit.
#[test]
fn test_parallelize_with_merge_commit_child() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "1"]).success();
for n in 2..4 {
work_dir.run_jj(["commit", "-m", &n.to_string()]).success();
}
work_dir.run_jj(["new", "root()", "-m", "a"]).success();
work_dir
.run_jj(["new", "subject(2)", "subject(a)", "-m", "2a-c"])
.success();
work_dir.run_jj(["new", "subject(3)", "-m", "4"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e6a543fcc5d8 4 parents: 3
โ 8cfb27e238c8 3 parents: 2
โ โ af7ad8059bf1 2a-c parents: 2 a
โญโโค
โ โ 8fa549442479 a parents:
โ โ 320daf48ba58 2 parents: 1
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
// After this finishes, child-2a will have three parents: "1", "2", and "a".
work_dir
.run_jj(["parallelize", "subject(1)::subject(3)"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 431d5005bab0 4 parents: 1 2 3
โโโฌโโฎ
โ โ โ 3b6586259aa9 3 parents:
โ โ โ โ 67b28b5cc688 2a-c parents: 1 2 a
โญโโฌโโโโค
โ โ โ โ 8fa549442479 a parents:
โ โ โโโฏ
โ โ โ dfd927ce07c0 2 parents:
โ โโโฏ
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_disconnected_target_commits() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
for n in 1..3 {
work_dir.run_jj(["commit", &format!("-m{n}")]).success();
}
work_dir.run_jj(["describe", "-m=3"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 8cfb27e238c8 3 parents: 2
โ 320daf48ba58 2 parents: 1
โ 884fe9b9c656 1 parents:
โ 000000000000 parents:
[EOF]
");
let output = work_dir.run_jj(["parallelize", "subject(1)", "subject(3)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 8cfb27e238c8 3 parents: 2
โ 320daf48ba58 2 parents: 1
โ 884fe9b9c656 1 parents:
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_head_is_a_merge() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m=0"]).success();
work_dir.run_jj(["commit", "-m=1"]).success();
work_dir.run_jj(["commit", "-m=2"]).success();
work_dir.run_jj(["new", "root()"]).success();
work_dir.run_jj(["commit", "-m=a"]).success();
work_dir.run_jj(["commit", "-m=b"]).success();
work_dir
.run_jj(["new", "subject(2)", "subject(b)", "-m=merged-head"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c634925e6ac2 merged-head parents: 2 b
โโโฎ
โ โ 448c6310957c b parents: a
โ โ 07fb6466f0cd a parents:
โ โ 1ae5c538c8ef 2 parents: 1
โ โ 42fc76489fb1 1 parents: 0
โ โ fc8a812f1b99 0 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
work_dir.run_jj(["parallelize", "subject(1)::"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ f97b547cdca0 merged-head parents: 0 b
โโโฎ
โ โ 448c6310957c b parents: a
โ โ 07fb6466f0cd a parents:
โ โ โ b240f5a52f77 2 parents: 0
โโโโโฏ
โ โ โ 42fc76489fb1 1 parents: 0
โโโโโฏ
โ โ fc8a812f1b99 0 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_interior_target_is_a_merge() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m=0"]).success();
work_dir.run_jj(["describe", "-m=1"]).success();
work_dir.run_jj(["new", "root()", "-m=a"]).success();
work_dir
.run_jj(["new", "subject(1)", "subject(a)", "-m=2"])
.success();
work_dir.run_jj(["new", "-m=3"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d84d604297c3 3 parents: 2
โ 5684656729e6 2 parents: 1 a
โโโฎ
โ โ 55fc07cbd79b a parents:
โ โ 42fc76489fb1 1 parents: 0
โ โ fc8a812f1b99 0 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
work_dir.run_jj(["parallelize", "subject(1)::"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d0dae190124d 3 parents: 0 a
โโโฎ
โ โ โ d5756d591190 2 parents: 0 a
โญโโฌโโฏ
โ โ 55fc07cbd79b a parents:
โ โ โ 42fc76489fb1 1 parents: 0
โโโโโฏ
โ โ fc8a812f1b99 0 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_root_is_a_merge() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m=y"]).success();
work_dir.run_jj(["new", "root()", "-m=x"]).success();
work_dir
.run_jj(["new", "subject(y)", "subject(x)", "-m=1"])
.success();
work_dir.run_jj(["new", "-m=2"]).success();
work_dir.run_jj(["new", "-m=3"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ ce0ec2d2d844 3 parents: 2
โ 44681d919431 2 parents: 1
โ 8a06bcc06aad 1 parents: y x
โโโฎ
โ โ 2d5d6dbc7e1f x parents:
โ โ 1ecf47f2262c y parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
work_dir
.run_jj(["parallelize", "subject(1)::subject(2)"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 2949bc60f108 3 parents: 1 2
โโโฎ
โ โ bf222a0e51d4 2 parents: y x
โ โโโฎ
โ โ โ 8a06bcc06aad 1 parents: y x
โฐโโฌโโฎ
โ โ 2d5d6dbc7e1f x parents:
โ โ 1ecf47f2262c y parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_multiple_heads() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m=0"]).success();
work_dir.run_jj(["describe", "-m=1"]).success();
work_dir.run_jj(["new", "subject(0)", "-m=2"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 96d58e6cf428 2 parents: 0
โ โ 42fc76489fb1 1 parents: 0
โโโฏ
โ fc8a812f1b99 0 parents:
โ 000000000000 parents:
[EOF]
");
work_dir.run_jj(["parallelize", "subject(0)::"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ fefea56b23ab 2 parents:
โ โ c4b1ea1106d1 1 parents:
โโโฏ
โ โ fc8a812f1b99 0 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
// All heads must have the same children as the other heads, but only if they
// have children. In this test only one head has children, so the command
// succeeds.
#[test]
fn test_parallelize_multiple_heads_with_and_without_children() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m=0"]).success();
work_dir.run_jj(["describe", "-m=1"]).success();
work_dir.run_jj(["new", "subject(0)", "-m=2"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 96d58e6cf428 2 parents: 0
โ โ 42fc76489fb1 1 parents: 0
โโโฏ
โ fc8a812f1b99 0 parents:
โ 000000000000 parents:
[EOF]
");
work_dir
.run_jj(["parallelize", "subject(0)", "subject(1)"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 96d58e6cf428 2 parents: 0
โ fc8a812f1b99 0 parents:
โ โ c4b1ea1106d1 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_multiple_roots() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m=1"]).success();
work_dir.run_jj(["new", "root()", "-m=a"]).success();
work_dir
.run_jj(["new", "subject(1)", "subject(a)", "-m=2"])
.success();
work_dir.run_jj(["new", "-m=3"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 9653da1c76e9 3 parents: 2
โ 248a57e1c968 2 parents: 1 a
โโโฎ
โ โ 3ce82963438f a parents:
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
// Succeeds because the roots have the same parents.
work_dir.run_jj(["parallelize", "root().."]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0c77dac691b5 3 parents:
โ โ 1a23775d87d5 2 parents:
โโโฏ
โ โ 3ce82963438f a parents:
โโโฏ
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_multiple_heads_with_different_children() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m=1"]).success();
work_dir.run_jj(["commit", "-m=2"]).success();
work_dir.run_jj(["commit", "-m=3"]).success();
work_dir.run_jj(["new", "root()"]).success();
work_dir.run_jj(["commit", "-m=a"]).success();
work_dir.run_jj(["commit", "-m=b"]).success();
work_dir.run_jj(["commit", "-m=c"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ afa59494cb01 parents: c
โ 8897bad1837f c parents: b
โ 448c6310957c b parents: a
โ 07fb6466f0cd a parents:
โ โ 8cfb27e238c8 3 parents: 2
โ โ 320daf48ba58 2 parents: 1
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
work_dir
.run_jj([
"parallelize",
"subject(1)::subject(2)",
"subject(a)::subject(b)",
])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 7d3e76dfbc7b parents: c
โ 6dbfcf648fad c parents: a b
โโโฎ
โ โ 8e5c55acd419 b parents:
โ โ 07fb6466f0cd a parents:
โโโฏ
โ โ abdef66ee7e9 3 parents: 1 2
โ โโโฎ
โ โ โ 7c8f6e529b52 2 parents:
โโโโโฏ
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_multiple_roots_with_different_parents() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m=1"]).success();
work_dir.run_jj(["commit", "-m=2"]).success();
work_dir.run_jj(["new", "root()"]).success();
work_dir.run_jj(["commit", "-m=a"]).success();
work_dir.run_jj(["commit", "-m=b"]).success();
work_dir
.run_jj(["new", "subject(2)", "subject(b)", "-m=merged-head"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 4e5f16f52b5e merged-head parents: 2 b
โโโฎ
โ โ 7686d0ce4f97 b parents: a
โ โ 331119737aad a parents:
โ โ 320daf48ba58 2 parents: 1
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
work_dir
.run_jj(["parallelize", "subject(2)::", "subject(b)::"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 180840c2f967 merged-head parents: 1 a
โโโฎ
โ โ โ 7686d0ce4f97 b parents: a
โ โโโฏ
โ โ 331119737aad a parents:
โ โ โ 320daf48ba58 2 parents: 1
โโโโโฏ
โ โ 884fe9b9c656 1 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_complex_nonlinear_target() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "-m=0", "root()"]).success();
work_dir.run_jj(["new", "-m=1", "subject(0)"]).success();
work_dir.run_jj(["new", "-m=2", "subject(0)"]).success();
work_dir.run_jj(["new", "-m=3", "subject(0)"]).success();
work_dir.run_jj(["new", "-m=4", "heads(..)"]).success();
work_dir.run_jj(["new", "-m=1c", "subject(1)"]).success();
work_dir.run_jj(["new", "-m=2c", "subject(2)"]).success();
work_dir.run_jj(["new", "-m=3c", "subject(3)"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 5cca06f145b2 3c parents: 3
โ โ 095be6de6f23 4 parents: 3 2 1
โญโโผโโฎ
โ โ โ 46cc2c450bba 3 parents: 0
โ โ โ โ 24113692de1e 2c parents: 2
โ โโโโโฏ
โ โ โ 5664a1d6ac8f 2 parents: 0
โโโฏ โ
โ โ โ 6d578e6cbc1a 1c parents: 1
โ โโโฏ
โ โ 883b398bc1fd 1 parents: 0
โโโฏ
โ 973f85cf2550 0 parents:
โ 000000000000 parents:
[EOF]
");
let output = work_dir.run_jj(["parallelize", "subject(0)::subject(4)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: yostqsxw d6bb6520 (empty) 3c
Parent commit (@-) : rlvkpnrz 973f85cf (empty) 0
Parent commit (@-) : mzvwutvl 47ec86fe (empty) 3
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d6bb652004e4 3c parents: 0 3
โโโฎ
โ โ 47ec86fe7334 3 parents:
โ โ โ 79e22ba7b736 2c parents: 0 2
โญโโโโค
โ โ โ 9d6818f73e0d 2 parents:
โ โโโฏ
โ โ โ bbeb29b59bee 1c parents: 0 1
โญโโโโค
โ โ โ ea96e6d5bb04 1 parents:
โ โโโฏ
โ โ 973f85cf2550 0 parents:
โโโฏ
โ โ 0f9aae95edbe 4 parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_immutable_base_commits() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "root()", "-m=x"]).success();
work_dir.run_jj(["new", "-m=x1"]).success();
work_dir.run_jj(["new", "-m=x2"]).success();
work_dir.run_jj(["new", "-m=x3"]).success();
work_dir.run_jj(["new", "root()", "-m=y"]).success();
work_dir.run_jj(["new", "-m=y1"]).success();
work_dir.run_jj(["new", "-m=y2"]).success();
work_dir
.run_jj([
"config",
"set",
"--repo",
"revset-aliases.'immutable_heads()'",
"subject(x) | subject(y)",
])
.success();
work_dir
.run_jj(["config", "set", "--repo", "revsets.log", "all()"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 1a0f8336974a y2 parents: y1
โ 0e07ea90229f y1 parents: y
โ a0fb97fc193f y parents:
โ โ d6c30fecfe88 x3 parents: x2
โ โ 6411b5818334 x2 parents: x1
โ โ 6d01ab1fb731 x1 parents: x
โ โ 8ceb28e1dc31 x parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
work_dir
.run_jj(["parallelize", "subject(x*)", "subject(y*)"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 264da1b87cf3 y2 parents:
โ โ 636008757721 y1 parents:
โโโฏ
โ โ db5717c9c093 x3 parents:
โโโฏ
โ โ 3e5fc34764e8 x2 parents:
โโโฏ
โ โ 71aeaa5e8891 x1 parents:
โโโฏ
โ โ a0fb97fc193f y parents:
โโโฏ
โ โ 8ceb28e1dc31 x parents:
โโโฏ
โ 000000000000 parents:
[EOF]
");
}
#[test]
fn test_parallelize_no_immutable_non_base_commits() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "root()", "-m=x"]).success();
work_dir.run_jj(["new", "-m=x1"]).success();
work_dir.run_jj(["new", "-m=x2"]).success();
work_dir.run_jj(["new", "-m=x3"]).success();
work_dir
.run_jj([
"config",
"set",
"--repo",
"revset-aliases.'immutable_heads()'",
"subject(x1)",
])
.success();
work_dir
.run_jj(["config", "set", "--repo", "revsets.log", "all()"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d6c30fecfe88 x3 parents: x2
โ 6411b5818334 x2 parents: x1
โ 6d01ab1fb731 x1 parents: x
โ 8ceb28e1dc31 x parents:
โ 000000000000 parents:
[EOF]
");
let output = work_dir.run_jj(["parallelize", "subject(x*)"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 6d01ab1fb731 is immutable
Hint: Could not modify commit: kkmpptxz 6d01ab1f (empty) x1
Hint: Immutable commits are used to protect shared history.
Hint: For more information, see:
- https://docs.jj-vcs.dev/latest/config/#set-of-immutable-commits
- `jj help -k config`, "Set of immutable commits"
Hint: This operation would rewrite 1 immutable commits.
[EOF]
[exit status: 1]
"#);
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"
separate(" ",
commit_id.short(),
description.first_line(),
"parents:",
parents.map(|c|c.description().first_line())
)"#;
work_dir.run_jj(["log", "-T", template])
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_generate_md_cli_help.rs | cli/tests/test_generate_md_cli_help.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use insta::assert_snapshot;
use crate::common::TestEnvironment;
const PREAMBLE: &str = r#"
<!-- BEGIN MARKDOWN-->
"#;
#[test]
fn test_generate_markdown_docs_in_docs_dir() {
let test_env = TestEnvironment::default();
let mut markdown_help = PREAMBLE.to_string();
markdown_help.push_str(
test_env
.run_jj_in(".", ["util", "markdown-help"])
.success()
.stdout
.raw(),
);
insta::with_settings!({
snapshot_path => ".",
snapshot_suffix => ".md",
prepend_module_to_snapshot => false,
omit_expression => true,
description => "AUTO-GENERATED FILE, DO NOT EDIT. This cli reference is generated \
by a test as an `insta` snapshot. MkDocs includes this snapshot \
from docs/cli-reference.md.",
},
{ assert_snapshot!("cli-reference", markdown_help) });
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_concurrent_operations.rs | cli/tests/test_concurrent_operations.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use itertools::Itertools as _;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_concurrent_operation_divergence() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "message 1"]).success();
work_dir
.run_jj(["describe", "-m", "message 2", "--at-op", "@-"])
.success();
// "--at-op=@" disables op heads merging, and prints head operation ids.
let output = work_dir.run_jj(["op", "log", "--at-op=@"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: The "@" expression resolved to more than one operation
Hint: Try specifying one of the operations by ID: b2cffe4f3026, d8ced2ea64a8
[EOF]
[exit status: 1]
"#);
// "op log --at-op" should work without merging the head operations
let output = work_dir.run_jj(["op", "log", "--at-op=d8ced2ea64a8"]);
insta::assert_snapshot!(output, @r"
@ d8ced2ea64a8 test-username@host.example.com 2001-02-03 04:05:09.000 +07:00 - 2001-02-03 04:05:09.000 +07:00
โ describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ args: jj describe -m 'message 2' --at-op @-
โ 8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
โ 000000000000 root()
[EOF]
");
// We should be informed about the concurrent modification
let output = get_log_output(&work_dir);
insta::assert_snapshot!(output, @r"
@ message 1
โ โ message 2
โโโฏ
โ
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
}
#[test]
fn test_concurrent_operations_auto_rebase() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "contents");
work_dir.run_jj(["describe", "-m", "initial"]).success();
work_dir.run_jj(["describe", "-m", "rewritten"]).success();
work_dir
.run_jj(["new", "--at-op=@-", "-m", "new child"])
.success();
// We should be informed about the concurrent modification
let output = get_log_output(&work_dir);
insta::assert_snapshot!(output, @r"
โ new child
@ rewritten
โ
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
Rebased 1 descendant commits onto commits rewritten by other operation
[EOF]
");
}
#[test]
fn test_concurrent_operations_wc_modified() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "contents\n");
work_dir.run_jj(["describe", "-m", "initial"]).success();
work_dir.run_jj(["new", "-m", "new child1"]).success();
work_dir
.run_jj(["new", "--at-op=@-", "-m", "new child2"])
.success();
work_dir.write_file("file", "modified\n");
// We should be informed about the concurrent modification
let output = get_log_output(&work_dir);
insta::assert_snapshot!(output, @r"
@ new child1
โ โ new child2
โโโฏ
โ initial
โ
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
let output = work_dir.run_jj(["diff", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file b/file
index 12f00e90b6..2e0996000b 100644
--- a/file
+++ b/file
@@ -1,1 +1,1 @@
-contents
+modified
[EOF]
");
// The working copy should be committed after merging the operations
let output = work_dir.run_jj(["op", "log", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
@ snapshot working copy
โ reconcile divergent operations
โโโฎ
โ โ new empty commit
โ โ new empty commit
โโโฏ
โ describe commit 9a462e35578a347e6a3951bf7a58ad7146959a8b
โ snapshot working copy
โ add workspace 'default'
โ
[EOF]
");
}
#[test]
fn test_concurrent_snapshot_wc_reloadable() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let op_heads_dir = work_dir
.root()
.join(".jj")
.join("repo")
.join("op_heads")
.join("heads");
work_dir.write_file("base", "");
work_dir.run_jj(["commit", "-m", "initial"]).success();
// Create new commit and checkout it.
work_dir.write_file("child1", "");
work_dir.run_jj(["commit", "-m", "new child1"]).success();
let template = r#"id.short() ++ "\n" ++ description ++ "\n" ++ tags"#;
let output = work_dir.run_jj(["op", "log", "-T", template]);
insta::assert_snapshot!(output, @r"
@ a631dcf37fea
โ commit c91a0909a9d3f3d8392ba9fab88f4b40fc0810ee
โ args: jj commit -m 'new child1'
โ 2b8e6f8683dc
โ snapshot working copy
โ args: jj commit -m 'new child1'
โ 2e1c4ffb74ca
โ commit 9af4c151edead0304de97ce3a0b414552921a425
โ args: jj commit -m initial
โ cfe73d1664ae
โ snapshot working copy
โ args: jj commit -m initial
โ 8f47435a3990
โ add workspace 'default'
โ 000000000000
[EOF]
");
let template = r#"id ++ "\n""#;
let output = work_dir.run_jj(["op", "log", "--no-graph", "-T", template]);
let [op_id_after_snapshot, _, op_id_before_snapshot] =
output.stdout.raw().lines().next_array().unwrap();
insta::assert_snapshot!(op_id_after_snapshot[..12], @"a631dcf37fea");
insta::assert_snapshot!(op_id_before_snapshot[..12], @"2e1c4ffb74ca");
// Simulate a concurrent operation that began from the "initial" operation
// (before the "child1" snapshot) but finished after the "child1"
// snapshot and commit.
std::fs::rename(
op_heads_dir.join(op_id_after_snapshot),
op_heads_dir.join(op_id_before_snapshot),
)
.unwrap();
work_dir.write_file("child2", "");
let output = work_dir.run_jj(["describe", "-m", "new child2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 493da83e new child2
Parent commit (@-) : rlvkpnrz 15bd889d new child1
[EOF]
");
// Since the repo can be reloaded before snapshotting, "child2" should be
// a child of "child1", not of "initial".
let output = work_dir.run_jj(["log", "-T", "description", "-s"]);
insta::assert_snapshot!(output, @r"
@ new child2
โ A child2
โ new child1
โ A child1
โ initial
โ A base
โ
[EOF]
");
}
#[test]
fn test_git_head_race_condition() {
// Test for race condition where concurrent jj processes create divergent
// operations when importing/exporting Git HEAD. This test spawns two
// processes in parallel: one running `jj debug snapshot` repeatedly
// (which imports Git HEAD) and another running `jj next/prev` repeatedly
// (which exports Git HEAD). Without the fix, this would create divergent
// operations.
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
// Create a large initial working copy to make snapshotting slower
for j in 0..200 {
let filename = format!("file_{j}");
let content = format!("content for file {j}\n").repeat(100);
work_dir.write_file(&filename, &content);
}
work_dir.run_jj(["commit", "-m", "initial"]).success();
// Remember the initial commit for later verification
let initial_commit = work_dir
.run_jj(["log", "--no-graph", "-T=commit_id", "-r=@-"])
.success()
.stdout
.into_raw();
let initial_commit = initial_commit.trim().to_owned();
// Create additional commits to iterate through with jj next/prev
for i in 0..10 {
for j in 0..50 {
let filename = format!("file_{i}_{j}");
let content = format!("content for commit {i} file {j}\n").repeat(100);
work_dir.write_file(&filename, &content);
}
work_dir
.run_jj(["commit", "-m", &format!("commit {i}")])
.success();
}
// Extract environment from TestEnvironment to use in spawned processes
let base_cmd = test_env.new_jj_cmd();
let jj_bin = base_cmd.get_program().to_owned();
let base_env: Vec<_> = base_cmd
.get_envs()
.filter_map(|(k, v)| v.map(|v| (k.to_owned(), v.to_owned())))
// Filter out timestamp and randomness seed so each command gets different values
.filter(|(k, _)| k != "JJ_TIMESTAMP" && k != "JJ_OP_TIMESTAMP" && k != "JJ_RANDOMNESS_SEED")
.collect();
let repo_path = work_dir.root();
let duration = std::time::Duration::from_secs(5);
let start = std::time::Instant::now();
std::thread::scope(|s| {
s.spawn(|| {
while start.elapsed() < duration {
// Snapshot repeatedly without delay
let mut cmd = std::process::Command::new(&jj_bin);
cmd.current_dir(repo_path);
cmd.args(["debug", "snapshot"]);
for (key, value) in &base_env {
cmd.env(key, value);
}
let output = cmd.output().expect("Failed to spawn jj");
assert!(output.status.success(), "jj debug snapshot failed");
}
});
s.spawn(|| {
let mut count = 0;
while start.elapsed() < duration {
// Go through commit history back and forth
let direction = if count % 20 < 10 { "prev" } else { "next" };
let mut cmd = std::process::Command::new(&jj_bin);
cmd.current_dir(repo_path);
cmd.arg(direction);
for (key, value) in &base_env {
cmd.env(key, value);
}
let output = cmd.output().expect("Failed to spawn jj");
assert!(output.status.success(), "jj {direction} failed");
count += 1;
}
});
});
const IMPORT_GIT_HEAD: &str = "import git head";
// Check for concurrent operations
let output = work_dir.run_jj(["op", "log", "-T", "description", "--ignore-working-copy"]);
let concurrent_count = output
.stdout
.raw()
.lines()
.filter(|line| line.contains(IMPORT_GIT_HEAD))
.count();
if concurrent_count > 0 {
eprintln!("Found {concurrent_count} concurrent operations:");
eprintln!("{}", output.stdout.raw());
panic!("Race condition detected: {concurrent_count} concurrent operations found");
}
// 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)
work_dir.run_jj(["new"]).success();
// Use git to checkout the initial commit, then trigger import
std::process::Command::new("git")
.current_dir(work_dir.root())
.args(["checkout", "-q", &initial_commit])
.status()
.unwrap();
let last_op = work_dir
.run_jj(["op", "log", "-T", "description", "--limit=1"])
.success()
.stdout
.into_raw();
assert!(
last_op.contains(IMPORT_GIT_HEAD),
"Expected last operation to contain '{IMPORT_GIT_HEAD}', got: {last_op:?}"
);
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
work_dir.run_jj(["log", "-T", "description"])
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_identical_commits.rs | cli/tests/test_identical_commits.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
fn create_test_environment() -> TestEnvironment {
let mut test_env = TestEnvironment::default();
test_env.add_env_var("JJ_RANDOMNESS_SEED", "0");
test_env.add_env_var("JJ_TIMESTAMP", "2001-01-01T00:00:00+00:00");
test_env.add_config("experimental.record-predecessors-in-commit = false");
test_env
}
#[test]
fn test_identical_commits() {
let test_env = create_test_environment();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "root()", "-m=test"]).success();
// TODO: Should not fail
insta::assert_snapshot!(work_dir.run_jj(["new", "root()", "-m=test"]), @r"
------- stderr -------
Internal error: Unexpected error from backend
Caused by: Newly-created commit e94ed463cbb0776612e308eba2ecaae74a7f8a73 already exists
[EOF]
[exit status: 255]
");
// There should be a single "test" commit
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e94ed463cbb0 test
โ 000000000000
[EOF]
");
}
/// Create "test1" commit, then rewrite it in the same way "concurrently" (by
/// starting at the same operation)
#[test]
fn test_identical_commits_concurrently() {
let test_env = create_test_environment();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "root()", "-m=test1"]).success();
work_dir.run_jj(["describe", "-m=test2"]).success();
work_dir
.run_jj(["describe", "-m=test2", "--at-op=@-"])
.success();
// There should be a single "test2" commit
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c5abd2256ac0 test2
โ 000000000000
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
}
/// Create commit "test1", then rewrite it to "test2", then rewrite it back to
/// "test1"
#[test]
fn test_identical_commits_by_cycling_rewrite() {
let test_env = create_test_environment();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "root()", "-m=test1"]).success();
work_dir.run_jj(["describe", "-m=test2"]).success();
// TODO: Should not fail
insta::assert_snapshot!(work_dir.run_jj(["describe", "-m=test1"]), @r"
------- stderr -------
Internal error: Unexpected error from backend
Caused by: Newly-created commit 053222c21fa06b9492e22346f8f70e732231ad4f already exists
[EOF]
[exit status: 255]
");
insta::assert_snapshot!(work_dir.run_jj(["evolog"]), @r"
@ oxmtprsl test.user@example.com 2001-01-01 11:00:00 c5abd225
โ (empty) test2
โ -- operation f184243937e9 describe commit 053222c21fa06b9492e22346f8f70e732231ad4f
โ oxmtprsl/1 test.user@example.com 2001-01-01 11:00:00 053222c2 (hidden)
(empty) test1
-- operation 509c18587028 new empty commit
[EOF]
");
// TODO: Test `jj op diff --from @--`
}
/// Create commits "test1" and "test2" and rewrite "test1". Then rewrite "test2"
/// to become identical to the rewritten "test1".
#[test]
fn test_identical_commits_by_convergent_rewrite() {
let test_env = create_test_environment();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "root()", "-m=test1"]).success();
work_dir.run_jj(["new", "root()", "-m=test2"]).success();
work_dir
.run_jj(["describe", "-m=test3", "subject(test1)"])
.success();
// TODO: Should not fail
insta::assert_snapshot!(work_dir.run_jj(["describe", "-m=test3", "subject(test2)"]), @r"
------- stderr -------
Internal error: Unexpected error from backend
Caused by: Newly-created commit 460733f1f6f9283d5a810b231dd3f846fd3a6f04 already exists
[EOF]
[exit status: 255]
");
// TODO: The "test3" commit should have either "test1" or "test2" as predecessor
// (or both?)
insta::assert_snapshot!(work_dir.run_jj(["evolog"]), @r"
@ oxmtprsl/1 test.user@example.com 2001-01-01 11:00:00 c5abd225 (divergent)
(empty) test2
-- operation a1561db9359b new empty commit
[EOF]
");
}
/// Create commits "test1" and "test2" and then rewrite both of them to be
/// identical in a single operation
#[test]
fn test_identical_commits_by_convergent_rewrite_one_operation() {
let test_env = create_test_environment();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "root()", "-m=test1"]).success();
work_dir.run_jj(["new", "root()", "-m=test2"]).success();
// TODO: Should not fail
insta::assert_snapshot!(work_dir.run_jj(["describe", "-m=test3", "root()+"]), @r"
------- stderr -------
Internal error: Unexpected error from backend
Caused by: Newly-created commit 460733f1f6f9283d5a810b231dd3f846fd3a6f04 already exists
[EOF]
[exit status: 255]
");
// TODO: There should be a single "test3" commit
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c5abd2256ac0 test2
โ โ 053222c21fa0 test1
โโโฏ
โ 000000000000
[EOF]
");
// TODO: The "test3" commit should have either "test1" or "test2" as predecessor
// (or both?)
insta::assert_snapshot!(work_dir.run_jj(["evolog"]), @r"
@ oxmtprsl/0 test.user@example.com 2001-01-01 11:00:00 c5abd225 (divergent)
(empty) test2
-- operation a1561db9359b new empty commit
[EOF]
");
}
/// Create two stacked commits. Then reorder them so they become rewrites of
/// each other.
#[test]
fn test_identical_commits_swap_by_reordering() {
let test_env = create_test_environment();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "root()", "-m=test"]).success();
work_dir.run_jj(["new", "-m=test"]).success();
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 5bae90c9b34d test
โ e94ed463cbb0 test
โ 000000000000
[EOF]
");
// TODO: Should not fail
insta::assert_snapshot!(work_dir.run_jj(["rebase", "-r=@", "-B=@-"]), @r"
------- stderr -------
Internal error: Unexpected error from backend
Caused by: Newly-created commit e94ed463cbb0776612e308eba2ecaae74a7f8a73 already exists
[EOF]
[exit status: 255]
");
// There same two commits should still be visible
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 5bae90c9b34d test
โ e94ed463cbb0 test
โ 000000000000
[EOF]
");
// TODO: Each commit should be a predecessor of the other
insta::assert_snapshot!(work_dir.run_jj(["evolog", "-r=@"]), @r"
@ oxmtprsl/0 test.user@example.com 2001-01-01 11:00:00 5bae90c9 (divergent)
(empty) test
-- operation 380fbe20623e new empty commit
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["evolog", "-r=@-"]), @r"
โ oxmtprsl/1 test.user@example.com 2001-01-01 11:00:00 e94ed463 (divergent)
(empty) test
-- operation 40e37b931010 new empty commit
[EOF]
");
// TODO: Test that `jj op show` displays something reasonable
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"commit_id.short() ++ " " ++ description"#;
work_dir.run_jj(["log", "-T", template])
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_log_command.rs | cli/tests/test_log_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::TestEnvironment;
use crate::common::to_toml_value;
#[test]
fn test_log_with_empty_revision() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["log", "-r="]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: a value is required for '--revisions <REVSETS>' but none was supplied
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_log_with_no_template() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["log", "-T"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: a value is required for '--template <TEMPLATE>' but none was supplied
For more information, try '--help'.
Hint: The following template aliases are defined:
- builtin_config_list
- builtin_config_list_detailed
- builtin_draft_commit_description
- builtin_evolog_compact
- builtin_log_comfortable
- builtin_log_compact
- builtin_log_compact_full_description
- builtin_log_detailed
- builtin_log_node
- builtin_log_node_ascii
- builtin_log_oneline
- builtin_log_redacted
- builtin_op_log_comfortable
- builtin_op_log_compact
- builtin_op_log_node
- builtin_op_log_node_ascii
- builtin_op_log_oneline
- builtin_op_log_redacted
- commit_summary_separator
- default_commit_description
- description_placeholder
- email_placeholder
- empty_commit_marker
- git_format_patch_email_headers
- name_placeholder
[EOF]
[exit status: 2]
");
}
#[test]
fn test_log_with_diff_stats() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\nfoo\n");
work_dir.write_file("file3", "foo\n");
work_dir.write_file("file4", "foo\n");
work_dir.write_file("file5", "foobar\nbaz\n");
work_dir
.run_jj(["describe", "-m", "initial commit"])
.success();
work_dir.run_jj(["new", "-m", "multiple changes"]).success();
work_dir.write_file("file1", "foo\nbar\n");
work_dir.write_file("file2", "bar\n");
work_dir.write_file("file3", "baz\n");
work_dir.remove_file("file4");
work_dir.remove_file("file5");
work_dir.write_file("file6", "foobar\nbaz\n");
let template = r#"
self.diff().files().map(
|f| f.status_char() ++ " " ++ f.status() ++ " " ++ f.source().path() ++ " " ++ f.target().path()
).join("\n")
++ "\n" ++
self.diff().stat().files().map(
|f| f.status_char() ++ " " ++ f.status() ++ " " ++ f.lines_added() ++ " " ++ f.lines_removed() ++ " " ++ f.path()
).join("\n")
"#;
let output = work_dir.run_jj(["log", "-T", template]);
insta::assert_snapshot!(output, @r"
@ M modified file1 file1
โ M modified file2 file2
โ M modified file3 file3
โ D removed file4 file4
โ R renamed file5 file6
โ M modified 1 0 file1
โ M modified 0 1 file2
โ M modified 1 1 file3
โ D removed 0 1 file4
โ R renamed 0 0 file6
โ A added file1 file1
โ A added file2 file2
โ A added file3 file3
โ A added file4 file4
โ A added file5 file5
โ A added 1 0 file1
โ A added 2 0 file2
โ A added 1 0 file3
โ A added 1 0 file4
โ A added 2 0 file5
โ
[EOF]
");
}
#[test]
fn test_log_with_or_without_diff() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.run_jj(["describe", "-m", "add a file"]).success();
work_dir.run_jj(["new", "-m", "a new commit"]).success();
work_dir.write_file("file1", "foo\nbar\n");
let output = work_dir.run_jj(["log", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ a new commit
โ add a file
โ
[EOF]
");
let output = work_dir.run_jj(["log", "-T", "description", "-p"]);
insta::assert_snapshot!(output, @r"
@ a new commit
โ Modified regular file file1:
โ 1 1: foo
โ 2: bar
โ add a file
โ Added regular file file1:
โ 1: foo
โ
[EOF]
");
let output = work_dir.run_jj(["log", "-T", "description", "--no-graph"]);
insta::assert_snapshot!(output, @r"
a new commit
add a file
[EOF]
");
// `-G` is the short name of --no-graph
let output = work_dir.run_jj(["log", "-T", r#"commit_id.short() ++ "\n""#, "-G"]);
insta::assert_snapshot!(output, @r"
58c940c45833
007859d3ad71
000000000000
[EOF]
");
// `-p` for default diff output, `-s` for summary
let output = work_dir.run_jj(["log", "-T", "description", "-p", "-s"]);
insta::assert_snapshot!(output, @r"
@ a new commit
โ M file1
โ Modified regular file file1:
โ 1 1: foo
โ 2: bar
โ add a file
โ A file1
โ Added regular file file1:
โ 1: foo
โ
[EOF]
");
// `-s` for summary, `--git` for git diff (which implies `-p`)
let output = work_dir.run_jj(["log", "-T", "description", "-s", "--git"]);
insta::assert_snapshot!(output, @r"
@ a new commit
โ M file1
โ diff --git a/file1 b/file1
โ index 257cc5642c..3bd1f0e297 100644
โ --- a/file1
โ +++ b/file1
โ @@ -1,1 +1,2 @@
โ foo
โ +bar
โ add a file
โ A file1
โ diff --git a/file1 b/file1
โ new file mode 100644
โ index 0000000000..257cc5642c
โ --- /dev/null
โ +++ b/file1
โ @@ -0,0 +1,1 @@
โ +foo
โ
[EOF]
");
// `-p` for default diff output, `--stat` for diff-stat
let output = work_dir.run_jj(["log", "-T", "description", "-p", "--stat"]);
insta::assert_snapshot!(output, @r"
@ a new commit
โ file1 | 1 +
โ 1 file changed, 1 insertion(+), 0 deletions(-)
โ Modified regular file file1:
โ 1 1: foo
โ 2: bar
โ add a file
โ file1 | 1 +
โ 1 file changed, 1 insertion(+), 0 deletions(-)
โ Added regular file file1:
โ 1: foo
โ 0 files changed, 0 insertions(+), 0 deletions(-)
[EOF]
");
// `--stat` is short format, which should be printed first
let output = work_dir.run_jj(["log", "-T", "description", "--git", "--stat"]);
insta::assert_snapshot!(output, @"
@ a new commit
โ file1 | 1 +
โ 1 file changed, 1 insertion(+), 0 deletions(-)
โ diff --git a/file1 b/file1
โ index 257cc5642c..3bd1f0e297 100644
โ --- a/file1
โ +++ b/file1
โ @@ -1,1 +1,2 @@
โ foo
โ +bar
โ add a file
โ file1 | 1 +
โ 1 file changed, 1 insertion(+), 0 deletions(-)
โ diff --git a/file1 b/file1
โ new file mode 100644
โ index 0000000000..257cc5642c
โ --- /dev/null
โ +++ b/file1
โ @@ -0,0 +1,1 @@
โ +foo
โ 0 files changed, 0 insertions(+), 0 deletions(-)
[EOF]
");
// `-p` enables default "summary" output, so `-s` is noop
let output = work_dir.run_jj([
"log",
"-T",
"description",
"-p",
"-s",
"--config=ui.diff-formatter=:summary",
]);
insta::assert_snapshot!(output, @r"
@ a new commit
โ M file1
โ add a file
โ A file1
โ
[EOF]
");
// `-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, @r"
@ a new commit
โ Modified regular file file1:
โ 1 1: foo
โ 2: bar
โ add a file
โ Added regular file file1:
โ 1: foo
โ
[EOF]
");
// `--git` enables git diff, so `-p` is noop
let output = work_dir.run_jj(["log", "-T", "description", "--no-graph", "-p", "--git"]);
insta::assert_snapshot!(output, @r"
a new commit
diff --git a/file1 b/file1
index 257cc5642c..3bd1f0e297 100644
--- a/file1
+++ b/file1
@@ -1,1 +1,2 @@
foo
+bar
add a file
diff --git a/file1 b/file1
new file mode 100644
index 0000000000..257cc5642c
--- /dev/null
+++ b/file1
@@ -0,0 +1,1 @@
+foo
[EOF]
");
// Cannot use both `--git` and `--color-words`
let output = work_dir.run_jj([
"log",
"-T",
"description",
"--no-graph",
"-p",
"--git",
"--color-words",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--git' cannot be used with '--color-words'
Usage: jj log --template <TEMPLATE> --no-graph --patch --git [FILESETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// `-s` with or without graph
let output = work_dir.run_jj(["log", "-T", "description", "-s"]);
insta::assert_snapshot!(output, @r"
@ a new commit
โ M file1
โ add a file
โ A file1
โ
[EOF]
");
let output = work_dir.run_jj(["log", "-T", "description", "--no-graph", "-s"]);
insta::assert_snapshot!(output, @r"
a new commit
M file1
add a file
A file1
[EOF]
");
// `--git` implies `-p`, with or without graph
let output = work_dir.run_jj(["log", "-T", "description", "-r", "@", "--git"]);
insta::assert_snapshot!(output, @r"
@ a new commit
โ diff --git a/file1 b/file1
~ index 257cc5642c..3bd1f0e297 100644
--- a/file1
+++ b/file1
@@ -1,1 +1,2 @@
foo
+bar
[EOF]
");
let output = work_dir.run_jj(["log", "-T", "description", "-r", "@", "--no-graph", "--git"]);
insta::assert_snapshot!(output, @r"
a new commit
diff --git a/file1 b/file1
index 257cc5642c..3bd1f0e297 100644
--- a/file1
+++ b/file1
@@ -1,1 +1,2 @@
foo
+bar
[EOF]
");
// `--color-words` implies `-p`, with or without graph
let output = work_dir.run_jj(["log", "-T", "description", "-r", "@", "--color-words"]);
insta::assert_snapshot!(output, @r"
@ a new commit
โ Modified regular file file1:
~ 1 1: foo
2: bar
[EOF]
");
let output = work_dir.run_jj([
"log",
"-T",
"description",
"-r",
"@",
"--no-graph",
"--color-words",
]);
insta::assert_snapshot!(output, @r"
a new commit
Modified regular file file1:
1 1: foo
2: bar
[EOF]
");
}
#[test]
fn test_log_null_terminate_multiline_descriptions() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["commit", "-m", "commit 1 line 1", "-m", "commit 1 line 2"])
.success();
work_dir
.run_jj(["commit", "-m", "commit 2 line 1", "-m", "commit 2 line 2"])
.success();
work_dir
.run_jj(["describe", "-m", "commit 3 line 1", "-m", "commit 3 line 2"])
.success();
let output = work_dir
.run_jj([
"log",
"-r",
"~root()",
"-T",
r#"description ++ "\0""#,
"--no-graph",
])
.success();
insta::assert_debug_snapshot!(
output.stdout.normalized(),
@r#""commit 3 line 1\n\ncommit 3 line 2\n\0commit 2 line 1\n\ncommit 2 line 2\n\0commit 1 line 1\n\ncommit 1 line 2\n\0""#
);
}
#[test]
fn test_log_shortest_accessors() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let render = |rev, template| work_dir.run_jj(["log", "--no-graph", "-r", rev, "-T", template]);
test_env.add_config(
r#"
[template-aliases]
'format_id(id)' = 'id.shortest(12).prefix() ++ "[" ++ id.shortest(12).rest() ++ "]"'
"#,
);
work_dir.write_file("file", "original file\n");
work_dir.run_jj(["describe", "-m", "initial"]).success();
work_dir
.run_jj(["bookmark", "c", "-r@", "original"])
.success();
insta::assert_snapshot!(
render("original", r#"format_id(change_id) ++ " " ++ format_id(commit_id)"#),
@"q[pvuntsmwlqt] 8[216f646c36d][EOF]");
// Create a chain of 10 commits
for i in 1..10 {
work_dir
.run_jj(["new", "-m", &format!("commit{i}")])
.success();
work_dir.write_file("file", format!("file {i}\n"));
}
// Create 2^3 duplicates of the chain
for _ in 0..3 {
work_dir.run_jj(["duplicate", "subject(commit*)"]).success();
}
insta::assert_snapshot!(
render("original", r#"format_id(change_id) ++ " " ++ format_id(commit_id)"#),
@"qpv[untsmwlqt] 82[16f646c36d][EOF]");
insta::assert_snapshot!(
render("::@", r#"change_id.shortest() ++ " " ++ commit_id.shortest() ++ "\n""#), @r"
wq c2
km 74
kp 97
zn 78
yo 40
vr bc9
yq 28
ro af
mz 04
qpv 82
zzz 00
[EOF]
");
insta::assert_snapshot!(
render("::@", r#"format_id(change_id) ++ " " ++ format_id(commit_id) ++ "\n""#), @r"
wq[nwkozpkust] c2[b4c0bb3362]
km[kuslswpqwq] 74[fcd50c0643]
kp[qxywonksrl] 97[dcaada9b8d]
zn[kkpsqqskkl] 78[c03ab2235b]
yo[stqsxwqrlt] 40[1119280761]
vr[uxwmqvtpmx] bc9[e8942b459]
yq[osqzytrlsw] 28[edbc9658ef]
ro[yxmykxtrkr] af[3e6a27a1d0]
mz[vwutvlkqwt] 04[6c6a1df762]
qpv[untsmwlqt] 82[16f646c36d]
zzz[zzzzzzzzz] 00[0000000000]
[EOF]
");
// Can get shorter prefixes in configured revset
test_env.add_config(r#"revsets.short-prefixes = "(@----)::""#);
insta::assert_snapshot!(
render("::@", r#"format_id(change_id) ++ " " ++ format_id(commit_id) ++ "\n""#), @r"
w[qnwkozpkust] c[2b4c0bb3362]
km[kuslswpqwq] 74[fcd50c0643]
kp[qxywonksrl] 9[7dcaada9b8d]
z[nkkpsqqskkl] 78[c03ab2235b]
y[ostqsxwqrlt] 4[01119280761]
vr[uxwmqvtpmx] bc9[e8942b459]
yq[osqzytrlsw] 28[edbc9658ef]
ro[yxmykxtrkr] af[3e6a27a1d0]
mz[vwutvlkqwt] 04[6c6a1df762]
qpv[untsmwlqt] 82[16f646c36d]
zzz[zzzzzzzzz] 00[0000000000]
[EOF]
");
// Can disable short prefixes by setting to empty string
test_env.add_config(r#"revsets.short-prefixes = """#);
insta::assert_snapshot!(
render("::@", r#"format_id(change_id) ++ " " ++ format_id(commit_id) ++ "\n""#), @r"
wq[nwkozpkust] c2[b4c0bb3362]
km[kuslswpqwq] 74[fcd50c0643]
kp[qxywonksrl] 97[dcaada9b8d]
zn[kkpsqqskkl] 78[c03ab2235b]
yo[stqsxwqrlt] 401[119280761]
vr[uxwmqvtpmx] bc9[e8942b459]
yq[osqzytrlsw] 28[edbc9658ef]
ro[yxmykxtrkr] af[3e6a27a1d0]
mz[vwutvlkqwt] 04[6c6a1df762]
qpv[untsmwlqt] 82[16f646c36d]
zzz[zzzzzzzzz] 00[0000000000]
[EOF]
");
// The shortest prefix "zzz" is shadowed by bookmark
work_dir
.run_jj(["bookmark", "set", "-r@", "z", "zz", "zzz"])
.success();
insta::assert_snapshot!(
render("root()", r#"format_id(change_id) ++ " " ++ format_id(commit_id) ++ "\n""#), @r"
zzzz[zzzzzzzz] 00[0000000000]
[EOF]
");
}
#[test]
fn test_log_bad_short_prefixes() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Suppress warning in the commit summary template
test_env.add_config("template-aliases.'format_short_id(id)' = 'id.short(8)'");
// Error on bad config of short prefixes
test_env.add_config(r#"revsets.short-prefixes = "!nval!d""#);
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Invalid `revsets.short-prefixes`
Caused by: --> 1:1
|
1 | !nval!d
| ^---
|
= expected <strict_identifier> or <expression>
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
// Warn on resolution of short prefixes
test_env.add_config("revsets.short-prefixes = 'missing'");
let output = work_dir.run_jj(["log", "-Tcommit_id.shortest()"]);
insta::assert_snapshot!(output, @r"
@ e
โ 0
[EOF]
------- stderr -------
Warning: In template expression
--> 1:11
|
1 | commit_id.shortest()
| ^------^
|
= Failed to load short-prefixes index
Failed to resolve short-prefixes disambiguation revset
Revision `missing` doesn't exist
[EOF]
");
// Error on resolution of short prefixes
test_env.add_config("revsets.short-prefixes = 'missing'");
let output = work_dir.run_jj(["log", "-r0"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to resolve short-prefixes disambiguation revset
Caused by: Revision `missing` doesn't exist
[EOF]
[exit status: 1]
");
}
#[test]
fn test_log_prefix_highlight_styled() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
fn prefix_format(len: Option<usize>) -> String {
format!(
r###"
separate(" ",
"Change",
change_id.shortest({0}),
description.first_line(),
commit_id.shortest({0}),
bookmarks,
)
"###,
len.map(|l| l.to_string()).unwrap_or_default()
)
}
work_dir.write_file("file", "original file\n");
work_dir.run_jj(["describe", "-m", "initial"]).success();
work_dir
.run_jj(["bookmark", "c", "-r@", "original"])
.success();
insta::assert_snapshot!(
work_dir.run_jj(["log", "-r", "original", "-T", &prefix_format(Some(12))]), @r"
@ Change qpvuntsmwlqt initial 8216f646c36d original
โ
~
[EOF]
");
// Create a chain of 10 commits
for i in 1..10 {
work_dir
.run_jj(["new", "-m", &format!("commit{i}")])
.success();
work_dir.write_file("file", format!("file {i}\n"));
}
// Create 2^3 duplicates of the chain
for _ in 0..3 {
work_dir.run_jj(["duplicate", "subject(commit*)"]).success();
}
insta::assert_snapshot!(
work_dir.run_jj(["log", "-r", "original", "-T", &prefix_format(Some(12))]), @r"
โ Change qpvuntsmwlqt initial 8216f646c36d original
โ
~
[EOF]
");
let output = work_dir.run_jj([
"--color=always",
"log",
"-r",
"@-----------..@",
"-T",
&prefix_format(Some(12)),
]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m Change [1m[38;5;5mwq[0m[38;5;8mnwkozpkust[39m commit9 [1m[38;5;4mc2[0m[38;5;8mb4c0bb3362[39m
โ Change [1m[38;5;5mkm[0m[38;5;8mkuslswpqwq[39m commit8 [1m[38;5;4m74[0m[38;5;8mfcd50c0643[39m
โ Change [1m[38;5;5mkp[0m[38;5;8mqxywonksrl[39m commit7 [1m[38;5;4m97[0m[38;5;8mdcaada9b8d[39m
โ Change [1m[38;5;5mzn[0m[38;5;8mkkpsqqskkl[39m commit6 [1m[38;5;4m78[0m[38;5;8mc03ab2235b[39m
โ Change [1m[38;5;5myo[0m[38;5;8mstqsxwqrlt[39m commit5 [1m[38;5;4m40[0m[38;5;8m1119280761[39m
โ Change [1m[38;5;5mvr[0m[38;5;8muxwmqvtpmx[39m commit4 [1m[38;5;4mbc9[0m[38;5;8me8942b459[39m
โ Change [1m[38;5;5myq[0m[38;5;8mosqzytrlsw[39m commit3 [1m[38;5;4m28[0m[38;5;8medbc9658ef[39m
โ Change [1m[38;5;5mro[0m[38;5;8myxmykxtrkr[39m commit2 [1m[38;5;4maf[0m[38;5;8m3e6a27a1d0[39m
โ Change [1m[38;5;5mmz[0m[38;5;8mvwutvlkqwt[39m commit1 [1m[38;5;4m04[0m[38;5;8m6c6a1df762[39m
โ Change [1m[38;5;5mqpv[0m[38;5;8muntsmwlqt[39m initial [1m[38;5;4m82[0m[38;5;8m16f646c36d[39m [38;5;5moriginal[39m
[1m[38;5;14mโ[0m Change [1m[38;5;5mzzz[0m[38;5;8mzzzzzzzzz[39m [1m[38;5;4m00[0m[38;5;8m0000000000[39m
[EOF]
");
let output = work_dir.run_jj([
"--color=always",
"log",
"-r",
"@-----------..@",
"-T",
&prefix_format(Some(3)),
]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m Change [1m[38;5;5mwq[0m[38;5;8mn[39m commit9 [1m[38;5;4mc2[0m[38;5;8mb[39m
โ Change [1m[38;5;5mkm[0m[38;5;8mk[39m commit8 [1m[38;5;4m74[0m[38;5;8mf[39m
โ Change [1m[38;5;5mkp[0m[38;5;8mq[39m commit7 [1m[38;5;4m97[0m[38;5;8md[39m
โ Change [1m[38;5;5mzn[0m[38;5;8mk[39m commit6 [1m[38;5;4m78[0m[38;5;8mc[39m
โ Change [1m[38;5;5myo[0m[38;5;8ms[39m commit5 [1m[38;5;4m40[0m[38;5;8m1[39m
โ Change [1m[38;5;5mvr[0m[38;5;8mu[39m commit4 [1m[38;5;4mbc9[0m
โ Change [1m[38;5;5myq[0m[38;5;8mo[39m commit3 [1m[38;5;4m28[0m[38;5;8me[39m
โ Change [1m[38;5;5mro[0m[38;5;8my[39m commit2 [1m[38;5;4maf[0m[38;5;8m3[39m
โ Change [1m[38;5;5mmz[0m[38;5;8mv[39m commit1 [1m[38;5;4m04[0m[38;5;8m6[39m
โ Change [1m[38;5;5mqpv[0m initial [1m[38;5;4m82[0m[38;5;8m1[39m [38;5;5moriginal[39m
[1m[38;5;14mโ[0m Change [1m[38;5;5mzzz[0m [1m[38;5;4m00[0m[38;5;8m0[39m
[EOF]
");
let output = work_dir.run_jj([
"--color=always",
"log",
"-r",
"@-----------..@",
"-T",
&prefix_format(None),
]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m Change [1m[38;5;5mwq[0m commit9 [1m[38;5;4mc2[0m
โ Change [1m[38;5;5mkm[0m commit8 [1m[38;5;4m74[0m
โ Change [1m[38;5;5mkp[0m commit7 [1m[38;5;4m97[0m
โ Change [1m[38;5;5mzn[0m commit6 [1m[38;5;4m78[0m
โ Change [1m[38;5;5myo[0m commit5 [1m[38;5;4m40[0m
โ Change [1m[38;5;5mvr[0m commit4 [1m[38;5;4mbc9[0m
โ Change [1m[38;5;5myq[0m commit3 [1m[38;5;4m28[0m
โ Change [1m[38;5;5mro[0m commit2 [1m[38;5;4maf[0m
โ Change [1m[38;5;5mmz[0m commit1 [1m[38;5;4m04[0m
โ Change [1m[38;5;5mqpv[0m initial [1m[38;5;4m82[0m [38;5;5moriginal[39m
[1m[38;5;14mโ[0m Change [1m[38;5;5mzzz[0m [1m[38;5;4m00[0m
[EOF]
");
}
#[test]
fn test_log_prefix_highlight_counts_hidden_commits() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
test_env.add_config(
r#"
[revsets]
short-prefixes = "" # Disable short prefixes
[template-aliases]
'format_id(id)' = 'id.shortest(12).prefix() ++ "[" ++ id.shortest(12).rest() ++ "]"'
"#,
);
let prefix_format = r#"
separate(" ",
"Change",
format_id(change_id),
description.first_line(),
format_id(commit_id),
bookmarks,
)
"#;
work_dir.write_file("file", "original file\n");
work_dir.run_jj(["describe", "-m", "initial"]).success();
work_dir
.run_jj(["bookmark", "c", "-r@", "original"])
.success();
insta::assert_snapshot!(work_dir.run_jj(["log", "-r", "all()", "-T", prefix_format]), @r"
@ Change q[pvuntsmwlqt] initial 8[216f646c36d] original
โ Change z[zzzzzzzzzzz] 00[0000000000]
[EOF]
");
// Create 2^7 hidden commits
work_dir.run_jj(["new", "root()", "-m", "extra"]).success();
for _ in 0..7 {
work_dir.run_jj(["duplicate", "subject(extra)"]).success();
}
work_dir.run_jj(["abandon", "subject(extra)"]).success();
// The unique prefixes became longer.
insta::assert_snapshot!(work_dir.run_jj(["log", "-T", prefix_format]), @r"
@ Change wq[nwkozpkust] 88[e8407a4f0a]
โ โ Change qpv[untsmwlqt] initial 82[16f646c36d] original
โโโฏ
โ Change zzz[zzzzzzzzz] 00[0000000000]
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["log", "-r", "8", "-T", prefix_format]), @r"
------- stderr -------
Error: Commit ID prefix `8` is ambiguous
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(work_dir.run_jj(["log", "-r", "88", "-T", prefix_format]), @r"
@ Change wq[nwkozpkust] 88[e8407a4f0a]
โ
~
[EOF]
");
}
#[test]
fn test_log_author_format() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
insta::assert_snapshot!(work_dir.run_jj(["log", "--revisions=@"]), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:07 e8849ae1
โ (empty) (no description set)
~
[EOF]
");
let decl = "template-aliases.'format_short_signature(signature)'";
insta::assert_snapshot!(work_dir.run_jj([
"--config",
&format!("{decl}='signature.email().local()'"),
"log",
"--revisions=@",
]), @r"
@ qpvuntsm test.user 2001-02-03 08:05:07 e8849ae1
โ (empty) (no description set)
~
[EOF]
");
}
#[test]
fn test_log_divergence() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let template = r#"description.first_line() ++ if(divergent, " !divergence!")"#;
work_dir.write_file("file", "foo\n");
work_dir
.run_jj(["describe", "-m", "description 1"])
.success();
// No divergence
let output = work_dir.run_jj(["log", "-T", template]);
insta::assert_snapshot!(output, @r"
@ description 1
โ
[EOF]
");
// Create divergence
work_dir
.run_jj(["describe", "-m", "description 2", "--at-operation", "@-"])
.success();
let output = work_dir.run_jj(["log", "-T", template]);
insta::assert_snapshot!(output, @r"
@ description 1 !divergence!
โ โ description 2 !divergence!
โโโฏ
โ
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
}
#[test]
fn test_log_reversed() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "first"]).success();
work_dir.run_jj(["new", "-m", "second"]).success();
let output = work_dir.run_jj(["log", "-T", "description", "--reversed"]);
insta::assert_snapshot!(output, @r"
โ
โ first
@ second
[EOF]
");
let output = work_dir.run_jj(["log", "-T", "description", "--reversed", "--no-graph"]);
insta::assert_snapshot!(output, @r"
first
second
[EOF]
");
}
#[test]
fn test_log_filtered_by_path() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.run_jj(["describe", "-m", "first"]).success();
work_dir.run_jj(["new", "-m", "second"]).success();
work_dir.write_file("file1", "foo\nbar\n");
work_dir.write_file("file2", "baz\n");
// The output filtered to a non-existent file should display a warning.
let output = work_dir.run_jj(["log", "-r", "@-", "-T", "description", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
[EOF]
");
// The output filtered to a non-existent file should display a warning.
// The warning should be displayed at the beginning of the output.
let output = work_dir.run_jj(["log", "-T", "description", "nonexistent"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Warning: No matching entries for paths: nonexistent
Warning: The argument "nonexistent" is being interpreted as a fileset expression. To specify a revset, pass -r "nonexistent" instead.
[EOF]
"#);
let output = work_dir.run_jj(["log", "-T", "description", "file1"]);
insta::assert_snapshot!(output, @r"
@ second
โ first
โ
~
[EOF]
");
let output = work_dir.run_jj(["log", "-T", "description", "file2"]);
insta::assert_snapshot!(output, @r"
@ second
โ
~
[EOF]
");
let output = work_dir.run_jj(["log", "-T", "description", "-s", "file1"]);
insta::assert_snapshot!(output, @r"
@ second
โ M file1
โ first
โ A file1
~
[EOF]
");
let output = work_dir.run_jj(["log", "-T", "description", "-s", "file2", "--no-graph"]);
insta::assert_snapshot!(output, @r"
second
A file2
[EOF]
");
// empty revisions are filtered out by "all()" fileset.
let output = work_dir.run_jj(["log", "-Tdescription", "-s", "all()"]);
insta::assert_snapshot!(output, @r"
@ second
โ M file1
โ A file2
โ first
โ A file1
~
[EOF]
");
// "root:<path>" is resolved relative to the workspace root.
let output = test_env.run_jj_in(
".",
[
"log",
"-R",
work_dir.root().to_str().unwrap(),
"-Tdescription",
"-s",
"root:file1",
],
);
insta::assert_snapshot!(output.normalize_backslash(), @r"
@ second
โ M repo/file1
โ first
โ A repo/file1
~
[EOF]
");
// files() revset doesn't filter the diff.
let output = work_dir.run_jj([
"log",
"-T",
"description",
"-s",
"-rfiles(file2)",
"--no-graph",
]);
insta::assert_snapshot!(output, @r"
second
M file1
A file2
[EOF]
");
}
#[test]
fn test_log_limit() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "a"]).success();
work_dir.write_file("a", "");
work_dir.run_jj(["new", "-m", "b"]).success();
work_dir.write_file("b", "");
work_dir.run_jj(["new", "-m", "c", "subject(a)"]).success();
work_dir.write_file("c", "");
work_dir
.run_jj(["new", "-m", "d", "subject(c)", "subject(b)"])
.success();
let output = work_dir.run_jj(["log", "-T", "description", "--limit=3"]);
insta::assert_snapshot!(output, @r"
@ d
โโโฎ
โ โ b
โ โ c
โโโฏ
[EOF]
");
// Applied on sorted DAG
let output = work_dir.run_jj(["log", "-T", "description", "--limit=2"]);
insta::assert_snapshot!(output, @r"
@ d
โโโฎ
โ โ b
[EOF]
");
let output = work_dir.run_jj(["log", "-T", "description", "--limit=2", "--no-graph"]);
insta::assert_snapshot!(output, @r"
d
c
[EOF]
");
// Applied on reversed DAG: Because the node "a" is omitted, "b" and "c" are
// rendered as roots.
let output = work_dir.run_jj(["log", "-T", "description", "--limit=3", "--reversed"]);
insta::assert_snapshot!(output, @r"
โ c
โ โ b
โโโฏ
@ d
[EOF]
");
let output = work_dir.run_jj([
"log",
"-T",
"description",
"--limit=3",
"--reversed",
"--no-graph",
]);
insta::assert_snapshot!(output, @r"
b
c
d
[EOF]
");
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_status_command.rs | cli/tests/test_status_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::TestEnvironment;
use crate::common::create_commit_with_files;
#[test]
fn test_status_copies() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("copy-source", "copy1\ncopy2\ncopy3\n");
work_dir.write_file("rename-source", "rename");
work_dir.run_jj(["new"]).success();
work_dir.write_file("copy-source", "copy1\ncopy2\ncopy3\nsource\n");
work_dir.write_file("copy-target", "copy1\ncopy2\ncopy3\ntarget\n");
work_dir.remove_file("rename-source");
work_dir.write_file("rename-target", "rename");
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
M copy-source
C {copy-source => copy-target}
R {rename-source => rename-target}
Working copy (@) : rlvkpnrz c2fce842 (no description set)
Parent commit (@-): qpvuntsm ebf799bc (no description set)
[EOF]
");
}
#[test]
fn test_status_merge() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "base");
work_dir.run_jj(["new", "-m=left"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "left"])
.success();
work_dir.run_jj(["new", "@-", "-m=right"]).success();
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)
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : mzvwutvl f62dad77 (empty) (no description set)
Parent commit (@-): rlvkpnrz a007d87b left | (empty) left
Parent commit (@-): zsuskuln e6ad1952 right
[EOF]
");
}
// See https://github.com/jj-vcs/jj/issues/2051.
#[test]
fn test_status_ignored_gitignore() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let untracked_dir = work_dir.create_dir("untracked");
untracked_dir.write_file("inside_untracked", "test");
untracked_dir.write_file(".gitignore", "!inside_untracked\n");
work_dir.write_file(".gitignore", "untracked/\n!dummy\n");
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
A .gitignore
Working copy (@) : qpvuntsm 32bad97e (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_status_filtered() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file_1", "file_1");
work_dir.write_file("file_2", "file_2");
// The output filtered to file_1 should not list the addition of file_2.
let output = work_dir.run_jj(["status", "file_1"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
A file_1
Working copy (@) : qpvuntsm 2f169edb (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// The output filtered to a non-existent file should display a warning.
let output = work_dir.run_jj(["status", "nonexistent"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
Working copy (@) : qpvuntsm 2f169edb (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
------- stderr -------
Warning: No matching entries for paths: nonexistent
[EOF]
");
}
#[test]
fn test_status_conflicted_bookmarks() {
// create conflicted local bookmark
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["bookmark", "create", "local_bookmark"])
.success();
work_dir.run_jj(["describe", "-m=a"]).success();
work_dir
.run_jj(["describe", "-m=b", "--at-op=@-"])
.success();
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : qpvuntsm/1 99025a24 local_bookmark?? | (divergent) (empty) a
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
Warning: These bookmarks have conflicts:
local_bookmark
Hint: Use `jj bookmark list` to see details. Use `jj bookmark set <name> -r <rev>` to resolve.
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
// create remote
test_env
.run_jj_in(".", ["git", "init", "origin", "--colocate"])
.success();
let origin_dir = test_env.work_dir("origin");
let origin_git_repo_path = origin_dir.root().join(".git");
origin_dir
.run_jj(["bookmark", "create", "remote_bookmark"])
.success();
origin_dir.run_jj(["git", "export"]).success();
// fetch remote bookmark with empty changes
work_dir
.run_jj([
"git",
"remote",
"add",
"origin",
origin_git_repo_path.to_str().unwrap(),
])
.success();
work_dir.run_jj(["git", "fetch"]).success();
// update remote
origin_dir.write_file("file.txt", "");
origin_dir.run_jj(["git", "export"]).success();
// create conflicted remote bookmark
work_dir.run_jj(["git", "fetch", "--at-op", "@-"]).success();
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : qpvuntsm/1 99025a24 local_bookmark?? | (divergent) (empty) a
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
Warning: These bookmarks have conflicts:
local_bookmark
Hint: Use `jj bookmark list` to see details. Use `jj bookmark set <name> -r <rev>` to resolve.
Warning: These remote bookmarks have conflicts:
remote_bookmark@origin
Hint: Use `jj bookmark list` to see details. Use `jj git fetch` to resolve.
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
}
// See <https://github.com/jj-vcs/jj/issues/3108>
// See <https://github.com/jj-vcs/jj/issues/4147>
#[test]
fn test_status_display_relevant_working_commit_conflict_hints() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// PARENT: Write the initial file
work_dir.write_file("conflicted1.txt", "initial contents");
work_dir.write_file("conflicted2.txt", "initial contents");
work_dir
.run_jj(["describe", "--message", "Initial contents"])
.success();
// CHILD1: New commit on top of <PARENT>
work_dir
.run_jj(["new", "--message", "First part of conflicting change"])
.success();
work_dir.write_file("conflicted1.txt", "Child 1");
work_dir.write_file("conflicted2.txt", "Child 1");
// CHILD2: New commit also on top of <PARENT>
work_dir
.run_jj([
"new",
"--message",
"Second part of conflicting change",
"@-",
])
.success();
work_dir.write_file("conflicted1.txt", "Child 2");
work_dir.write_file("conflicted2.txt", "Child 2");
// CONFLICT: New commit that is conflicted by merging <CHILD1> and <CHILD2>
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.
work_dir.run_jj(["new", "--message", "boom-cont"]).success();
work_dir
.run_jj(["new", "--message", "boom-cont-2"])
.success();
let output = work_dir.run_jj(["log", "-r", "::"]);
insta::assert_snapshot!(output, @r"
@ yqosqzyt test.user@example.com 2001-02-03 08:05:13 d31638b7 (conflict)
โ (empty) boom-cont-2
ร royxmykx test.user@example.com 2001-02-03 08:05:12 20d4acb3 (conflict)
โ (empty) boom-cont
ร mzvwutvl test.user@example.com 2001-02-03 08:05:11 553ce839 (conflict)
โโโฎ (empty) boom
โ โ kkmpptxz test.user@example.com 2001-02-03 08:05:10 7bb1724e
โ โ First part of conflicting change
โ โ zsuskuln test.user@example.com 2001-02-03 08:05:11 263e2eb6
โโโฏ Second part of conflicting change
โ qpvuntsm test.user@example.com 2001-02-03 08:05:08 8b2bca65
โ Initial contents
โ zzzzzzzz root() 00000000
[EOF]
");
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : yqosqzyt d31638b7 (conflict) (empty) boom-cont-2
Parent commit (@-): royxmykx 20d4acb3 (conflict) (empty) boom-cont
Warning: There are unresolved conflicts at these paths:
conflicted1.txt 2-sided conflict
conflicted2.txt 2-sided conflict
Hint: To resolve the conflicts, start by creating a commit on top of
the first conflicted commit:
jj new mzvwutvl
Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved, you can inspect the result with `jj diff`.
Then run `jj squash` to move the resolution into the conflicted commit.
[EOF]
");
// Can filter by paths for conflicts.
let output = work_dir.run_jj(["status", "conflicted1.txt"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : yqosqzyt d31638b7 (conflict) (empty) boom-cont-2
Parent commit (@-): royxmykx 20d4acb3 (conflict) (empty) boom-cont
Warning: There are unresolved conflicts at these paths:
conflicted1.txt 2-sided conflict
Hint: To resolve the conflicts, start by creating a commit on top of
the first conflicted commit:
jj new mzvwutvl
Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved, you can inspect the result with `jj diff`.
Then run `jj squash` to move the resolution into the conflicted commit.
[EOF]
");
let output = work_dir.run_jj(["status", "--color=always"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : [1m[38;5;13my[38;5;8mqosqzyt[39m [38;5;12md[38;5;8m31638b7[39m [38;5;9m(conflict)[39m [38;5;10m(empty)[39m boom-cont-2[0m
Parent commit (@-): [1m[38;5;5mr[0m[38;5;8moyxmykx[39m [1m[38;5;4m20[0m[38;5;8md4acb3[39m [38;5;1m(conflict)[39m [38;5;2m(empty)[39m boom-cont
[1m[38;5;3mWarning: [39mThere are unresolved conflicts at these paths:[0m
conflicted1.txt [38;5;3m2-sided conflict[39m
conflicted2.txt [38;5;3m2-sided conflict[39m
[1m[38;5;6mHint: [0m[39mTo resolve the conflicts, start by creating a commit on top of[39m
[39mthe first conflicted commit:[39m
[39m jj new [1m[38;5;5mm[0m[38;5;8mzvwutvl[39m[39m
[39mThen use `jj resolve`, or edit the conflict markers in the file directly.[39m
[39mOnce the conflicts are resolved, you can inspect the result with `jj diff`.[39m
[39mThen run `jj squash` to move the resolution into the conflicted commit.[39m
[EOF]
");
let output = work_dir.run_jj(["status", "--config=hints.resolving-conflicts=false"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : yqosqzyt d31638b7 (conflict) (empty) boom-cont-2
Parent commit (@-): royxmykx 20d4acb3 (conflict) (empty) boom-cont
Warning: There are unresolved conflicts at these paths:
conflicted1.txt 2-sided conflict
conflicted2.txt 2-sided conflict
[EOF]
");
// Resolve conflict
work_dir.run_jj(["new", "--message", "fixed 1"]).success();
work_dir.write_file("conflicted1.txt", "first commit to fix conflict");
work_dir.write_file("conflicted2.txt", "first commit to fix conflict");
// Add one more commit atop the commit that resolves the conflict.
work_dir.run_jj(["new", "--message", "fixed 2"]).success();
work_dir.write_file("conflicted1.txt", "edit not conflict");
work_dir.write_file("conflicted2.txt", "edit not conflict");
// wc is now conflict free, parent is also conflict free
let output = work_dir.run_jj(["log", "-r", "::"]);
insta::assert_snapshot!(output, @r"
@ lylxulpl test.user@example.com 2001-02-03 08:05:21 db84565c
โ fixed 2
โ wqnwkozp test.user@example.com 2001-02-03 08:05:20 b64eded1
โ fixed 1
ร yqosqzyt test.user@example.com 2001-02-03 08:05:13 d31638b7 (conflict)
โ (empty) boom-cont-2
ร royxmykx test.user@example.com 2001-02-03 08:05:12 20d4acb3 (conflict)
โ (empty) boom-cont
ร mzvwutvl test.user@example.com 2001-02-03 08:05:11 553ce839 (conflict)
โโโฎ (empty) boom
โ โ kkmpptxz test.user@example.com 2001-02-03 08:05:10 7bb1724e
โ โ First part of conflicting change
โ โ zsuskuln test.user@example.com 2001-02-03 08:05:11 263e2eb6
โโโฏ Second part of conflicting change
โ qpvuntsm test.user@example.com 2001-02-03 08:05:08 8b2bca65
โ Initial contents
โ zzzzzzzz root() 00000000
[EOF]
");
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
M conflicted1.txt
M conflicted2.txt
Working copy (@) : lylxulpl db84565c fixed 2
Parent commit (@-): wqnwkozp b64eded1 fixed 1
[EOF]
");
// Step back one.
// wc is still conflict free, parent has a conflict.
work_dir.run_jj(["edit", "@-"]).success();
let output = work_dir.run_jj(["log", "-r", "::"]);
insta::assert_snapshot!(output, @r"
โ lylxulpl test.user@example.com 2001-02-03 08:05:21 db84565c
โ fixed 2
@ wqnwkozp test.user@example.com 2001-02-03 08:05:20 b64eded1
โ fixed 1
ร yqosqzyt test.user@example.com 2001-02-03 08:05:13 d31638b7 (conflict)
โ (empty) boom-cont-2
ร royxmykx test.user@example.com 2001-02-03 08:05:12 20d4acb3 (conflict)
โ (empty) boom-cont
ร mzvwutvl test.user@example.com 2001-02-03 08:05:11 553ce839 (conflict)
โโโฎ (empty) boom
โ โ kkmpptxz test.user@example.com 2001-02-03 08:05:10 7bb1724e
โ โ First part of conflicting change
โ โ zsuskuln test.user@example.com 2001-02-03 08:05:11 263e2eb6
โโโฏ Second part of conflicting change
โ qpvuntsm test.user@example.com 2001-02-03 08:05:08 8b2bca65
โ Initial contents
โ zzzzzzzz root() 00000000
[EOF]
");
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
M conflicted1.txt
M conflicted2.txt
Working copy (@) : wqnwkozp b64eded1 fixed 1
Parent commit (@-): yqosqzyt d31638b7 (conflict) (empty) boom-cont-2
Hint: Conflict in parent commit has been resolved in working copy
[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
// our hinting logic doesn't get confused.
work_dir.run_jj(["edit", "root()+"]).success();
let output = work_dir.run_jj(["log", "-r", "::"]);
insta::assert_snapshot!(output, @r"
โ lylxulpl test.user@example.com 2001-02-03 08:05:21 db84565c
โ fixed 2
โ wqnwkozp test.user@example.com 2001-02-03 08:05:20 b64eded1
โ fixed 1
ร yqosqzyt test.user@example.com 2001-02-03 08:05:13 d31638b7 (conflict)
โ (empty) boom-cont-2
ร royxmykx test.user@example.com 2001-02-03 08:05:12 20d4acb3 (conflict)
โ (empty) boom-cont
ร mzvwutvl test.user@example.com 2001-02-03 08:05:11 553ce839 (conflict)
โโโฎ (empty) boom
โ โ kkmpptxz test.user@example.com 2001-02-03 08:05:10 7bb1724e
โ โ First part of conflicting change
โ โ zsuskuln test.user@example.com 2001-02-03 08:05:11 263e2eb6
โโโฏ Second part of conflicting change
@ qpvuntsm test.user@example.com 2001-02-03 08:05:08 8b2bca65
โ Initial contents
โ zzzzzzzz root() 00000000
[EOF]
");
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
A conflicted1.txt
A conflicted2.txt
Working copy (@) : qpvuntsm 8b2bca65 Initial contents
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_status_simplify_conflict_sides() {
let test_env = TestEnvironment::default();
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
// fileB: A - A + A - A + B - C + D
create_commit_with_files(
&work_dir,
"base",
&[],
&[("fileA", "base\n"), ("fileB", "base\n")],
);
create_commit_with_files(&work_dir, "a1", &["base"], &[("fileA", "1\n")]);
create_commit_with_files(&work_dir, "a2", &["base"], &[("fileA", "2\n")]);
create_commit_with_files(&work_dir, "b1", &["base"], &[("fileB", "1\n")]);
create_commit_with_files(&work_dir, "b2", &["base"], &[("fileB", "2\n")]);
create_commit_with_files(&work_dir, "conflictA", &["a1", "a2"], &[]);
create_commit_with_files(&work_dir, "conflictB", &["b1", "b2"], &[]);
create_commit_with_files(&work_dir, "conflict", &["conflictA", "conflictB"], &[]);
insta::assert_snapshot!(work_dir.run_jj(["status"]),
@r"
The working copy has no changes.
Working copy (@) : nkmrtpmo 88a1af9c conflict | (conflict) (empty) conflict
Parent commit (@-): kmkuslsw 0fb57c44 conflictA | (conflict) (empty) conflictA
Parent commit (@-): lylxulpl 4ec7381a conflictB | (conflict) (empty) conflictB
Warning: There are unresolved conflicts at these paths:
fileA 2-sided conflict
fileB 2-sided conflict
Hint: To resolve the conflicts, start by creating a commit on top of
one of the first conflicted commits:
jj new lylxulpl
jj new kmkuslsw
Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved, you can inspect the result with `jj diff`.
Then run `jj squash` to move the resolution into the conflicted commit.
[EOF]
");
}
#[test]
fn test_status_untracked_files() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"snapshot.auto-track = "none()""#);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("always-untracked-file", "...");
work_dir.write_file("initially-untracked-file", "...");
let sub_dir = work_dir.create_dir("sub");
sub_dir.write_file("always-untracked", "...");
sub_dir.write_file("initially-untracked", "...");
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
Untracked paths:
? always-untracked-file
? initially-untracked-file
? sub/
Working copy (@) : qpvuntsm e8849ae1 (empty) (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
work_dir
.run_jj([
"file",
"track",
"initially-untracked-file",
"sub/initially-untracked",
])
.success();
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
Working copy changes:
A initially-untracked-file
A sub/initially-untracked
Untracked paths:
? always-untracked-file
? sub/always-untracked
Working copy (@) : qpvuntsm b8c1286d (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
Untracked paths:
? always-untracked-file
? sub/always-untracked
Working copy (@) : mzvwutvl daa133b8 (empty) (no description set)
Parent commit (@-): qpvuntsm b8c1286d (no description set)
[EOF]
");
work_dir
.run_jj([
"file",
"untrack",
"initially-untracked-file",
"sub/initially-untracked",
])
.success();
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
Working copy changes:
D initially-untracked-file
D sub/initially-untracked
Untracked paths:
? always-untracked-file
? initially-untracked-file
? sub/
Working copy (@) : mzvwutvl 240f261a (no description set)
Parent commit (@-): qpvuntsm b8c1286d (no description set)
[EOF]
");
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
Untracked paths:
? always-untracked-file
? initially-untracked-file
? sub/
Working copy (@) : yostqsxw 50beac0d (empty) (no description set)
Parent commit (@-): mzvwutvl 240f261a (no description set)
[EOF]
");
let output = work_dir.dir("sub").run_jj(["status"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
Untracked paths:
? ../always-untracked-file
? ../initially-untracked-file
? ./
Working copy (@) : yostqsxw 50beac0d (empty) (no description set)
Parent commit (@-): mzvwutvl 240f261a (no description set)
[EOF]
");
}
#[test]
fn test_status_no_working_copy() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["workspace", "forget"]).success();
insta::assert_snapshot!(work_dir.run_jj(["status"]), @r"
No working copy
[EOF]
");
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_debug_command.rs | cli/tests/test_debug_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use insta::assert_snapshot;
use regex::Regex;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
#[test]
fn test_debug_fileset() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["debug", "fileset", "all()"]);
assert_snapshot!(output, @r"
-- Parsed:
All
-- Matcher:
EverythingMatcher
[EOF]
");
let output = work_dir.run_jj(["debug", "fileset", "cwd:.."]);
assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Error: Failed to parse fileset: Invalid file pattern
Caused by:
1: --> 1:1
|
1 | cwd:..
| ^----^
|
= Invalid file pattern
2: Path ".." is not in the repo "."
3: Invalid component ".." in repo-relative path "../"
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_debug_revset() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let mut insta_settings = insta::Settings::clone_current();
insta_settings.add_filter(r"(?m)(^ .*\n)+", " ..\n");
let _guard = insta_settings.bind_to_scope();
let output = work_dir.run_jj(["debug", "revset", "root()"]);
assert_snapshot!(output, @r"
-- Parsed:
Root
-- Resolved:
Root
-- Optimized:
Root
-- Backend:
Commits(
..
)
-- Evaluated:
RevsetImpl {
..
}
-- Commit IDs:
0000000000000000000000000000000000000000
[EOF]
");
let output = work_dir.run_jj(["debug", "revset", "--no-optimize", "root() & ~@"]);
assert_snapshot!(output, @r"
-- Parsed:
Intersection(
..
)
-- Resolved:
Intersection(
..
)
-- Backend:
Intersection(
..
)
-- Evaluated:
RevsetImpl {
..
}
-- Commit IDs:
0000000000000000000000000000000000000000
[EOF]
");
let output = work_dir.run_jj(["debug", "revset", "--no-resolve", "foo & ~bar"]);
assert_snapshot!(output, @r"
-- Parsed:
Intersection(
..
)
-- Optimized:
Difference(
..
)
[EOF]
");
let output = work_dir.run_jj([
"debug",
"revset",
"--no-resolve",
"--no-optimize",
"foo & ~bar",
]);
assert_snapshot!(output, @r"
-- Parsed:
Intersection(
..
)
[EOF]
");
}
#[test]
fn test_debug_index() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["debug", "index"]);
assert_snapshot!(filter_index_stats(output), @r"
=== Commits ===
Number of commits: 2
Number of merges: 0
Max generation number: 1
Number of heads: 1
Number of changes: 2
Stats per level:
Level 0:
Number of commits: 2
Name: [hash]
=== Changed paths ===
Indexed commits: none
Stats per level:
[EOF]
");
// Enable changed-path index, index one commit
let output = work_dir.run_jj(["debug", "index-changed-paths", "-n1"]);
assert_snapshot!(output, @r"
------- stderr -------
Finished indexing 1..2 commits.
[EOF]
");
let output = work_dir.run_jj(["debug", "index"]);
assert_snapshot!(filter_index_stats(output), @r"
=== Commits ===
Number of commits: 2
Number of merges: 0
Max generation number: 1
Number of heads: 1
Number of changes: 2
Stats per level:
Level 0:
Number of commits: 2
Name: [hash]
=== Changed paths ===
Indexed commits: 1..2
Stats per level:
Level 0:
Number of commits: 1
Number of changed paths: 0
Number of paths: 0
Name: [hash]
[EOF]
");
}
#[test]
fn test_debug_reindex() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new"]).success();
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj(["debug", "index"]);
assert_snapshot!(filter_index_stats(output), @r"
=== Commits ===
Number of commits: 4
Number of merges: 0
Max generation number: 3
Number of heads: 1
Number of changes: 4
Stats per level:
Level 0:
Number of commits: 3
Name: [hash]
Level 1:
Number of commits: 1
Name: [hash]
=== Changed paths ===
Indexed commits: none
Stats per level:
[EOF]
");
let output = work_dir.run_jj(["debug", "reindex"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Finished indexing 4 commits.
[EOF]
");
let output = work_dir.run_jj(["debug", "index"]);
assert_snapshot!(filter_index_stats(output), @r"
=== Commits ===
Number of commits: 4
Number of merges: 0
Max generation number: 3
Number of heads: 1
Number of changes: 4
Stats per level:
Level 0:
Number of commits: 4
Name: [hash]
=== Changed paths ===
Indexed commits: none
Stats per level:
[EOF]
");
}
#[test]
fn test_debug_stacked_table() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new"]).success();
work_dir.run_jj(["new"]).success();
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj([
"debug",
"stacked-table",
".jj/repo/store/extra",
"--key-size=20", // HASH_LENGTH
]);
assert_snapshot!(filter_index_stats(output), @r"
Number of entries: 4
Stats per level:
Level 0:
Number of entries: 3
Name: [hash]
Level 1:
Number of entries: 1
Name: [hash]
[EOF]
");
}
#[test]
fn test_debug_tree() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let sub_dir = work_dir.create_dir_all("dir/subdir");
sub_dir.write_file("file1", "contents 1");
work_dir.run_jj(["new"]).success();
sub_dir.write_file("file2", "contents 2");
// Defaults to showing the tree at the current commit
let output = work_dir.run_jj(["debug", "tree"]);
assert_snapshot!(output.normalize_backslash(), @r#"
dir/subdir/file1: Ok(Resolved(Some(File { id: FileId("498e9b01d79cb8d31cdf0df1a663cc1fcefd9de3"), executable: false, copy_id: CopyId("") })))
dir/subdir/file2: Ok(Resolved(Some(File { id: FileId("b2496eaffe394cd50a9db4de5787f45f09fd9722"), executable: false, copy_id: CopyId("") })))
[EOF]
"#
);
// Can show the tree at another commit
let output = work_dir.run_jj(["debug", "tree", "-r@-"]);
assert_snapshot!(output.normalize_backslash(), @r#"
dir/subdir/file1: Ok(Resolved(Some(File { id: FileId("498e9b01d79cb8d31cdf0df1a663cc1fcefd9de3"), executable: false, copy_id: CopyId("") })))
[EOF]
"#
);
// Can filter by paths
let output = work_dir.run_jj(["debug", "tree", "dir/subdir/file2"]);
assert_snapshot!(output.normalize_backslash(), @r#"
dir/subdir/file2: Ok(Resolved(Some(File { id: FileId("b2496eaffe394cd50a9db4de5787f45f09fd9722"), executable: false, copy_id: CopyId("") })))
[EOF]
"#
);
// Can a show the root tree by id
let output = work_dir.run_jj([
"debug",
"tree",
"--id=0958358e3f80e794f032b25ed2be96cf5825da6c",
]);
assert_snapshot!(output.normalize_backslash(), @r#"
dir/subdir/file1: Ok(Resolved(Some(File { id: FileId("498e9b01d79cb8d31cdf0df1a663cc1fcefd9de3"), executable: false, copy_id: CopyId("") })))
dir/subdir/file2: Ok(Resolved(Some(File { id: FileId("b2496eaffe394cd50a9db4de5787f45f09fd9722"), executable: false, copy_id: CopyId("") })))
[EOF]
"#
);
// Can a show non-root tree by id
let output = work_dir.run_jj([
"debug",
"tree",
"--dir=dir",
"--id=6ac232efa713535ae518a1a898b77e76c0478184",
]);
assert_snapshot!(output.normalize_backslash(), @r#"
dir/subdir/file1: Ok(Resolved(Some(File { id: FileId("498e9b01d79cb8d31cdf0df1a663cc1fcefd9de3"), executable: false, copy_id: CopyId("") })))
dir/subdir/file2: Ok(Resolved(Some(File { id: FileId("b2496eaffe394cd50a9db4de5787f45f09fd9722"), executable: false, copy_id: CopyId("") })))
[EOF]
"#
);
// Can filter by paths when showing non-root tree (matcher applies from root)
let output = work_dir.run_jj([
"debug",
"tree",
"--dir=dir",
"--id=6ac232efa713535ae518a1a898b77e76c0478184",
"dir/subdir/file2",
]);
assert_snapshot!(output.normalize_backslash(), @r#"
dir/subdir/file2: Ok(Resolved(Some(File { id: FileId("b2496eaffe394cd50a9db4de5787f45f09fd9722"), executable: false, copy_id: CopyId("") })))
[EOF]
"#
);
}
fn filter_index_stats(output: CommandOutput) -> CommandOutput {
let regex = Regex::new(r" Name: [0-9a-z]+").unwrap();
output.normalize_stdout_with(|text| regex.replace_all(&text, " Name: [hash]").into_owned())
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_git_clone.rs | cli/tests/test_git_clone.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path;
use indoc::formatdoc;
use indoc::indoc;
use testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::to_toml_value;
fn set_up_non_empty_git_repo(git_repo: &gix::Repository) {
set_up_git_repo_with_file(git_repo, "file");
}
fn set_up_git_repo_with_file(git_repo: &gix::Repository, filename: &str) {
git::add_commit(
git_repo,
"refs/heads/main",
filename,
b"content",
"message",
&[],
);
git::set_symbolic_reference(git_repo, "HEAD", "refs/heads/main");
}
#[test]
fn test_git_clone() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path);
// Clone an empty repo
let output = root_dir.run_jj(["git", "clone", "source", "empty"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/empty"
Nothing changed.
[EOF]
"#);
set_up_non_empty_git_repo(&git_repo);
// Clone with relative source path
let output = root_dir.run_jj(["git", "clone", "source", "clone"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone"
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: uuqppmxq 3711b3b5 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 main | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
let clone_dir = test_env.work_dir("clone");
assert!(clone_dir.root().join("file").exists());
// Subsequent fetch should just work even if the source path was relative
let output = clone_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Failed clone should clean up the destination directory
root_dir.create_dir("bad");
let output = root_dir.run_jj(["git", "clone", "bad", "failed"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/failed"
Error: Could not find repository at '$TEST_ENV/bad'
[EOF]
[exit status: 1]
"#);
assert!(!test_env.env_root().join("failed").exists());
// Failed initialization of the workspace should clean up the destination
// directory
let output = root_dir.run_jj([
"git",
"clone",
"--config=fsmonitor.backend=invalid",
"source",
"failed-init",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Internal error: Failed to access the repository
Caused by:
1: Failed to read the tree state settings
2: Invalid type or value for fsmonitor.backend
3: Unknown fsmonitor kind: invalid
[EOF]
[exit status: 255]
");
assert!(!test_env.env_root().join("failed-init").exists());
// Failed clone shouldn't remove the existing destination directory
let failed_dir = root_dir.create_dir("failed");
let output = root_dir.run_jj(["git", "clone", "bad", "failed"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/failed"
Error: Could not find repository at '$TEST_ENV/bad'
[EOF]
[exit status: 1]
"#);
assert!(failed_dir.root().exists());
assert!(!failed_dir.root().join(".jj").exists());
// Failed clone (if attempted) shouldn't remove the existing workspace
let output = root_dir.run_jj(["git", "clone", "bad", "clone"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Destination path exists and is not an empty directory
[EOF]
[exit status: 1]
");
assert!(clone_dir.root().join(".jj").exists());
// Try cloning into an existing workspace
let output = root_dir.run_jj(["git", "clone", "source", "clone"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Destination path exists and is not an empty directory
[EOF]
[exit status: 1]
");
// Try cloning into an existing file
root_dir.write_file("file", "contents");
let output = root_dir.run_jj(["git", "clone", "source", "file"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Destination path exists and is not an empty directory
[EOF]
[exit status: 1]
");
// Try cloning into non-empty, non-workspace directory
clone_dir.remove_dir_all(".jj");
let output = root_dir.run_jj(["git", "clone", "source", "clone"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Destination path exists and is not an empty directory
[EOF]
[exit status: 1]
");
// Clone into a nested path
let output = root_dir.run_jj(["git", "clone", "source", "nested/path/to/repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/nested/path/to/repo"
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: vzqnnsmr fea36bca (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 main | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
}
#[test]
fn test_git_clone_bad_source() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let output = root_dir.run_jj(["git", "clone", "", "dest"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: local path "" does not specify a path to a repository
[EOF]
[exit status: 2]
"#);
// Invalid URL unparsable by gitoxide
let output = root_dir.run_jj(["git", "clone", "https://", "dest"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: URL "https://" can not be parsed as valid URL
Caused by: Scheme requires host
[EOF]
[exit status: 2]
"#);
}
#[test]
fn test_git_clone_colocate() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path);
// Clone an empty repo
let output = root_dir.run_jj(["git", "clone", "source", "empty", "--colocate"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/empty"
Nothing changed.
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
// git_target path should be relative to the store
let empty_dir = test_env.work_dir("empty");
let git_target_file_contents =
String::from_utf8(empty_dir.read_file(".jj/repo/store/git_target").into()).unwrap();
insta::assert_snapshot!(
git_target_file_contents.replace(path::MAIN_SEPARATOR, "/"),
@"../../../.git");
set_up_non_empty_git_repo(&git_repo);
// Clone with relative source path
let output = root_dir.run_jj(["git", "clone", "source", "clone", "--colocate"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone"
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: uuqppmxq 3711b3b5 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 main | message
Added 1 files, modified 0 files, removed 0 files
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
let clone_dir = test_env.work_dir("clone");
assert!(clone_dir.root().join("file").exists());
assert!(clone_dir.root().join(".git").exists());
eprintln!(
"{:?}",
git_repo.head().expect("Repo head should be set").name()
);
let jj_git_repo = git::open(clone_dir.root());
assert_eq!(
jj_git_repo
.head_id()
.expect("Clone Repo HEAD should be set.")
.detach(),
git_repo
.head_id()
.expect("Repo HEAD should be set.")
.detach(),
);
// ".jj" directory should be ignored at Git side.
let git_statuses = git::status(&jj_git_repo);
insta::assert_debug_snapshot!(git_statuses, @r#"
[
GitStatus {
path: ".jj/.gitignore",
status: Worktree(
Ignored,
),
},
GitStatus {
path: ".jj/repo",
status: Worktree(
Ignored,
),
},
GitStatus {
path: ".jj/working_copy",
status: Worktree(
Ignored,
),
},
]
"#);
// The old default bookmark "master" shouldn't exist.
insta::assert_snapshot!(get_bookmark_output(&clone_dir), @r"
main: qomsplrm ebeb70d8 message
@git: qomsplrm ebeb70d8 message
@origin: qomsplrm ebeb70d8 message
[EOF]
");
// Subsequent fetch should just work even if the source path was relative
let output = clone_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Failed clone should clean up the destination directory
root_dir.create_dir("bad");
let output = root_dir.run_jj(["git", "clone", "--colocate", "bad", "failed"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/failed"
Error: Could not find repository at '$TEST_ENV/bad'
[EOF]
[exit status: 1]
"#);
assert!(!test_env.env_root().join("failed").exists());
// Failed clone shouldn't remove the existing destination directory
let failed_dir = root_dir.create_dir("failed");
let output = root_dir.run_jj(["git", "clone", "--colocate", "bad", "failed"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/failed"
Error: Could not find repository at '$TEST_ENV/bad'
[EOF]
[exit status: 1]
"#);
assert!(failed_dir.root().exists());
assert!(!failed_dir.root().join(".git").exists());
assert!(!failed_dir.root().join(".jj").exists());
// Failed clone (if attempted) shouldn't remove the existing workspace
let output = root_dir.run_jj(["git", "clone", "--colocate", "bad", "clone"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Destination path exists and is not an empty directory
[EOF]
[exit status: 1]
");
assert!(clone_dir.root().join(".git").exists());
assert!(clone_dir.root().join(".jj").exists());
// Try cloning into an existing workspace
let output = root_dir.run_jj(["git", "clone", "source", "clone", "--colocate"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Destination path exists and is not an empty directory
[EOF]
[exit status: 1]
");
// Try cloning into an existing file
root_dir.write_file("file", "contents");
let output = root_dir.run_jj(["git", "clone", "source", "file", "--colocate"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Destination path exists and is not an empty directory
[EOF]
[exit status: 1]
");
// Try cloning into non-empty, non-workspace directory
clone_dir.remove_dir_all(".jj");
let output = root_dir.run_jj(["git", "clone", "source", "clone", "--colocate"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Destination path exists and is not an empty directory
[EOF]
[exit status: 1]
");
// Clone into a nested path
let output = root_dir.run_jj([
"git",
"clone",
"source",
"nested/path/to/repo",
"--colocate",
]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/nested/path/to/repo"
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: vzqnnsmr fea36bca (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 main | message
Added 1 files, modified 0 files, removed 0 files
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
}
#[test]
fn test_git_clone_colocate_via_config() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path);
test_env.add_config("git.colocate = true");
set_up_non_empty_git_repo(&git_repo);
let output = root_dir.run_jj(["git", "clone", "source", "clone"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone"
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: sqpuoqvx 1ca44815 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 main | message
Added 1 files, modified 0 files, removed 0 files
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
let clone_dir = test_env.work_dir("clone");
assert!(clone_dir.root().join("file").exists());
assert!(clone_dir.root().join(".git").exists());
}
#[test]
fn test_git_clone_no_colocate() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path);
test_env.add_config("git.colocate = true");
set_up_non_empty_git_repo(&git_repo);
let output = root_dir.run_jj(["git", "clone", "--no-colocate", "source", "clone"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone"
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: sqpuoqvx 1ca44815 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 main | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
let clone_dir = test_env.work_dir("clone");
assert!(clone_dir.root().join("file").exists());
assert!(!clone_dir.root().join(".git").exists());
}
#[test]
fn test_git_clone_tags() {
use gix::remote::fetch::Tags;
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
let source_git_repo = git::init(git_repo_path);
git::add_commit(
&source_git_repo,
"refs/tags/v1.0",
"foo",
b"content",
"message",
&[],
);
let commit = git::add_commit(
&source_git_repo,
"refs/tags/v2.0",
"bar",
b"content",
"message",
&[],
)
.commit_id;
git::add_commit(
&source_git_repo,
"refs/heads/main",
"baz",
b"content",
"message",
&[commit],
);
git::set_symbolic_reference(&source_git_repo, "HEAD", "refs/heads/main");
let run_test = |name, args: &[_]| {
// Clone an empty repo
root_dir.run_jj(
["git", "clone", "source", name, "--colocate"]
.iter()
.chain(args),
)
};
let get_remote_fetch_tags = |name| {
git::open(test_env.env_root().join(name))
.find_remote("origin")
.unwrap()
.fetch_tags()
};
insta::assert_snapshot!(run_test("default", &[]), @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/default"
bookmark: main@origin [new] tracked
tag: v1.0@git [new]
tag: v2.0@git [new]
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: sqpuoqvx 88542a00 (empty) (no description set)
Parent commit (@-) : lnmyztun e93ca54d main | message
Added 2 files, modified 0 files, removed 0 files
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
insta::assert_snapshot!(run_test("included", &["--fetch-tags", "included"]), @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/included"
bookmark: main@origin [new] tracked
tag: v2.0@git [new]
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: uuqppmxq 676b2fd8 (empty) (no description set)
Parent commit (@-) : lnmyztun e93ca54d main | message
Added 2 files, modified 0 files, removed 0 files
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
insta::assert_snapshot!(run_test("all", &["--fetch-tags", "all"]), @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/all"
bookmark: main@origin [new] tracked
tag: v1.0@git [new]
tag: v2.0@git [new]
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: pmmvwywv cd5996a2 (empty) (no description set)
Parent commit (@-) : lnmyztun e93ca54d main | message
Added 2 files, modified 0 files, removed 0 files
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
insta::assert_snapshot!(run_test("none", &["--fetch-tags", "none"]), @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/none"
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: rzvqmyuk 61c45a3c (empty) (no description set)
Parent commit (@-) : lnmyztun e93ca54d main | message
Added 2 files, modified 0 files, removed 0 files
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
assert_eq!(Tags::Included, get_remote_fetch_tags("default"));
assert_eq!(Tags::Included, get_remote_fetch_tags("included"));
assert_eq!(Tags::All, get_remote_fetch_tags("all"));
assert_eq!(Tags::None, get_remote_fetch_tags("none"));
}
#[test]
fn test_git_clone_remote_default_bookmark() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path.clone());
set_up_non_empty_git_repo(&git_repo);
// Create non-default bookmark in remote
let head_id = git_repo.head_id().unwrap().detach();
git_repo
.reference(
"refs/heads/feature1",
head_id,
gix::refs::transaction::PreviousValue::MustNotExist,
"",
)
.unwrap();
// All fetched bookmarks will be imported if auto-track-bookmarks = '*'
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
let output = root_dir.run_jj(["git", "clone", "source", "clone1"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone1"
bookmark: feature1@origin [new] tracked
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: sqpuoqvx 1ca44815 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 feature1 main | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
let clone_dir1 = test_env.work_dir("clone1");
insta::assert_snapshot!(get_bookmark_output(&clone_dir1), @r"
feature1: qomsplrm ebeb70d8 message
@origin: qomsplrm ebeb70d8 message
main: qomsplrm ebeb70d8 message
@origin: qomsplrm ebeb70d8 message
[EOF]
");
// "trunk()" alias should be set to default bookmark "main"
let output = clone_dir1.run_jj(["config", "list", "--repo", "revset-aliases.'trunk()'"]);
insta::assert_snapshot!(output, @r#"
revset-aliases.'trunk()' = "main@origin"
[EOF]
"#);
// Only the default bookmark will be imported if auto-track-bookmarks = '~*'
test_env.add_config("remotes.origin.auto-track-bookmarks = '~*'");
let output = root_dir.run_jj(["git", "clone", "source", "clone2"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone2"
bookmark: feature1@origin [new] untracked
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: rzvqmyuk 27e56779 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 feature1@origin main | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
let clone_dir2 = test_env.work_dir("clone2");
insta::assert_snapshot!(get_bookmark_output(&clone_dir2), @r"
feature1@origin: qomsplrm ebeb70d8 message
main: qomsplrm ebeb70d8 message
@origin: qomsplrm ebeb70d8 message
[EOF]
");
// Change the default bookmark in remote
git::set_symbolic_reference(&git_repo, "HEAD", "refs/heads/feature1");
let output = root_dir.run_jj(["git", "clone", "source", "clone3"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone3"
bookmark: feature1@origin [new] tracked
bookmark: main@origin [new] untracked
Setting the revset alias `trunk()` to `feature1@origin`
Working copy (@) now at: nppvrztz b16020e9 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 feature1 main@origin | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
let clone_dir3 = test_env.work_dir("clone3");
insta::assert_snapshot!(get_bookmark_output(&clone_dir3), @r"
feature1: qomsplrm ebeb70d8 message
@origin: qomsplrm ebeb70d8 message
main@origin: qomsplrm ebeb70d8 message
[EOF]
");
// "trunk()" alias should be set to new default bookmark "feature1"
let output = clone_dir3.run_jj(["config", "list", "--repo", "revset-aliases.'trunk()'"]);
insta::assert_snapshot!(output, @r#"
revset-aliases.'trunk()' = "feature1@origin"
[EOF]
"#);
// No bookmarks should be imported if both auto-track-bookmarks and
// track-default-bookmark-on-clone are turned off
let output = root_dir.run_jj([
"git",
"clone",
"--config=git.track-default-bookmark-on-clone=false",
"source",
"clone4",
]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone4"
bookmark: feature1@origin [new] untracked
bookmark: main@origin [new] untracked
Setting the revset alias `trunk()` to `feature1@origin`
Working copy (@) now at: wmwvqwsz 5068d576 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 feature1@origin main@origin | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
let clone_dir4 = test_env.work_dir("clone4");
insta::assert_snapshot!(get_bookmark_output(&clone_dir4), @r"
feature1@origin: qomsplrm ebeb70d8 message
main@origin: qomsplrm ebeb70d8 message
[EOF]
");
// Show hint if track-default-bookmark-on-clone=false has no effect
let output = root_dir.run_jj([
"git",
"clone",
"--config=git.auto-local-bookmark=true",
"--config=git.track-default-bookmark-on-clone=false",
"source",
"clone5",
]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Warning: Deprecated CLI-provided config: `git.auto-local-bookmark` is deprecated; use `remotes.<name>.auto-track-bookmarks` instead.
Example: jj config set --user remotes.origin.auto-track-bookmarks '*'
For details, see: https://docs.jj-vcs.dev/latest/config/#automatic-tracking-of-bookmarks
Fetching into new repo in "$TEST_ENV/clone5"
bookmark: feature1@origin [new] tracked
bookmark: main@origin [new] tracked
Hint: `git.track-default-bookmark-on-clone=false` has no effect if `git.auto-local-bookmark` is enabled.
Setting the revset alias `trunk()` to `feature1@origin`
Working copy (@) now at: vzqnnsmr fea36bca (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 feature1 main | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
let clone_dir5 = test_env.work_dir("clone5");
insta::assert_snapshot!(get_bookmark_output(&clone_dir5), @r"
feature1: qomsplrm ebeb70d8 message
@origin: qomsplrm ebeb70d8 message
main: qomsplrm ebeb70d8 message
@origin: qomsplrm ebeb70d8 message
[EOF]
");
}
// A branch with a strange name should get quoted in the config. Windows doesn't
// like the strange name, so we don't run the test there.
#[cfg(unix)]
#[test]
fn test_git_clone_remote_default_bookmark_with_escape() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path);
// Create a branch to something that needs to be escaped
let commit_id = git::add_commit(
&git_repo,
"refs/heads/\"",
"file",
b"content",
"message",
&[],
)
.commit_id;
git::set_head_to_id(&git_repo, commit_id);
let output = root_dir.run_jj(["git", "clone", "source", "clone"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone"
bookmark: "\""@origin [new] tracked
Setting the revset alias `trunk()` to `"\""@origin`
Working copy (@) now at: sqpuoqvx 1ca44815 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 "\"" | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
// "trunk()" alias should be escaped and quoted
let clone_dir = test_env.work_dir("clone");
let output = clone_dir.run_jj(["config", "list", "--repo", "revset-aliases.'trunk()'"]);
insta::assert_snapshot!(output, @r#"
revset-aliases.'trunk()' = '"\""@origin'
[EOF]
"#);
}
#[test]
fn test_git_clone_ignore_working_copy() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path);
set_up_non_empty_git_repo(&git_repo);
// Should not update working-copy files
let output = root_dir.run_jj(["git", "clone", "--ignore-working-copy", "source", "clone"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone"
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
[EOF]
"#);
let clone_dir = test_env.work_dir("clone");
let output = clone_dir.run_jj(["status", "--ignore-working-copy"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : sqpuoqvx 1ca44815 (empty) (no description set)
Parent commit (@-): qomsplrm ebeb70d8 main | message
[EOF]
");
// TODO: Correct, but might be better to check out the root commit?
let output = clone_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The working copy is stale (not updated since operation 8f47435a3990).
Hint: Run `jj workspace update-stale` to update it.
See https://docs.jj-vcs.dev/latest/working-copy/#stale-working-copy for more information.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_clone_at_operation() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path);
set_up_non_empty_git_repo(&git_repo);
let output = root_dir.run_jj(["git", "clone", "--at-op=@-", "source", "clone"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --at-op is not respected
[EOF]
[exit status: 2]
");
}
#[test]
fn test_git_clone_with_remote_name() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path);
set_up_non_empty_git_repo(&git_repo);
// Clone with relative source path and a non-default remote name
let output = root_dir.run_jj(["git", "clone", "source", "clone", "--remote", "upstream"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone"
bookmark: main@upstream [new] tracked
Setting the revset alias `trunk()` to `main@upstream`
Working copy (@) now at: sqpuoqvx 1ca44815 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 main | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
}
#[test]
fn test_git_clone_with_remote_named_git() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
git::init(git_repo_path);
let output = root_dir.run_jj(["git", "clone", "--remote=git", "source", "dest"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remote named 'git' is reserved for local Git repository
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_clone_with_remote_with_slashes() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
git::init(git_repo_path);
let output = root_dir.run_jj(["git", "clone", "--remote=slash/origin", "source", "dest"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remotes with slashes are incompatible with jj: slash/origin
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_clone_trunk_deleted() {
let test_env = TestEnvironment::default();
let root_dir = test_env.work_dir("");
let git_repo_path = test_env.env_root().join("source");
let git_repo = git::init(git_repo_path);
set_up_non_empty_git_repo(&git_repo);
let clone_dir = test_env.work_dir("clone");
let output = root_dir.run_jj(["git", "clone", "source", "clone"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/clone"
bookmark: main@origin [new] tracked
Setting the revset alias `trunk()` to `main@origin`
Working copy (@) now at: sqpuoqvx 1ca44815 (empty) (no description set)
Parent commit (@-) : qomsplrm ebeb70d8 main | message
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
let output = clone_dir.run_jj(["bookmark", "forget", "--include-remotes", "main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Forgot 1 local bookmarks.
Forgot 1 remote bookmarks.
Warning: Failed to resolve `revset-aliases.trunk()`: Revision `main@origin` doesn't exist
Hint: Use `jj config edit --repo` to adjust the `trunk()` alias.
[EOF]
");
let output = clone_dir.run_jj(["log"]);
insta::assert_snapshot!(output, @r"
@ sqpuoqvx test.user@example.com 2001-02-03 08:05:07 1ca44815
โ (empty) (no description set)
โ qomsplrm someone@example.org 1970-01-01 11:00:00 ebeb70d8
โ message
โ zzzzzzzz root() 00000000
[EOF]
------- stderr -------
Warning: Failed to resolve `revset-aliases.trunk()`: Revision `main@origin` doesn't exist
Hint: Use `jj config edit --repo` to adjust the `trunk()` alias.
[EOF]
");
}
#[test]
fn test_git_clone_conditional_config() {
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_duplicate_command.rs | cli/tests/test_duplicate_command.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit;
#[test]
fn test_duplicate() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &[]);
create_commit(&work_dir, "c", &["a", "b"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 387b928721d9 c
โโโฎ
โ โ d18ca3e87135 b
โ โ 7d980be7a1d4 a
โโโฏ
โ 000000000000
[EOF]
");
let output = work_dir.run_jj(["duplicate", "all()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Cannot duplicate the root commit
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["duplicate", "none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No revisions to duplicate.
[EOF]
");
let output = work_dir.run_jj(["duplicate", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 7d980be7a1d4 as kpqxywon 13eb8bd0 a
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 387b928721d9 c
โโโฎ
โ โ d18ca3e87135 b
โ โ 7d980be7a1d4 a
โโโฏ
โ โ 13eb8bd0a547 a
โโโฏ
โ 000000000000
[EOF]
");
let output = work_dir.run_jj(["undo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Restored to operation: 9fdb56d75a27 (2001-02-03 08:05:13) create bookmark c pointing to commit 387b928721d9f2efff819ccce81868f32537d71f
[EOF]
");
let output = work_dir.run_jj(["duplicate" /* duplicates `c` */]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 387b928721d9 as lylxulpl 71c64df5 c
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 387b928721d9 c
โโโฎ
โ โ โ 71c64df584dc c
โญโโฌโโฏ
โ โ d18ca3e87135 b
โ โ 7d980be7a1d4 a
โโโฏ
โ 000000000000
[EOF]
");
}
#[test]
fn test_duplicate_many() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["a"]);
create_commit(&work_dir, "d", &["c"]);
create_commit(&work_dir, "e", &["b", "d"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0559be9bd4d0 e
โโโฎ
โ โ a2dbb1aad514 d
โ โ 991a7501d660 c
โ โ 123b4d91f6e5 b
โโโฏ
โ 7d980be7a1d4 a
โ 000000000000
[EOF]
");
let setup_opid = work_dir.current_operation_id();
let output = work_dir.run_jj(["duplicate", "b::"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 123b4d91f6e5 as wqnwkozp 10059c86 b
Duplicated 0559be9bd4d0 as mouksmqu 0afe2f34 e
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0559be9bd4d0 e
โโโฎ
โ โ 123b4d91f6e5 b
โ โ โ 0afe2f348a93 e
โ โญโโค
โ โ โ a2dbb1aad514 d
โ โ โ 991a7501d660 c
โโโฏ โ
โ โ 10059c8651d7 b
โโโโโฏ
โ 7d980be7a1d4 a
โ 000000000000
[EOF]
");
// Try specifying the same commit twice directly
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["duplicate", "b", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 123b4d91f6e5 as nkmrtpmo 1ccf2589 b
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0559be9bd4d0 e
โโโฎ
โ โ a2dbb1aad514 d
โ โ 991a7501d660 c
โ โ 123b4d91f6e5 b
โโโฏ
โ โ 1ccf2589bfd1 b
โโโฏ
โ 7d980be7a1d4 a
โ 000000000000
[EOF]
");
// Try specifying the same commit twice indirectly
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["duplicate", "b::", "d::"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 123b4d91f6e5 as xtnwkqum 1a94ffc6 b
Duplicated a2dbb1aad514 as pqrnrkux 6a17a96d d
Duplicated 0559be9bd4d0 as ztxkyksq b113bd5c e
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0559be9bd4d0 e
โโโฎ
โ โ a2dbb1aad514 d
โ โ 123b4d91f6e5 b
โ โ โ b113bd5c550a e
โ โ โโโฎ
โ โ โ โ 6a17a96d77d2 d
โ โโโโโฏ
โ โ โ 991a7501d660 c
โโโฏ โ
โ โ 1a94ffc6e6aa b
โโโโโฏ
โ 7d980be7a1d4 a
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Reminder of the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0559be9bd4d0 e
โโโฎ
โ โ a2dbb1aad514 d
โ โ 991a7501d660 c
โ โ 123b4d91f6e5 b
โโโฏ
โ 7d980be7a1d4 a
โ 000000000000
[EOF]
");
let output = work_dir.run_jj(["duplicate", "d::", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 7d980be7a1d4 as nlrtlrxv 117dd806 a
Duplicated a2dbb1aad514 as plymsszl f2ec1b7f d
Duplicated 0559be9bd4d0 as urrlptpw 9e54f34c e
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0559be9bd4d0 e
โโโฎ
โ โ a2dbb1aad514 d
โ โ โ 9e54f34ca238 e
โญโโโโค
โ โ โ f2ec1b7f4e82 d
โ โโโฏ
โ โ 991a7501d660 c
โ โ 123b4d91f6e5 b
โโโฏ
โ 7d980be7a1d4 a
โ โ 117dd80623e6 a
โโโฏ
โ 000000000000
[EOF]
");
// Check for BUG -- makes too many 'a'-s, etc.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["duplicate", "a::"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 7d980be7a1d4 as uuuvxpvw cb730319 a
Duplicated 123b4d91f6e5 as nmpuuozl b00a23f6 b
Duplicated 991a7501d660 as kzpokyyw 7c1b86d5 c
Duplicated a2dbb1aad514 as yxrlprzz 2f5494bb d
Duplicated 0559be9bd4d0 as mvkzkxrl 8a4c81fe e
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0559be9bd4d0 e
โโโฎ
โ โ a2dbb1aad514 d
โ โ 991a7501d660 c
โ โ 123b4d91f6e5 b
โโโฏ
โ 7d980be7a1d4 a
โ โ 8a4c81fee5f1 e
โ โโโฎ
โ โ โ 2f5494bb9bce d
โ โ โ 7c1b86d551da c
โ โ โ b00a23f660bf b
โ โโโฏ
โ โ cb7303191ed7 a
โโโฏ
โ 000000000000
[EOF]
");
}
#[test]
fn test_duplicate_destination() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a1", &[]);
create_commit(&work_dir, "a2", &["a1"]);
create_commit(&work_dir, "a3", &["a2"]);
create_commit(&work_dir, "b", &[]);
create_commit(&work_dir, "c", &[]);
create_commit(&work_dir, "d", &[]);
let setup_opid = work_dir.current_operation_id();
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 5248650c3314 d
โ โ 22370aa928dc c
โโโฏ
โ โ c406dbab05ac b
โโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
// Duplicate a single commit onto a single destination.
let output = work_dir.run_jj(["duplicate", "a1", "-o", "c"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as kxryzmor 08f0f980 a1
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 5248650c3314 d
โ โ 08f0f980b8ad a1
โ โ 22370aa928dc c
โโโฏ
โ โ c406dbab05ac b
โโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate a single commit onto multiple destinations.
let output = work_dir.run_jj(["duplicate", "a1", "-o", "c", "-o", "d"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as xznxytkn 0bad88fb a1
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
โ 0bad88fbab2e a1
โโโฎ
โ @ 5248650c3314 d
โ โ 22370aa928dc c
โโโฏ
โ โ c406dbab05ac b
โโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate a single commit onto its descendant.
let output = work_dir.run_jj(["duplicate", "a1", "-o", "a3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5d93a4b8f4bd as a descendant of itself
Duplicated 5d93a4b8f4bd as tlkvzzqu 8351ae70 (empty) a1
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 5248650c3314 d
โ โ 22370aa928dc c
โโโฏ
โ โ c406dbab05ac b
โโโฏ
โ โ 8351ae7027e4 a1
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits without a direct ancestry relationship onto a
// single destination.
let output = work_dir.run_jj(["duplicate", "-r=a1", "-r=b", "-o", "c"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as pzsxstzt 663f101c a1
Duplicated c406dbab05ac as nxkxtmvy b8a86167 b
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 5248650c3314 d
โ โ b8a8616787a4 b
โ โ โ 663f101c476a a1
โ โโโฏ
โ โ 22370aa928dc c
โโโฏ
โ โ c406dbab05ac b
โโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits without a direct ancestry relationship onto
// multiple destinations.
let output = work_dir.run_jj(["duplicate", "-r=a1", "b", "-o", "c", "-o", "d"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as qmkrwlvp b0f531b0 a1
Duplicated c406dbab05ac as pkqrwoqq 0df6b6b2 b
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
โ 0df6b6b21bfe b
โโโฎ
โ โ โ b0f531b01b33 a1
โญโโฌโโฏ
โ @ 5248650c3314 d
โ โ 22370aa928dc c
โโโฏ
โ โ c406dbab05ac b
โโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits with an ancestry relationship onto a
// single destination.
let output = work_dir.run_jj(["duplicate", "a1", "a3", "-o", "c"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as qwyusntz 5f1c245f a1
Duplicated 5fb83d2b58d6 as pwpvvyov 2a209b65 a3
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 5248650c3314 d
โ โ 2a209b658cd6 a3
โ โ 5f1c245fb9ae a1
โ โ 22370aa928dc c
โโโฏ
โ โ c406dbab05ac b
โโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits with an ancestry relationship onto
// multiple destinations.
let output = work_dir.run_jj(["duplicate", "a1", "a3", "-o", "c", "-o", "d"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as soqnvnyz bc6678fd a1
Duplicated 5fb83d2b58d6 as nmmmqslz a35b7e76 a3
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
โ a35b7e76b4dd a3
โ bc6678fdf2a5 a1
โโโฎ
โ @ 5248650c3314 d
โ โ 22370aa928dc c
โโโฏ
โ โ c406dbab05ac b
โโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
}
#[test]
fn test_duplicate_insert_after() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a1", &[]);
create_commit(&work_dir, "a2", &["a1"]);
create_commit(&work_dir, "a3", &["a2"]);
create_commit(&work_dir, "a4", &["a3"]);
create_commit(&work_dir, "b1", &[]);
create_commit(&work_dir, "b2", &["b1"]);
create_commit(&work_dir, "c1", &[]);
create_commit(&work_dir, "c2", &["c1"]);
create_commit(&work_dir, "d1", &[]);
create_commit(&work_dir, "d2", &["d1"]);
let setup_opid = work_dir.current_operation_id();
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ e9b68b6313be a4
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
// 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 -------
Duplicated 5d93a4b8f4bd as nlrtlrxv 52959024 a1
Rebased 1 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 8124402d0ebe b2
โ โ 52959024d93a a1
โ โ 6a9343b8797a b1
โโโฏ
โ โ e9b68b6313be a4
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate a single commit after a single ancestor commit.
let output = work_dir.run_jj(["duplicate", "a3", "--after", "a1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5fb83d2b58d6 as an ancestor of itself
Duplicated 5fb83d2b58d6 as uuuvxpvw f626655e a3
Rebased 3 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ cfea8bb13adf a4
โ โ 3a595c648b6d a3
โ โ 307ab42af890 a2
โ โ f626655ef3dd a3
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate a single commit after a single descendant commit.
let output = work_dir.run_jj(["duplicate", "a1", "--after", "a3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5d93a4b8f4bd as a descendant of itself
Duplicated 5d93a4b8f4bd as pkstwlsy 610e8ba1 (empty) a1
Rebased 1 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ f8077bd38256 a4
โ โ 610e8ba113f6 a1
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate a single commit after multiple commits with no direct
// relationship.
let output = work_dir.run_jj(["duplicate", "a1", "--after", "b1", "--after", "c1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as zowrlwsv a78c25cc a1
Rebased 2 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 4150b5a5466e c2
โ โ โ 4a1f33498a39 b2
โ โโโฏ
โ โ a78c25cc7d58 a1
โ โโโฎ
โ โ โ 9b24b49f717e c1
โโโโโฏ
โ โ 6a9343b8797a b1
โโโฏ
โ โ e9b68b6313be a4
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate a single commit after multiple commits including an ancestor.
let output = work_dir.run_jj(["duplicate", "a3", "--after", "a2", "--after", "b2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5fb83d2b58d6 as an ancestor of itself
Duplicated 5fb83d2b58d6 as wvmqtotl 0824a995 a3
Rebased 2 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ a916f82ba67e a4
โ โ 3568f02a532c a3
โ โ 0824a99549cc a3
โ โโโฎ
โ โ โ 65b6f1fe6b41 b2
โ โ โ 6a9343b8797a b1
โโโโโฏ
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate a single commit after multiple commits including a descendant.
let output = work_dir.run_jj(["duplicate", "a1", "--after", "a3", "--after", "b2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5d93a4b8f4bd as a descendant of itself
Duplicated 5d93a4b8f4bd as opwsxtwu 7548fb00 (empty) a1
Rebased 1 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 784c89a5ba72 a4
โ โ 7548fb00a50a a1
โ โโโฎ
โ โ โ 65b6f1fe6b41 b2
โ โ โ 6a9343b8797a b1
โโโโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits without a direct ancestry relationship after a
// single commit without a direct relationship.
let output = work_dir.run_jj(["duplicate", "a1", "b1", "--after", "c1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as ukwxllxp 0cedc1c7 a1
Duplicated 6a9343b8797a as yrwmsomt 0d18a4ba b1
Rebased 1 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 133e5ef54093 c2
โ โโโฎ
โ โ โ 0d18a4ba8860 b1
โ โ โ 0cedc1c7f5dc a1
โ โโโฏ
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ e9b68b6313be a4
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits without a direct ancestry relationship after a
// single commit which is an ancestor of one of the duplicated commits.
let output = work_dir.run_jj(["duplicate", "a3", "b1", "--after", "a2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5fb83d2b58d6 as an ancestor of itself
Duplicated 5fb83d2b58d6 as szrrkvty 5ea1ddf1 a3
Duplicated 6a9343b8797a as wvmrymqu 8081d164 b1
Rebased 2 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ e5be4d6a351f a4
โ โ d6fe9e37ad2e a3
โ โโโฎ
โ โ โ 8081d1648811 b1
โ โ โ 5ea1ddf11f02 a3
โ โโโฏ
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits without a direct ancestry relationship after a
// single commit which is a descendant of one of the duplicated commits.
let output = work_dir.run_jj(["duplicate", "a1", "b1", "--after", "a3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5d93a4b8f4bd as a descendant of itself
Duplicated 5d93a4b8f4bd as ztnvrxlv 896deede (empty) a1
Duplicated 6a9343b8797a as upuzqpxs ad048f81 b1
Rebased 1 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ 87ec7e281ad9 a4
โ โโโฎ
โ โ โ ad048f810d3c b1
โ โ โ 896deede3c03 a1
โ โโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits without a direct ancestry relationship after
// multiple commits without a direct relationship to the duplicated commits.
let output = work_dir.run_jj(["duplicate", "a1", "b1", "--after", "c1", "--after", "d1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as muymlknp 7db83f0f a1
Duplicated 6a9343b8797a as snrzyvry d10bd4dd b1
Rebased 2 commits onto duplicated commits
Working copy (@) now at: nmzmmopx 57d2a947 d2 | d2
Parent commit (@-) : muymlknp 7db83f0f a1
Parent commit (@-) : snrzyvry d10bd4dd b1
Added 3 files, modified 0 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 57d2a947c305 d2
โโโฎ
โ โ โ aca0050dbbc4 c2
โญโโฌโโฏ
โ โ d10bd4ddb880 b1
โ โโโฎ
โ โ โ 7db83f0f554b a1
โฐโโฌโโฎ
โ โ ae61a031221a d1
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ e9b68b6313be a4
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits without a direct ancestry relationship after
// multiple commits including an ancestor of one of the duplicated commits.
let output = work_dir.run_jj(["duplicate", "a3", "b1", "--after", "a1", "--after", "c1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5fb83d2b58d6 as an ancestor of itself
Duplicated 5fb83d2b58d6 as vnqwxmpr 749e7782 a3
Duplicated 6a9343b8797a as pvqonzsn cdc6ab27 b1
Rebased 4 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 77dbe4a4ab86 c2
โ โโโฎ
โ โ โ โ 52a5fbe4cfe6 a4
โ โ โ โ 87a6779455c5 a3
โ โ โ โ 1df3435c91be a2
โ โญโโฌโโฏ
โ โ โ cdc6ab279cb7 b1
โ โ โโโฎ
โ โ โ โ 749e778247d3 a3
โ โฐโโฌโโฎ
โ โ โ 9b24b49f717e c1
โโโโโโโฏ
โ โ 5d93a4b8f4bd a1
โโโโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits without a direct ancestry relationship after
// multiple commits including a descendant of one of the duplicated commits.
let output = work_dir.run_jj(["duplicate", "a1", "b1", "--after", "a3", "--after", "c2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5d93a4b8f4bd as a descendant of itself
Duplicated 5d93a4b8f4bd as qtvkyytt e9ac46df (empty) a1
Duplicated 6a9343b8797a as ouvslmur bbf796e8 b1
Rebased 1 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ ecaa1f7b16fb a4
โ โโโฎ
โ โ โ bbf796e8f265 b1
โ โ โโโฎ
โ โ โ โ e9ac46df3691 a1
โ โฐโโฌโโฎ
โ โ โ 47a79ab4bbc6 c2
โ โ โ 9b24b49f717e c1
โโโโโโโฏ
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits with an ancestry relationship after a single
// commit without a direct relationship.
let output = work_dir.run_jj(["duplicate", "a1", "a3", "--after", "c2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as qowqnpnw 0478473b a1
Duplicated 5fb83d2b58d6 as mommxqln 6175d88f a3
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 6175d88f3848 a3
โ โ 0478473bfff3 a1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ e9b68b6313be a4
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits with an ancestry relationship after a single
// ancestor commit.
let output = work_dir.run_jj(["duplicate", "a2", "a3", "--after", "a1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 5fb83d2b58d6 as an ancestor of itself
Warning: Duplicating commit 7bfd9fbe959c as an ancestor of itself
Duplicated 7bfd9fbe959c as qzusktlu abac3b29 a2
Duplicated 5fb83d2b58d6 as zryotxso 0ac7bc72 a3
Rebased 3 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ e6b5faccb8d6 a4
โ โ 1b0489e81cdf a3
โ โ 91cc24eeda92 a2
โ โ 0ac7bc72e563 a3
โ โ abac3b29eace a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits with an ancestry relationship after a single
// descendant commit.
let output = work_dir.run_jj(["duplicate", "a1", "a2", "--after", "a3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Duplicating commit 7bfd9fbe959c as a descendant of itself
Warning: Duplicating commit 5d93a4b8f4bd as a descendant of itself
Duplicated 5d93a4b8f4bd as stzvpxow 607f49d4 (empty) a1
Duplicated 7bfd9fbe959c as zrzsnomp 802bec72 (empty) a2
Rebased 1 commits onto duplicated commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3e122d6a4b70 d2
โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ 5968d4b950df a4
โ โ 802bec723045 a2
โ โ 607f49d4e2dd a1
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits with an ancestry relationship after multiple
// commits without a direct relationship to the duplicated commits.
let output = work_dir.run_jj(["duplicate", "a1", "a3", "--after", "c2", "--after", "d2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Duplicated 5d93a4b8f4bd as ysllonyo 24a4e9f8 a1
Duplicated 5fb83d2b58d6 as kzxwzvzw 64d6f104 a3
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
โ 64d6f1045b10 a3
โ 24a4e9f817c7 a1
โโโฎ
โ @ 3e122d6a4b70 d2
โ โ ae61a031221a d1
โ โ 47a79ab4bbc6 c2
โ โ 9b24b49f717e c1
โโโฏ
โ โ 65b6f1fe6b41 b2
โ โ 6a9343b8797a b1
โโโฏ
โ โ e9b68b6313be a4
โ โ 5fb83d2b58d6 a3
โ โ 7bfd9fbe959c a2
โ โ 5d93a4b8f4bd a1
โโโฏ
โ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Duplicate multiple commits with an ancestry relationship after multiple
// commits including an ancestor of one of the duplicated commits.
let output = work_dir.run_jj(["duplicate", "a3", "a4", "--after", "a2", "--after", "c2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_operations.rs | cli/tests/test_operations.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use std::path::PathBuf;
use itertools::Itertools as _;
use regex::Regex;
use testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::to_toml_value;
#[test]
fn test_op_log() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["describe", "-m", "description 0"])
.success();
let output = work_dir.run_jj(["op", "log"]);
insta::assert_snapshot!(output, @r"
@ 12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
โ describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ args: jj describe -m 'description 0'
โ 8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
โ 000000000000 root()
[EOF]
");
let op_log_lines = output.stdout.raw().lines().collect_vec();
let add_workspace_id = op_log_lines[3].split(' ').nth(2).unwrap();
// Can load the repo at a specific operation ID
insta::assert_snapshot!(get_log_output(&work_dir, add_workspace_id), @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
โ 0000000000000000000000000000000000000000
[EOF]
");
// "@" resolves to the head operation
insta::assert_snapshot!(get_log_output(&work_dir, "@"), @r"
@ 3ae22e7f50a15d393e412cca72d09a61165d0c84
โ 0000000000000000000000000000000000000000
[EOF]
");
// "@-" resolves to the parent of the head operation
insta::assert_snapshot!(get_log_output(&work_dir, "@-"), @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
โ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["log", "--at-op", "@---"]), @r#"
------- stderr -------
Error: The "@---" expression resolved to no operations
[EOF]
[exit status: 1]
"#);
// We get a reasonable message if an invalid operation ID is specified
insta::assert_snapshot!(work_dir.run_jj(["log", "--at-op", "foo"]), @r#"
------- stderr -------
Error: Operation ID "foo" is not a valid hexadecimal prefix
[EOF]
[exit status: 1]
"#);
let output = work_dir.run_jj(["op", "log", "--op-diff"]);
insta::assert_snapshot!(output, @r"
@ 12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
โ describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ args: jj describe -m 'description 0'
โ
โ Changed commits:
โ โ + qpvuntsm 3ae22e7f (empty) description 0
โ - qpvuntsm/1 e8849ae1 (hidden) (empty) (no description set)
โ
โ Changed working copy default@:
โ + qpvuntsm 3ae22e7f (empty) description 0
โ - qpvuntsm/1 e8849ae1 (hidden) (empty) (no description set)
โ 8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
โ
โ Changed commits:
โ โ + qpvuntsm e8849ae1 (empty) (no description set)
โ
โ Changed working copy default@:
โ + qpvuntsm e8849ae1 (empty) (no description set)
โ - (absent)
โ 000000000000 root()
[EOF]
");
let output = work_dir.run_jj(["op", "log", "--op-diff", "--color=always"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m [1m[38;5;12m12f7cbba4278[39m [38;5;3mtest-username@host.example.com[39m [38;5;14m2001-02-03 04:05:08.000 +07:00[39m - [38;5;14m2001-02-03 04:05:08.000 +07:00[39m[0m
โ [1mdescribe commit e8849ae12c709f2321908879bc724fdb2ab8a781[0m
โ [1m[38;5;13margs: jj describe -m 'description 0'[39m[0m
โ
โ Changed commits:
โ โ [38;5;2m+[39m [1m[38;5;13mq[38;5;8mpvuntsm[39m [38;5;12m3[38;5;8mae22e7f[39m [38;5;10m(empty)[39m description 0[0m
โ [38;5;1m-[39m [1m[39mq[0m[38;5;8mpvuntsm[1m[39m/1[0m [1m[38;5;4me[0m[38;5;8m8849ae1[39m (hidden) [38;5;2m(empty)[39m [38;5;2m(no description set)[39m
โ
โ Changed working copy [38;5;2mdefault@[39m:
โ [38;5;2m+[39m [1m[38;5;13mq[38;5;8mpvuntsm[39m [38;5;12m3[38;5;8mae22e7f[39m [38;5;10m(empty)[39m description 0[0m
โ [38;5;1m-[39m [1m[39mq[0m[38;5;8mpvuntsm[1m[39m/1[0m [1m[38;5;4me[0m[38;5;8m8849ae1[39m (hidden) [38;5;2m(empty)[39m [38;5;2m(no description set)[39m
โ [38;5;4m8f47435a3990[39m [38;5;3mtest-username@host.example.com[39m [38;5;6m2001-02-03 04:05:07.000 +07:00[39m - [38;5;6m2001-02-03 04:05:07.000 +07:00[39m
โ add workspace 'default'
โ
โ Changed commits:
โ โ [38;5;2m+[39m [1m[38;5;13mq[38;5;8mpvuntsm[39m [38;5;12me[38;5;8m8849ae1[39m [38;5;10m(empty)[39m [38;5;10m(no description set)[0m
โ
โ Changed working copy [38;5;2mdefault@[39m:
โ [38;5;2m+[39m [1m[38;5;13mq[38;5;8mpvuntsm[39m [38;5;12me[38;5;8m8849ae1[39m [38;5;10m(empty)[39m [38;5;10m(no description set)[0m
โ [38;5;1m-[39m (absent)
โ [38;5;4m000000000000[39m [38;5;2mroot()[39m
[EOF]
");
work_dir
.run_jj(["describe", "-m", "description 1"])
.success();
work_dir
.run_jj([
"describe",
"-m",
"description 2",
"--at-op",
add_workspace_id,
])
.success();
insta::assert_snapshot!(work_dir.run_jj(["log", "--at-op", "@-"]), @r#"
------- stderr -------
Error: The "@" expression resolved to more than one operation
Hint: Try specifying one of the operations by ID: a57c1debcef0, 6a23c2d6dc15
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_op_log_with_custom_symbols() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["describe", "-m", "description 0"])
.success();
let output = work_dir.run_jj([
"op",
"log",
"--config=templates.op_log_node='if(current_operation, \"$\", if(root, \"โด\", \"โ\"))'",
]);
insta::assert_snapshot!(output, @r"
$ 12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
โ describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ args: jj describe -m 'description 0'
โ 8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
โด 000000000000 root()
[EOF]
");
}
#[test]
fn test_op_log_with_no_template() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["op", "log", "-T"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: a value is required for '--template <TEMPLATE>' but none was supplied
For more information, try '--help'.
Hint: The following template aliases are defined:
- builtin_config_list
- builtin_config_list_detailed
- builtin_draft_commit_description
- builtin_evolog_compact
- builtin_log_comfortable
- builtin_log_compact
- builtin_log_compact_full_description
- builtin_log_detailed
- builtin_log_node
- builtin_log_node_ascii
- builtin_log_oneline
- builtin_log_redacted
- builtin_op_log_comfortable
- builtin_op_log_compact
- builtin_op_log_node
- builtin_op_log_node_ascii
- builtin_op_log_oneline
- builtin_op_log_redacted
- commit_summary_separator
- default_commit_description
- description_placeholder
- email_placeholder
- empty_commit_marker
- git_format_patch_email_headers
- name_placeholder
[EOF]
[exit status: 2]
");
}
#[test]
fn test_op_log_limit() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["op", "log", "-Tdescription", "--limit=1"]);
insta::assert_snapshot!(output, @r"
@ add workspace 'default'
[EOF]
");
}
#[test]
fn test_op_log_no_graph() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["op", "log", "--no-graph", "--color=always"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;12m8f47435a3990[39m [38;5;3mtest-username@host.example.com[39m [38;5;14m2001-02-03 04:05:07.000 +07:00[39m - [38;5;14m2001-02-03 04:05:07.000 +07:00[39m[0m
[1madd workspace 'default'[0m
[38;5;4m000000000000[39m [38;5;2mroot()[39m
[EOF]
");
let output = work_dir.run_jj(["op", "log", "--op-diff", "--no-graph"]);
insta::assert_snapshot!(output, @r"
8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
add workspace 'default'
Changed commits:
+ qpvuntsm e8849ae1 (empty) (no description set)
Changed working copy default@:
+ qpvuntsm e8849ae1 (empty) (no description set)
- (absent)
000000000000 root()
[EOF]
");
}
#[test]
fn test_op_log_reversed() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["describe", "-m", "description 0"])
.success();
let output = work_dir.run_jj(["op", "log", "--reversed"]);
insta::assert_snapshot!(output, @r"
โ 000000000000 root()
โ 8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
@ 12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
args: jj describe -m 'description 0'
[EOF]
");
work_dir
.run_jj(["describe", "-m", "description 1", "--at-op", "@-"])
.success();
// Should be able to display log with fork and branch points
let output = work_dir.run_jj(["op", "log", "--reversed"]);
insta::assert_snapshot!(output, @r"
โ 000000000000 root()
โ 8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
โโโฎ add workspace 'default'
โ โ 39f59ea3ec6e test-username@host.example.com 2001-02-03 04:05:10.000 +07:00 - 2001-02-03 04:05:10.000 +07:00
โ โ describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ โ args: jj describe -m 'description 1' --at-op @-
โ โ 12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
โโโฏ describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ args: jj describe -m 'description 0'
@ fa6e12f12705 test-username@host.example.com 2001-02-03 04:05:11.000 +07:00 - 2001-02-03 04:05:11.000 +07:00
reconcile divergent operations
args: jj op log --reversed
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
// Should work correctly with `--no-graph`
let output = work_dir.run_jj(["op", "log", "--reversed", "--no-graph"]);
insta::assert_snapshot!(output, @r"
000000000000 root()
8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
add workspace 'default'
39f59ea3ec6e test-username@host.example.com 2001-02-03 04:05:10.000 +07:00 - 2001-02-03 04:05:10.000 +07:00
describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
args: jj describe -m 'description 1' --at-op @-
12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
args: jj describe -m 'description 0'
fa6e12f12705 test-username@host.example.com 2001-02-03 04:05:11.000 +07:00 - 2001-02-03 04:05:11.000 +07:00
reconcile divergent operations
args: jj op log --reversed
[EOF]
");
// Should work correctly with `--limit`
let output = work_dir.run_jj(["op", "log", "--reversed", "--limit=3"]);
insta::assert_snapshot!(output, @r"
โ 39f59ea3ec6e test-username@host.example.com 2001-02-03 04:05:10.000 +07:00 - 2001-02-03 04:05:10.000 +07:00
โ describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ args: jj describe -m 'description 1' --at-op @-
โ โ 12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
โโโฏ describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ args: jj describe -m 'description 0'
@ fa6e12f12705 test-username@host.example.com 2001-02-03 04:05:11.000 +07:00 - 2001-02-03 04:05:11.000 +07:00
reconcile divergent operations
args: jj op log --reversed
[EOF]
");
// Should work correctly with `--limit` and `--no-graph`
let output = work_dir.run_jj(["op", "log", "--reversed", "--limit=2", "--no-graph"]);
insta::assert_snapshot!(output, @r"
12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
args: jj describe -m 'description 0'
fa6e12f12705 test-username@host.example.com 2001-02-03 04:05:11.000 +07:00 - 2001-02-03 04:05:11.000 +07:00
reconcile divergent operations
args: jj op log --reversed
[EOF]
");
}
#[test]
fn test_op_log_no_graph_null_terminated() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "message1"]).success();
work_dir.run_jj(["commit", "-m", "message2"]).success();
let output = work_dir
.run_jj([
"op",
"log",
"--no-graph",
"--template",
r#"id.short(4) ++ "\0""#,
])
.success();
insta::assert_debug_snapshot!(output.stdout.normalized(), @r#""a9e5\00265\08f47\00000\0""#);
}
#[test]
fn test_op_log_template() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let render = |template| work_dir.run_jj(["op", "log", "-T", template]);
insta::assert_snapshot!(render(r#"id ++ "\n""#), @r"
@ 8f47435a3990362feaf967ca6de2eb0a31c8b883dfcb66fba5c22200d12bbe61e3dc8bc855f1f6879285fcafaf85ac792f9a43bcc36e57d28737d18347d5e752
โ 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(
render(r#"separate(" ", id.short(5), current_operation, user,
time.start(), time.end(), time.duration()) ++ "\n""#), @r"
@ 8f474 true test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 2001-02-03 04:05:07.000 +07:00 less than a microsecond
โ 00000 false @ 1970-01-01 00:00:00.000 +00:00 1970-01-01 00:00:00.000 +00:00 less than a microsecond
[EOF]
");
// Negative length shouldn't cause panic.
insta::assert_snapshot!(render(r#"id.short(-1) ++ "|""#), @r"
@ <Error: out of range integral type conversion attempted>|
โ <Error: out of range integral type conversion attempted>|
[EOF]
");
insta::assert_snapshot!(render(r#"json(self) ++ "\n""#), @r#"
@ {"id":"8f47435a3990362feaf967ca6de2eb0a31c8b883dfcb66fba5c22200d12bbe61e3dc8bc855f1f6879285fcafaf85ac792f9a43bcc36e57d28737d18347d5e752","parents":["00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"],"time":{"start":"2001-02-03T04:05:07+07:00","end":"2001-02-03T04:05:07+07:00"},"description":"add workspace 'default'","hostname":"host.example.com","username":"test-username","is_snapshot":false,"tags":{}}
โ {"id":"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","parents":[],"time":{"start":"1970-01-01T00:00:00Z","end":"1970-01-01T00:00:00Z"},"description":"","hostname":"","username":"","is_snapshot":false,"tags":{}}
[EOF]
"#);
// Test the default template, i.e. with relative start time and duration. We
// don't generally use that template because it depends on the current time,
// so we need to reset the time range format here.
test_env.add_config(
r#"
[template-aliases]
'format_time_range(time_range)' = 'time_range.end().ago() ++ ", lasted " ++ time_range.duration()'
"#,
);
let regex = Regex::new(r"\d\d years").unwrap();
let output = work_dir.run_jj(["op", "log"]);
insta::assert_snapshot!(
output.normalize_stdout_with(|s| regex.replace_all(&s, "NN years").into_owned()), @r"
@ 8f47435a3990 test-username@host.example.com NN years ago, lasted less than a microsecond
โ add workspace 'default'
โ 000000000000 root()
[EOF]
");
}
#[test]
fn test_op_log_builtin_templates() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Render without graph to test line ending
let render = |template| work_dir.run_jj(["op", "log", "-T", template, "--no-graph"]);
work_dir
.run_jj(["describe", "-m", "description 0"])
.success();
insta::assert_snapshot!(render(r#"builtin_op_log_compact"#), @r"
12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
args: jj describe -m 'description 0'
8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
add workspace 'default'
000000000000 root()
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_op_log_comfortable"#), @r"
12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
args: jj describe -m 'description 0'
8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
add workspace 'default'
000000000000 root()
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_op_log_oneline"#), @r"
12f7cbba4278 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00 describe commit e8849ae12c709f2321908879bc724fdb2ab8a781 args: jj describe -m 'description 0'
8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00 add workspace 'default'
000000000000 root()
[EOF]
");
}
#[test]
fn test_op_log_word_wrap() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n".repeat(100));
work_dir.run_jj(["debug", "snapshot"]).success();
let render = |args: &[&str], columns: u32, word_wrap: bool| {
let word_wrap = to_toml_value(word_wrap);
work_dir.run_jj_with(|cmd| {
cmd.args(args)
.arg(format!("--config=ui.log-word-wrap={word_wrap}"))
.env("COLUMNS", columns.to_string())
})
};
// ui.log-word-wrap option works
insta::assert_snapshot!(render(&["op", "log"], 40, false), @r"
@ 2144f9621985 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
โ snapshot working copy
โ args: jj debug snapshot
โ 8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
โ 000000000000 root()
[EOF]
");
insta::assert_snapshot!(render(&["op", "log"], 40, true), @r"
@ 2144f9621985
โ test-username@host.example.com
โ 2001-02-03 04:05:08.000 +07:00 -
โ 2001-02-03 04:05:08.000 +07:00
โ snapshot working copy
โ args: jj debug snapshot
โ 8f47435a3990
โ test-username@host.example.com
โ 2001-02-03 04:05:07.000 +07:00 -
โ 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
โ 000000000000 root()
[EOF]
");
// Nested graph should be wrapped
insta::assert_snapshot!(render(&["op", "log", "--op-diff"], 40, true), @r"
@ 2144f9621985
โ test-username@host.example.com
โ 2001-02-03 04:05:08.000 +07:00 -
โ 2001-02-03 04:05:08.000 +07:00
โ snapshot working copy
โ args: jj debug snapshot
โ
โ Changed commits:
โ โ + qpvuntsm 79f0968d (no
โ description set)
โ - qpvuntsm/1 e8849ae1 (hidden)
โ (empty) (no description set)
โ
โ Changed working copy default@:
โ + qpvuntsm 79f0968d (no description
โ set)
โ - qpvuntsm/1 e8849ae1 (hidden)
โ (empty) (no description set)
โ 8f47435a3990
โ test-username@host.example.com
โ 2001-02-03 04:05:07.000 +07:00 -
โ 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
โ
โ Changed commits:
โ โ + qpvuntsm e8849ae1 (empty) (no
โ description set)
โ
โ Changed working copy default@:
โ + qpvuntsm e8849ae1 (empty) (no
โ description set)
โ - (absent)
โ 000000000000 root()
[EOF]
");
// Nested diff stat shouldn't exceed the terminal width
insta::assert_snapshot!(render(&["op", "log", "-n1", "--stat"], 40, true), @r"
@ 2144f9621985
โ test-username@host.example.com
โ 2001-02-03 04:05:08.000 +07:00 -
โ 2001-02-03 04:05:08.000 +07:00
โ snapshot working copy
โ args: jj debug snapshot
โ
โ Changed commits:
โ โ + qpvuntsm 79f0968d (no
โ description set)
โ - qpvuntsm/1 e8849ae1 (hidden)
โ (empty) (no description set)
โ file1 | 100 ++++++++++++++++++++++
โ 1 file changed, 100 insertions(+), 0 deletions(-)
โ
โ Changed working copy default@:
โ + qpvuntsm 79f0968d (no description
โ set)
โ - qpvuntsm/1 e8849ae1 (hidden)
โ (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(render(&["op", "log", "-n1", "--no-graph", "--stat"], 40, true), @r"
2144f9621985
test-username@host.example.com
2001-02-03 04:05:08.000 +07:00 -
2001-02-03 04:05:08.000 +07:00
snapshot working copy
args: jj debug snapshot
Changed commits:
+ qpvuntsm 79f0968d (no description set)
- qpvuntsm/1 e8849ae1 (hidden) (empty)
(no description set)
file1 | 100 ++++++++++++++++++++++++++++
1 file changed, 100 insertions(+), 0 deletions(-)
Changed working copy default@:
+ qpvuntsm 79f0968d (no description set)
- qpvuntsm/1 e8849ae1 (hidden) (empty)
(no description set)
[EOF]
");
// Nested graph widths should be subtracted from the term width
let config = r#"templates.commit_summary='"0 1 2 3 4 5 6 7 8 9"'"#;
insta::assert_snapshot!(
render(&["op", "log", "-T''", "--op-diff", "-n1", "--config", config], 15, true), @r"
@
โ Changed
โ commits:
โ โ + 0 1 2 3
โ 4 5 6 7 8
โ 9
โ - 0 1 2 3
โ 4 5 6 7 8
โ 9
โ
โ Changed
โ working copy
โ default@:
โ + 0 1 2 3 4
โ 5 6 7 8 9
โ - 0 1 2 3 4
โ 5 6 7 8 9
[EOF]
");
}
#[test]
fn test_op_log_configurable() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"operation.hostname = "my-hostname"
operation.username = "my-username"
"#,
);
test_env
.run_jj_with(|cmd| {
cmd.args(["git", "init", "repo"])
.env_remove("JJ_OP_HOSTNAME")
.env_remove("JJ_OP_USERNAME")
})
.success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["op", "log"]);
insta::assert_snapshot!(output, @r"
@ 906f45b6b2a8 my-username@my-hostname 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
โ 000000000000 root()
[EOF]
");
}
#[test]
fn test_op_abandon_invalid() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Create a merge operation
work_dir.run_jj(["commit", "-m", "commit 1"]).success();
work_dir
.run_jj(["commit", "--at-op=@-", "-m", "commit 2"])
.success();
work_dir.run_jj(["commit", "-m", "commit 3"]).success();
insta::assert_snapshot!(work_dir.run_jj(["op", "log", "-T", "description"]), @"
@ commit 4e0592f3dd52e7a4998a97d9a1f354e2727a856b
โ reconcile divergent operations
โโโฎ
โ โ commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ โ commit e8849ae12c709f2321908879bc724fdb2ab8a781
โโโฏ
โ add workspace 'default'
โ
[EOF]
");
// Cannot abandon the root operation
let output = work_dir.run_jj(["op", "abandon", "000000000000"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Error: Cannot abandon the root operation
[EOF]
[exit status: 1]
");
// Cannot abandon merge operations
let output = work_dir.run_jj(["op", "abandon", "@-"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Error: Cannot abandon a merge operation
[EOF]
[exit status: 1]
");
// Cannot abandon the current operation (specified via "..")
let output = work_dir.run_jj(["op", "abandon", "@-.."]);
insta::assert_snapshot!(output, @"
------- stderr -------
Error: Cannot abandon the current operation 633ee70ce825
Hint: Run `jj undo` to revert the current operation, then use `jj op abandon`
[EOF]
[exit status: 1]
");
// Confirm no change
insta::assert_snapshot!(work_dir.run_jj(["op", "log", "-T", "description"]), @"
@ commit 4e0592f3dd52e7a4998a97d9a1f354e2727a856b
โ reconcile divergent operations
โโโฎ
โ โ commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ โ commit e8849ae12c709f2321908879bc724fdb2ab8a781
โโโฏ
โ add workspace 'default'
โ
[EOF]
");
}
#[test]
fn test_op_abandon_ancestors() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "commit 1"]).success();
work_dir.run_jj(["commit", "-m", "commit 2"]).success();
insta::assert_snapshot!(work_dir.run_jj(["op", "log"]), @r"
@ 3fc56f6bb4db test-username@host.example.com 2001-02-03 04:05:09.000 +07:00 - 2001-02-03 04:05:09.000 +07:00
โ commit 4e0592f3dd52e7a4998a97d9a1f354e2727a856b
โ args: jj commit -m 'commit 2'
โ c815486340d5 test-username@host.example.com 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
โ commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ args: jj commit -m 'commit 1'
โ 8f47435a3990 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
โ add workspace 'default'
โ 000000000000 root()
[EOF]
");
// Abandon old operations. The working-copy operation id should be updated.
let output = work_dir.run_jj(["op", "abandon", "..@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 2 operations and reparented 1 descendant operations.
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["debug", "local-working-copy", "--ignore-working-copy"]), @r#"
Current operation: OperationId("1675333b7de89b5da012c696d797345bad2a6ce55a4b605e85c3897f818f05e11e8c53de19d34c2fee38a36528dc95bd2a378f72ac0877f8bec2513a68043253")
Current tree: MergedTree { tree_ids: Resolved(TreeId("4b825dc642cb6eb9a060e54bf8d69288fbee4904")), labels: Unlabeled, .. }
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["op", "log"]), @r"
@ 1675333b7de8 test-username@host.example.com 2001-02-03 04:05:09.000 +07:00 - 2001-02-03 04:05:09.000 +07:00
โ commit 4e0592f3dd52e7a4998a97d9a1f354e2727a856b
โ args: jj commit -m 'commit 2'
โ 000000000000 root()
[EOF]
");
// Abandon operation range.
work_dir.run_jj(["commit", "-m", "commit 3"]).success();
work_dir.run_jj(["commit", "-m", "commit 4"]).success();
work_dir.run_jj(["commit", "-m", "commit 5"]).success();
let output = work_dir.run_jj(["op", "abandon", "@---..@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 2 operations and reparented 1 descendant operations.
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["op", "log"]), @r"
@ 9df33337d494 test-username@host.example.com 2001-02-03 04:05:16.000 +07:00 - 2001-02-03 04:05:16.000 +07:00
โ commit 2f3e935ade915272ccdce9e43e5a5c82fc336aee
โ args: jj commit -m 'commit 5'
โ 1675333b7de8 test-username@host.example.com 2001-02-03 04:05:09.000 +07:00 - 2001-02-03 04:05:09.000 +07:00
โ commit 4e0592f3dd52e7a4998a97d9a1f354e2727a856b
โ args: jj commit -m 'commit 2'
โ 000000000000 root()
[EOF]
");
// Can't abandon the current operation.
let output = work_dir.run_jj(["op", "abandon", "..@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Cannot abandon the current operation 9df33337d494
Hint: Run `jj undo` to revert the current operation, then use `jj op abandon`
[EOF]
[exit status: 1]
");
// Can't create concurrent abandoned operations explicitly.
let output = work_dir.run_jj(["op", "abandon", "--at-op=@-", "@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --at-op is not respected
[EOF]
[exit status: 2]
");
// Abandon the current operation by reverting it first.
work_dir.run_jj(["op", "revert"]).success();
let output = work_dir.run_jj(["op", "abandon", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 operations and reparented 1 descendant operations.
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["debug", "local-working-copy", "--ignore-working-copy"]), @r#"
Current operation: OperationId("ce6a0300b7346109e75a6dcc97e3ff9e1488ce43a4073dd9eb81afb7f463b4543d3f15cf9a42a9864a4aaf6daab900b6b037dbdcb95f87422e891f7e884641aa")
Current tree: MergedTree { tree_ids: Resolved(TreeId("4b825dc642cb6eb9a060e54bf8d69288fbee4904")), labels: Unlabeled, .. }
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["op", "log"]), @r"
@ ce6a0300b734 test-username@host.example.com 2001-02-03 04:05:21.000 +07:00 - 2001-02-03 04:05:21.000 +07:00
โ revert operation 9df33337d49450b21bf694025557ede1ac4c63c7b17f593add0d7adc81b394d363f1edffa025b323f88ec947dcd9214f46e82e742e7a74adbfff4c2d96321133
โ args: jj op revert
โ 1675333b7de8 test-username@host.example.com 2001-02-03 04:05:09.000 +07:00 - 2001-02-03 04:05:09.000 +07:00
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_acls.rs | cli/tests/test_acls.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use jj_lib::secret_backend::SecretBackend;
use crate::common::TestEnvironment;
#[test]
fn test_diff() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.create_dir("dir");
work_dir.write_file("a-first", "foo\n");
work_dir.write_file("deleted-secret", "foo\n");
work_dir.write_file("dir/secret", "foo\n");
work_dir.write_file("modified-secret", "foo\n");
work_dir.write_file("z-last", "foo\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("a-first", "bar\n");
work_dir.remove_file("deleted-secret");
work_dir.write_file("added-secret", "bar\n");
work_dir.write_file("dir/secret", "bar\n");
work_dir.write_file("modified-secret", "bar\n");
work_dir.write_file("z-last", "bar\n");
SecretBackend::adopt_git_repo(work_dir.root());
let output = work_dir.run_jj(["diff", "--color-words"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
Modified regular file a-first:
1 1: foobar
Access denied to added-secret: No access
Access denied to deleted-secret: No access
Access denied to dir/secret: No access
Access denied to modified-secret: No access
Modified regular file z-last:
1 1: foobar
[EOF]
");
let output = work_dir.run_jj(["diff", "--summary"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
M a-first
C {a-first => added-secret}
D deleted-secret
M dir/secret
M modified-secret
M z-last
[EOF]
");
let output = work_dir.run_jj(["diff", "--types"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
FF a-first
FF {a-first => added-secret}
F- deleted-secret
FF dir/secret
FF modified-secret
FF z-last
[EOF]
");
let output = work_dir.run_jj(["diff", "--stat"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
a-first | 2 +-
{a-first => added-secret} | 2 +-
deleted-secret | 1 -
dir/secret | 0
modified-secret | 0
z-last | 2 +-
6 files changed, 3 insertions(+), 4 deletions(-)
[EOF]
");
let output = work_dir.run_jj(["diff", "--git"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
diff --git a/a-first b/a-first
index 257cc5642c..5716ca5987 100644
--- a/a-first
+++ b/a-first
@@ -1,1 +1,1 @@
-foo
+bar
[EOF]
------- stderr -------
Error: Access denied to added-secret
Caused by: No access
[EOF]
[exit status: 1]
");
// TODO: Test external tool
}
#[test]
fn test_file_list_show() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("a-first", "foo\n");
work_dir.write_file("secret", "bar\n");
work_dir.write_file("z-last", "baz\n");
SecretBackend::adopt_git_repo(work_dir.root());
// "file list" should just work since it doesn't access file content
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
a-first
secret
z-last
[EOF]
");
let output = work_dir.run_jj(["file", "show", "."]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
foo
baz
[EOF]
------- stderr -------
Warning: Path 'secret' exists but access is denied: No access
[EOF]
");
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_root.rs | cli/tests/test_root.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use test_case::test_case;
use testutils::TestRepoBackend;
use testutils::TestWorkspace;
use crate::common::TestEnvironment;
#[test_case(TestRepoBackend::Simple ; "simple backend")]
#[test_case(TestRepoBackend::Git ; "git backend")]
fn test_root(backend: TestRepoBackend) {
let test_env = TestEnvironment::default();
let test_workspace = TestWorkspace::init_with_backend(backend);
let root = test_workspace.workspace.workspace_root();
let subdir = root.join("subdir");
std::fs::create_dir(&subdir).unwrap();
let output = test_env.run_jj_in(&subdir, ["root"]).success();
assert_eq!(
output.stdout.raw(),
&[root.to_str().unwrap(), "\n"].concat()
);
}
#[test]
fn test_root_outside_a_repo() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(Path::new("/"), ["root"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_file_search_command.rs | cli/tests/test_file_search_command.rs | // Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::TestEnvironment;
#[test]
fn test_file_search() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "-foo-");
work_dir.write_file("file2", "-bar-");
work_dir.run_jj(["new"]).success();
work_dir.create_dir("dir");
work_dir.write_file("dir/file3", "-foobar-");
// Searches all files in the current revision by default
let output = work_dir.run_jj(["file", "search", "--pattern=*foo*"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
dir/file3
file1
[EOF]
");
// Matches only the whole line
let output = work_dir.run_jj(["file", "search", "--pattern=foo"]);
insta::assert_snapshot!(output.normalize_backslash(), @"");
// Can search files in another revision
let output = work_dir.run_jj(["file", "search", "--pattern=*foo*", "-r=@-"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
file1
[EOF]
");
// Can filter by path
let output = work_dir.run_jj(["file", "search", "--pattern=*foo*", "dir"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
dir/file3
[EOF]
");
// Warning if path doesn't exist
let output = work_dir.run_jj(["file", "search", "--pattern=*foo*", "file9"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
------- stderr -------
Warning: No matching entries for paths: file9
[EOF]
");
}
#[test]
fn test_file_search_conflicts() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "-foo-");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "-bar-");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "-baz-");
work_dir.run_jj(["rebase", "-r=@", "-B=@-"]).success();
// Test the setup
insta::assert_snapshot!(work_dir.read_file("file1"), @r"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 958d516d (parents of rebased revision) (no terminating newline)
\\\\\\\ to: qpvuntsm 6da222ee (rebase destination) (no terminating newline)
--bar-
+-foo-
+++++++ kkmpptxz 95e61837 (rebased revision) (no terminating newline)
-baz-
>>>>>>> conflict 1 of 1 ends
");
// Matches positive terms
let output = work_dir.run_jj(["file", "search", "--pattern=*foo*"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
file1
[EOF]
");
let output = work_dir.run_jj(["file", "search", "--pattern=*bar*"]);
insta::assert_snapshot!(output.normalize_backslash(), @"");
let output = work_dir.run_jj(["file", "search", "--pattern=*baz*"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
file1
[EOF]
");
// Doesn't match the conflict markers
let output = work_dir.run_jj(["file", "search", "--pattern=*%%%*"]);
insta::assert_snapshot!(output.normalize_backslash(), @"");
// Doesn't list file if the pattern doesn't match
let output = work_dir.run_jj(["file", "search", "--pattern=*qux*"]);
insta::assert_snapshot!(output.normalize_backslash(), @"");
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_new_command.rs | cli/tests/test_new_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit;
use crate::common::create_commit_with_files;
#[test]
fn test_new() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "add a file"]).success();
work_dir.run_jj(["new", "-m", "a new commit"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 22aec45f30a36a2d244c70e131e369d79e400962 a new commit
โ 55eabcc47301440da7a71d5610d3db021d1925ca add a file
โ 0000000000000000000000000000000000000000
[EOF]
");
// 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();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 8818c9ee28d00667cb3072a2114a67619ded7ceb off of root
โ โ 22aec45f30a36a2d244c70e131e369d79e400962 a new commit
โ โ 55eabcc47301440da7a71d5610d3db021d1925ca add a file
โโโฏ
โ 0000000000000000000000000000000000000000
[EOF]
");
// --edit is a no-op
work_dir
.run_jj(["new", "--edit", "-m", "yet another commit"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 9629f035563a7d9fa86becc783ae71557bd25269 yet another commit
โ 8818c9ee28d00667cb3072a2114a67619ded7ceb off of root
โ โ 22aec45f30a36a2d244c70e131e369d79e400962 a new commit
โ โ 55eabcc47301440da7a71d5610d3db021d1925ca add a file
โโโฏ
โ 0000000000000000000000000000000000000000
[EOF]
");
// --edit cannot be used with --no-edit
let output = work_dir.run_jj(["new", "--edit", "B", "--no-edit", "D"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--edit' cannot be used with '--no-edit'
Usage: jj new <REVSETS>...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_new_merge() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
work_dir.run_jj(["describe", "-m", "add file1"]).success();
work_dir.write_file("file1", "a");
work_dir
.run_jj(["new", "root()", "-m", "add file2"])
.success();
work_dir.write_file("file2", "b");
work_dir.run_jj(["debug", "snapshot"]).success();
let setup_opid = work_dir.current_operation_id();
// Create a merge commit
work_dir.run_jj(["new", "main", "@"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 94ce38ef81dc7912c1574cc5aa2f434b9057d58a
โโโฎ
โ โ 5bf404a038660799fae348cc31b9891349c128c1 add file2
โ โ 96ab002e5b86c39a661adc0524df211a3dac3f1b add file1
โโโฏ
โ 0000000000000000000000000000000000000000
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1"]);
insta::assert_snapshot!(output, @"a[EOF]");
let output = work_dir.run_jj(["file", "show", "file2"]);
insta::assert_snapshot!(output, @"b[EOF]");
// Same test with `--no-edit`
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["new", "main", "@", "--no-edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Created new commit kpqxywon 061f4210 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
โ 061f42107e030034242b424264f22985429552c1
โโโฎ
โ @ 5bf404a038660799fae348cc31b9891349c128c1 add file2
โ โ 96ab002e5b86c39a661adc0524df211a3dac3f1b add file1
โโโฏ
โ 0000000000000000000000000000000000000000
[EOF]
");
// Same test with `jj new`
work_dir.run_jj(["op", "restore", &setup_opid]).success();
work_dir.run_jj(["new", "main", "@"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ cee60a55c085ff349af7fa1e7d6b7d4b7bdd4c3a
โโโฎ
โ โ 5bf404a038660799fae348cc31b9891349c128c1 add file2
โ โ 96ab002e5b86c39a661adc0524df211a3dac3f1b add file1
โโโฏ
โ 0000000000000000000000000000000000000000
[EOF]
");
// merge with non-unique revisions
let output = work_dir.run_jj(["new", "@", "3a44e"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revision `3a44e` doesn't exist
[EOF]
[exit status: 1]
");
// duplicates are allowed
let output = work_dir.run_jj(["new", "@", "visible_heads()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: uyznsvlq 68a7f50c (empty) (no description set)
Parent commit (@-) : lylxulpl cee60a55 (empty) (no description set)
[EOF]
");
// merge with root
let output = work_dir.run_jj(["new", "@", "root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The Git backend does not support creating merge commits with the root commit as one of the parents.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_merge_parents_order() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "1", &[]);
create_commit(&work_dir, "2", &[]);
create_commit(&work_dir, "3", &[]);
create_commit(&work_dir, "4", &[]);
create_commit(&work_dir, "5", &[]);
// The order of positional and -r/-o args should be preserved
work_dir
.run_jj([
"new",
"-osubject(2)",
"subject(3)",
"-rsubject(1)",
"-dsubject(5)",
"subject(4)",
])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 2034dc93c6ddad404d1aa677ab99b0621d8e109d
โโโฌโโฌโโฌโโฎ
โ โ โ โ โ de5bab19f679c52a021c343b8942ca875ec6aae7 4
โ โ โ โ โ de3c6b2c8e065351203063817ef0794df1adb2f9 5
โ โ โ โโโฏ
โ โ โ โ 1783ad0eb5c21d958b2e1bf8caab9b019f3d16e9 1
โ โ โโโฏ
โ โ โ fb047eea4c2bec04e2fd3cd21eca0193d5720341 3
โ โโโฏ
โ โ 36b1b4840ac943a08e7f953df4eadc53e825f2a6 2
โโโฏ
โ 0000000000000000000000000000000000000000
[EOF]
");
}
#[test]
fn test_new_merge_conflicts() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "1", &[], &[("file", "1a\n1b\n")]);
create_commit_with_files(&work_dir, "2", &["1"], &[("file", "1a 2a\n1b\n2c\n")]);
create_commit_with_files(&work_dir, "3", &["1"], &[("file", "3a 1a\n1b\n")]);
// merge line by line by default
let output = work_dir.run_jj(["new", "2|3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv d85cd009 (conflict) (empty) (no description set)
Parent commit (@-) : royxmykx 1b282e07 3 | 3
Parent commit (@-) : zsuskuln 7ac709e5 2 | 2
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz a93ed0a5 "1"
\\\\\\\ to: royxmykx 1b282e07 "3"
-1a
+3a 1a
+++++++ zsuskuln 7ac709e5 "2"
1a 2a
>>>>>>> conflict 1 of 1 ends
1b
2c
"#);
// reset working copy
work_dir.run_jj(["new", "root()"]).success();
// merge word by word
let output = work_dir.run_jj(["new", "2|3", "--config=merge.hunk-level=word"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: znkkpsqq 892ac90f (empty) (no description set)
Parent commit (@-) : royxmykx 1b282e07 3 | 3
Parent commit (@-) : zsuskuln 7ac709e5 2 | 2
Added 1 files, modified 0 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @r"
3a 1a 2a
1b
2c
");
}
#[test]
fn test_new_merge_same_change() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "1", &[], &[("file", "a\n")]);
create_commit_with_files(&work_dir, "2", &["1"], &[("file", "a\nb\n")]);
create_commit_with_files(&work_dir, "3", &["1"], &[("file", "a\nb\n")]);
// same-change conflict is resolved by default
let output = work_dir.run_jj(["new", "2|3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 7bebf0fe (empty) (no description set)
Parent commit (@-) : royxmykx 1b9fe696 3 | 3
Parent commit (@-) : zsuskuln 829e1e90 2 | 2
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @r"
a
b
");
// reset working copy
work_dir.run_jj(["new", "root()"]).success();
// keep same-change conflict
let output = work_dir.run_jj(["new", "2|3", "--config=merge.same-change=keep"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: znkkpsqq af8f7324 (conflict) (empty) (no description set)
Parent commit (@-) : royxmykx 1b9fe696 3 | 3
Parent commit (@-) : zsuskuln 829e1e90 2 | 2
Added 1 files, modified 0 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @r#"
a
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 2adf972b "1"
\\\\\\\ to: royxmykx 1b9fe696 "3"
+b
+++++++ zsuskuln 829e1e90 "2"
b
>>>>>>> conflict 1 of 1 ends
"#);
}
#[test]
fn test_new_insert_after() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
@ F
โโโฎ
โ โ E
โ โ D
โโโฏ
โ โ C
โ โ B
โ โ A
โโโฏ
โ root
[EOF]
");
// --insert-after can be repeated; --after is an alias
let output = work_dir.run_jj(["new", "-m", "G", "--insert-after", "B", "--after", "D"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 descendant commits
Working copy (@) now at: kxryzmor 57acfedf (empty) G
Parent commit (@-) : kkmpptxz bb98b010 B | (empty) B
Parent commit (@-) : vruxwmqv 521674f5 D | (empty) D
[EOF]
");
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
โ C
โ โ F
โญโโค
@ โ G
โโโโโฎ
โ โ โ D
โ โ โ B
โ โ โ A
โโโโโฏ
โ โ E
โโโฏ
โ root
[EOF]
");
let output = work_dir.run_jj(["new", "-m", "H", "--insert-after", "D"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 descendant commits
Working copy (@) now at: uyznsvlq fd3f1413 (empty) H
Parent commit (@-) : vruxwmqv 521674f5 D | (empty) D
[EOF]
");
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
โ C
โ โ F
โญโโค
โ โ G
โโโโโฎ
โ โ @ H
โ โ โ D
โ โ โ B
โ โ โ A
โโโโโฏ
โ โ E
โโโฏ
โ root
[EOF]
");
// --after cannot be used with revisions
let output = work_dir.run_jj(["new", "--after", "B", "D"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--insert-after <REVSETS>' cannot be used with:
[REVSETS]...
-o <REVSETS>
Usage: jj new --insert-after <REVSETS> <REVSETS>...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_new_insert_after_children() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
@ F
โโโฎ
โ โ E
โ โ D
โโโฏ
โ โ C
โ โ B
โ โ A
โโโฏ
โ root
[EOF]
");
// Attempting to insert G after A and C errors out due to the cycle created
// as A is an ancestor of C.
let output = work_dir.run_jj([
"new",
"-m",
"G",
"--insert-after",
"A",
"--insert-after",
"C",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Refusing to create a loop: commit d32ebe56a293 would be both an ancestor and a descendant of the new commit
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_insert_before() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
@ F
โโโฎ
โ โ E
โ โ D
โโโฏ
โ โ C
โ โ B
โ โ A
โโโฏ
โ root
[EOF]
");
let output = work_dir.run_jj([
"new",
"-m",
"G",
"--insert-before",
"C",
"--insert-before",
"F",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 descendant commits
Working copy (@) now at: kxryzmor 2f16c40d (empty) G
Parent commit (@-) : kkmpptxz bb98b010 B | (empty) B
Parent commit (@-) : vruxwmqv 521674f5 D | (empty) D
Parent commit (@-) : znkkpsqq 56a33cd0 E | (empty) E
[EOF]
");
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
โ F
โ โ C
โโโฏ
@ G
โโโฌโโฎ
โ โ โ E
โ โ โ D
โ โโโฏ
โ โ B
โ โ A
โโโฏ
โ root
[EOF]
");
// --before cannot be used with revisions
let output = work_dir.run_jj(["new", "--before", "B", "D"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--insert-before <REVSETS>' cannot be used with:
[REVSETS]...
-o <REVSETS>
Usage: jj new --insert-before <REVSETS> <REVSETS>...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_new_insert_before_root_successors() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
@ F
โโโฎ
โ โ E
โ โ D
โโโฏ
โ โ C
โ โ B
โ โ A
โโโฏ
โ root
[EOF]
");
let output = work_dir.run_jj([
"new",
"-m",
"G",
"--insert-before",
"A",
"--insert-before",
"D",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 5 descendant commits
Working copy (@) now at: kxryzmor 8c026b06 (empty) G
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
โ F
โโโฎ
โ โ E
โ โ D
โ โ โ C
โ โ โ B
โ โ โ A
โโโโโฏ
@ โ G
โโโฏ
โ root
[EOF]
");
}
#[test]
fn test_new_insert_before_no_loop() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
let template = r#"commit_id.short() ++ " " ++ if(description, description, "root")"#;
let output = work_dir.run_jj(["log", "-T", template]);
insta::assert_snapshot!(output, @r"
@ a8176a8a5348 F
โโโฎ
โ โ 56a33cd09d90 E
โ โ 521674f591a6 D
โโโฏ
โ โ d32ebe56a293 C
โ โ bb98b0102ef5 B
โ โ 515354d01f1b A
โโโฏ
โ 000000000000 root
[EOF]
");
let output = work_dir.run_jj([
"new",
"-m",
"G",
"--insert-before",
"A",
"--insert-before",
"C",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Refusing to create a loop: commit bb98b0102ef5 would be both an ancestor and a descendant of the new commit
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_insert_before_no_root_merge() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
@ F
โโโฎ
โ โ E
โ โ D
โโโฏ
โ โ C
โ โ B
โ โ A
โโโฏ
โ root
[EOF]
");
let output = work_dir.run_jj([
"new",
"-m",
"G",
"--insert-before",
"B",
"--insert-before",
"D",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The Git backend does not support creating merge commits with the root commit as one of the parents.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_insert_before_root() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
@ F
โโโฎ
โ โ E
โ โ D
โโโฏ
โ โ C
โ โ B
โ โ A
โโโฏ
โ root
[EOF]
");
let output = work_dir.run_jj(["new", "-m", "G", "--insert-before", "root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The root commit 000000000000 is immutable
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_insert_after_before() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
@ F
โโโฎ
โ โ E
โ โ D
โโโฏ
โ โ C
โ โ B
โ โ A
โโโฏ
โ root
[EOF]
");
let output = work_dir.run_jj(["new", "-m", "G", "--after", "C", "--before", "F"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: kxryzmor 55a63f47 (empty) G
Parent commit (@-) : mzvwutvl d32ebe56 C | (empty) C
[EOF]
");
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
โ F
โโโฌโโฎ
โ โ @ G
โ โ โ C
โ โ โ B
โ โ โ A
โ โ โ E
โ โโโฏ
โ โ D
โโโฏ
โ root
[EOF]
");
let output = work_dir.run_jj(["new", "-m", "H", "--after", "D", "--before", "B"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 4 descendant commits
Working copy (@) now at: uyznsvlq fd3f1413 (empty) H
Parent commit (@-) : vruxwmqv 521674f5 D | (empty) D
[EOF]
");
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
โ F
โโโฌโโฎ
โ โ โ G
โ โ โ C
โ โ โ B
โ โ โโโฎ
โ โ โ @ H
โโโโโโโฏ
โ โ โ D
โ โ โ A
โโโโโฏ
โ โ E
โโโฏ
โ root
[EOF]
");
}
#[test]
fn test_new_insert_after_before_no_loop() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
let template = r#"commit_id.short() ++ " " ++ if(description, description, "root")"#;
let output = work_dir.run_jj(["log", "-T", template]);
insta::assert_snapshot!(output, @r"
@ a8176a8a5348 F
โโโฎ
โ โ 56a33cd09d90 E
โ โ 521674f591a6 D
โโโฏ
โ โ d32ebe56a293 C
โ โ bb98b0102ef5 B
โ โ 515354d01f1b A
โโโฏ
โ 000000000000 root
[EOF]
");
let output = work_dir.run_jj([
"new",
"-m",
"G",
"--insert-before",
"A",
"--insert-after",
"C",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Refusing to create a loop: commit d32ebe56a293 would be both an ancestor and a descendant of the new commit
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_insert_after_empty_before() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
setup_before_insertion(&work_dir);
let template = r#"commit_id.short() ++ " " ++ if(description, description, "root")"#;
let output = work_dir.run_jj(["log", "-T", template]);
insta::assert_snapshot!(output, @r"
@ a8176a8a5348 F
โโโฎ
โ โ 56a33cd09d90 E
โ โ 521674f591a6 D
โโโฏ
โ โ d32ebe56a293 C
โ โ bb98b0102ef5 B
โ โ 515354d01f1b A
โโโฏ
โ 000000000000 root
[EOF]
");
let output = work_dir.run_jj(["new", "-mG", "--insert-before=none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No revisions found to use as parent
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["new", "-mG", "--insert-before=none()", "--insert-after=B"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: nkmrtpmo d7088f92 (empty) G
Parent commit (@-) : kkmpptxz bb98b010 B | (empty) B
[EOF]
");
insta::assert_snapshot!(get_short_log_output(&work_dir), @r"
@ G
โ โ C
โโโฏ
โ B
โ A
โ โ F
โ โโโฎ
โ โ โ E
โโโโโฏ
โ โ D
โโโฏ
โ root
[EOF]
");
}
#[test]
fn test_new_conflicting_bookmarks() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "one"]).success();
work_dir.run_jj(["new", "-m", "two", "@-"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "foo"])
.success();
work_dir
.run_jj(["--at-op=@-", "bookmark", "create", "foo", "-rsubject(one)"])
.success();
// Trigger resolution of divergent operations
work_dir.run_jj(["st"]).success();
let output = work_dir.run_jj(["new", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Name `foo` is conflicted
Hint: Use commit ID to select single revision from: 96948328bc42, 401ea16fc3fe
Hint: Use `bookmarks(foo)` to select all revisions
Hint: To set which revision the bookmark points to, run `jj bookmark set foo -r <REVISION>`
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_conflicting_change_ids() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "one"]).success();
work_dir
.run_jj(["--at-op=@-", "describe", "-m", "two"])
.success();
// Trigger resolution of divergent operations
work_dir.run_jj(["st"]).success();
let output = work_dir.run_jj(["new", "qpvuntsm"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Change ID `qpvuntsm` is divergent
Hint: Use change offset to select single revision: qpvuntsm/0, qpvuntsm/1
Hint: Use `change_id(qpvuntsm)` to select all revisions
Hint: To abandon unneeded revisions, run `jj abandon <commit_id>`
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_error_revision_does_not_exist() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "one"]).success();
work_dir.run_jj(["new", "-m", "two"]).success();
let output = work_dir.run_jj(["new", "this"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revision `this` doesn't exist
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_with_trailers() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "one"]).success();
test_env.add_config(
r#"[templates]
commit_trailers = '"Signed-off-by: " ++ committer.email()'
"#,
);
work_dir.run_jj(["new", "-m", "two"]).success();
let output = work_dir.run_jj(["log", "--no-graph", "-r@", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
two
Signed-off-by: test.user@example.com
[EOF]
");
// new without message has no trailer
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj(["log", "--no-graph", "-r@", "-Tdescription"]);
insta::assert_snapshot!(output, @"");
}
fn setup_before_insertion(work_dir: &TestWorkDir) {
work_dir
.run_jj(["bookmark", "create", "-r@", "A"])
.success();
work_dir.run_jj(["commit", "-m", "A"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "B"])
.success();
work_dir.run_jj(["commit", "-m", "B"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "C"])
.success();
work_dir.run_jj(["describe", "-m", "C"]).success();
work_dir.run_jj(["new", "-m", "D", "root()"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "D"])
.success();
work_dir.run_jj(["new", "-m", "E", "root()"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "E"])
.success();
work_dir.run_jj(["new", "-m", "F", "D", "E"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "F"])
.success();
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"commit_id ++ " " ++ description"#;
work_dir.run_jj(["log", "-T", template])
}
#[must_use]
fn get_short_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"if(description, description, "root")"#;
work_dir.run_jj(["log", "-T", template])
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/runner.rs | cli/tests/runner.rs | use std::path::PathBuf;
mod common;
#[test]
fn test_no_forgotten_test_files() {
let test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests");
testutils::assert_no_forgotten_test_files(&test_dir);
}
mod test_abandon_command;
mod test_absorb_command;
mod test_acls;
mod test_advance_bookmarks;
mod test_alias;
mod test_bisect_command;
mod test_bookmark_command;
mod test_builtin_aliases;
mod test_commit_command;
mod test_commit_template;
mod test_completion;
mod test_concurrent_operations;
mod test_config_command;
mod test_config_schema;
mod test_copy_detection;
mod test_debug_command;
mod test_debug_init_simple_command;
mod test_describe_command;
mod test_diff_command;
mod test_diffedit_command;
mod test_duplicate_command;
mod test_edit_command;
mod test_evolog_command;
mod test_file_annotate_command;
mod test_file_chmod_command;
mod test_file_list_command;
mod test_file_search_command;
mod test_file_show_command;
mod test_file_track_untrack_commands;
mod test_fix_command;
mod test_generate_md_cli_help;
mod test_gerrit_upload;
mod test_git_clone;
mod test_git_colocated;
mod test_git_colocation;
mod test_git_fetch;
mod test_git_import_export;
mod test_git_init;
mod test_git_private_commits;
mod test_git_push;
mod test_git_remotes;
mod test_git_root;
mod test_gitignores;
mod test_global_opts;
mod test_help_command;
mod test_identical_commits;
mod test_immutable_commits;
mod test_interdiff_command;
mod test_log_command;
mod test_metaedit_command;
mod test_new_command;
mod test_next_prev_commands;
mod test_op_revert_command;
mod test_operations;
mod test_parallelize_command;
mod test_rebase_command;
mod test_repo_change_report;
mod test_resolve_command;
mod test_restore_command;
mod test_revert_command;
mod test_revset_output;
mod test_root;
mod test_show_command;
mod test_sign_unsign_commands;
mod test_simplify_parents_command;
mod test_sparse_command;
mod test_split_command;
mod test_squash_command;
mod test_status_command;
mod test_tag_command;
mod test_templater;
mod test_undo_redo_commands;
mod test_util_command;
mod test_working_copy;
mod test_workspaces;
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_bisect_command.rs | cli/tests/test_bisect_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit;
use crate::common::fake_bisector_path;
#[test]
fn test_bisect_run_missing_command() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=.."]), @r"
------- stderr -------
Error: Command argument is required
[EOF]
[exit status: 2]
");
}
#[test]
fn test_bisect_run_empty_revset() {
let mut test_env = TestEnvironment::default();
let bisector_path = fake_bisector_path();
let bisection_script = test_env.set_up_fake_bisector();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
std::fs::write(&bisection_script, ["fail"].join("\0")).unwrap();
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=none()", &bisector_path]), @r"
Search complete. To discard any revisions created during search, run:
jj op restore 8f47435a3990
[EOF]
------- stderr -------
Error: Could not find the first bad revision. Was the input range empty?
[EOF]
[exit status: 1]
");
}
#[test]
fn test_bisect_run() {
let mut test_env = TestEnvironment::default();
let bisector_path = fake_bisector_path();
let bisection_script = test_env.set_up_fake_bisector();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["b"]);
create_commit(&work_dir, "d", &["c"]);
create_commit(&work_dir, "e", &["d"]);
create_commit(&work_dir, "f", &["e"]);
std::fs::write(&bisection_script, ["fail"].join("\0")).unwrap();
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=..", &bisector_path]), @r"
Now evaluating: royxmykx dffaa0d4 c | c
fake-bisector testing commit dffaa0d4daccf6cee70bac3498fae3b3fd5d6b5b
The revision is bad.
Now evaluating: rlvkpnrz 7d980be7 a | a
fake-bisector testing commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
The revision is bad.
Search complete. To discard any revisions created during search, run:
jj op restore 9152b6b19cce
The first bad revision is: rlvkpnrz 7d980be7 a | a
[EOF]
------- stderr -------
Working copy (@) now at: lylxulpl 68b3a16f (empty) (no description set)
Parent commit (@-) : royxmykx dffaa0d4 c | c
Added 0 files, modified 0 files, removed 3 files
Working copy (@) now at: rsllmpnm 5f328bc5 (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ rsllmpnmslon 5f328bc5fde0 '' files:
โ โ kmkuslswpqwq 8b67af288466 'f' files: f
โ โ znkkpsqqskkl 62d30ded0e8f 'e' files: e
โ โ vruxwmqvtpmx 86be7a223919 'd' files: d
โ โ royxmykxtrkr dffaa0d4dacc 'c' files: c
โ โ zsuskulnrvyr 123b4d91f6e5 'b' files: b
โโโฏ
โ rlvkpnrzqnoo 7d980be7a1d4 'a' files: a
โ zzzzzzzzzzzz 000000000000 '' files:
[EOF]
");
// Try with legacy command argument
std::fs::write(&bisection_script, ["fail"].join("\0")).unwrap();
// Testing only stderr to avoid a variable op id in the stdout.
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=..", "--command", &bisector_path]).success().stderr, @r"
Warning: `--command` is deprecated; use positional arguments instead: `jj bisect run --range=... -- $FAKE_BISECTOR_PATH`
Working copy (@) now at: nkmrtpmo 1601f7b4 (empty) (no description set)
Parent commit (@-) : royxmykx dffaa0d4 c | c
Added 2 files, modified 0 files, removed 0 files
Working copy (@) now at: ruktrxxu fb9e625c (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ ruktrxxusqqp fb9e625c1023 '' files:
โ โ kmkuslswpqwq 8b67af288466 'f' files: f
โ โ znkkpsqqskkl 62d30ded0e8f 'e' files: e
โ โ vruxwmqvtpmx 86be7a223919 'd' files: d
โ โ royxmykxtrkr dffaa0d4dacc 'c' files: c
โ โ zsuskulnrvyr 123b4d91f6e5 'b' files: b
โโโฏ
โ rlvkpnrzqnoo 7d980be7a1d4 'a' files: a
โ zzzzzzzzzzzz 000000000000 '' files:
[EOF]
");
}
#[test]
fn test_bisect_run_find_first_good() {
let mut test_env = TestEnvironment::default();
let bisector_path = fake_bisector_path();
test_env.set_up_fake_bisector();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["b"]);
create_commit(&work_dir, "d", &["c"]);
create_commit(&work_dir, "e", &["d"]);
create_commit(&work_dir, "f", &["e"]);
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=..", "--find-good", &bisector_path]), @r"
Now evaluating: royxmykx dffaa0d4 c | c
fake-bisector testing commit dffaa0d4daccf6cee70bac3498fae3b3fd5d6b5b
The revision is good.
Now evaluating: rlvkpnrz 7d980be7 a | a
fake-bisector testing commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
The revision is good.
Search complete. To discard any revisions created during search, run:
jj op restore 9152b6b19cce
The first good revision is: rlvkpnrz 7d980be7 a | a
[EOF]
------- stderr -------
Working copy (@) now at: lylxulpl 68b3a16f (empty) (no description set)
Parent commit (@-) : royxmykx dffaa0d4 c | c
Added 0 files, modified 0 files, removed 3 files
Working copy (@) now at: rsllmpnm 5f328bc5 (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ rsllmpnmslon 5f328bc5fde0 '' files:
โ โ kmkuslswpqwq 8b67af288466 'f' files: f
โ โ znkkpsqqskkl 62d30ded0e8f 'e' files: e
โ โ vruxwmqvtpmx 86be7a223919 'd' files: d
โ โ royxmykxtrkr dffaa0d4dacc 'c' files: c
โ โ zsuskulnrvyr 123b4d91f6e5 'b' files: b
โโโฏ
โ rlvkpnrzqnoo 7d980be7a1d4 'a' files: a
โ zzzzzzzzzzzz 000000000000 '' files:
[EOF]
");
}
#[test]
fn test_bisect_run_with_args() {
let mut test_env = TestEnvironment::default();
let bisector_path = fake_bisector_path();
test_env.set_up_fake_bisector();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["b"]);
create_commit(&work_dir, "d", &["c"]);
create_commit(&work_dir, "e", &["d"]);
create_commit(&work_dir, "f", &["e"]);
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=..", "--find-good", "--", &bisector_path, "--require-file=c"]), @r"
Now evaluating: royxmykx dffaa0d4 c | c
fake-bisector testing commit dffaa0d4daccf6cee70bac3498fae3b3fd5d6b5b
The revision is good.
Now evaluating: rlvkpnrz 7d980be7 a | a
fake-bisector testing commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
The revision is bad.
Now evaluating: zsuskuln 123b4d91 b | b
fake-bisector testing commit 123b4d91f6e5e39bfed39bae3bacf9380dc79078
The revision is bad.
Search complete. To discard any revisions created during search, run:
jj op restore 9152b6b19cce
The first good revision is: royxmykx dffaa0d4 c | c
[EOF]
------- stderr -------
Working copy (@) now at: lylxulpl 68b3a16f (empty) (no description set)
Parent commit (@-) : royxmykx dffaa0d4 c | c
Added 0 files, modified 0 files, removed 3 files
Working copy (@) now at: rsllmpnm 5f328bc5 (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Added 0 files, modified 0 files, removed 2 files
Working copy (@) now at: zqsquwqt 042badd2 (empty) (no description set)
Parent commit (@-) : zsuskuln 123b4d91 b | b
Added 1 files, modified 0 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zqsquwqtrvts 042badd28c1d '' files:
โ โ kmkuslswpqwq 8b67af288466 'f' files: f
โ โ znkkpsqqskkl 62d30ded0e8f 'e' files: e
โ โ vruxwmqvtpmx 86be7a223919 'd' files: d
โ โ royxmykxtrkr dffaa0d4dacc 'c' files: c
โโโฏ
โ zsuskulnrvyr 123b4d91f6e5 'b' files: b
โ rlvkpnrzqnoo 7d980be7a1d4 'a' files: a
โ zzzzzzzzzzzz 000000000000 '' files:
[EOF]
");
}
#[test]
fn test_bisect_run_abort() {
let mut test_env = TestEnvironment::default();
let bisector_path = fake_bisector_path();
let bisection_script = test_env.set_up_fake_bisector();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["b"]);
// stop immediately on failure
std::fs::write(&bisection_script, ["abort"].join("\0")).unwrap();
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=..", &bisector_path]), @r"
Now evaluating: rlvkpnrz 7d980be7 a | a
fake-bisector testing commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
[EOF]
------- stderr -------
Working copy (@) now at: vruxwmqv 538d9e7f (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Added 0 files, modified 0 files, removed 2 files
Error: Evaluation command returned 127 (command not found) - aborting bisection.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_bisect_run_skip() {
let mut test_env = TestEnvironment::default();
let bisector_path = fake_bisector_path();
let bisection_script = test_env.set_up_fake_bisector();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// head (b) is assumed to be bad, even though all revisions are skipped
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
std::fs::write(&bisection_script, ["skip"].join("\0")).unwrap();
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=..", &bisector_path]), @r"
Now evaluating: rlvkpnrz 7d980be7 a | a
fake-bisector testing commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
It could not be determined if the revision is good or bad.
Search complete. To discard any revisions created during search, run:
jj op restore 9cc40e5398a9
The first bad revision is: zsuskuln 123b4d91 b | b
[EOF]
------- stderr -------
Working copy (@) now at: royxmykx 2144134b (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
}
#[test]
fn test_bisect_run_multiple_results() {
let mut test_env = TestEnvironment::default();
let bisector_path = fake_bisector_path();
test_env.set_up_fake_bisector();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// heads (d and b) are assumed to be bad
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["a"]);
create_commit(&work_dir, "d", &["c"]);
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=a|b|c|d", &bisector_path]), @r"
Now evaluating: rlvkpnrz 7d980be7 a | a
fake-bisector testing commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
The revision is good.
Now evaluating: royxmykx 991a7501 c | c
fake-bisector testing commit 991a7501d660abb6a80e8b00f77c651d76d845d7
The revision is good.
Search complete. To discard any revisions created during search, run:
jj op restore d750de12e02a
The first bad revisions are:
vruxwmqv a2dbb1aa d | d
zsuskuln 123b4d91 b | b
[EOF]
------- stderr -------
Working copy (@) now at: znkkpsqq 1b117fe7 (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Added 0 files, modified 0 files, removed 2 files
Working copy (@) now at: uuzqqzqu 6bf5f5e7 (empty) (no description set)
Parent commit (@-) : royxmykx 991a7501 c | c
Added 1 files, modified 0 files, removed 0 files
[EOF]
");
}
#[test]
fn test_bisect_run_write_file() {
let mut test_env = TestEnvironment::default();
let bisector_path = fake_bisector_path();
let bisection_script = test_env.set_up_fake_bisector();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["b"]);
create_commit(&work_dir, "d", &["c"]);
create_commit(&work_dir, "e", &["d"]);
std::fs::write(
&bisection_script,
["write new-file\nsome contents", "fail"].join("\0"),
)
.unwrap();
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=..", &bisector_path]), @r"
Now evaluating: zsuskuln 123b4d91 b | b
fake-bisector testing commit 123b4d91f6e5e39bfed39bae3bacf9380dc79078
The revision is bad.
Now evaluating: rlvkpnrz 7d980be7 a | a
fake-bisector testing commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
The revision is bad.
Search complete. To discard any revisions created during search, run:
jj op restore 156d8a1abcb8
The first bad revision is: rlvkpnrz 7d980be7 a | a
[EOF]
------- stderr -------
Working copy (@) now at: kmkuslsw 17e2a972 (empty) (no description set)
Parent commit (@-) : zsuskuln 123b4d91 b | b
Added 0 files, modified 0 files, removed 3 files
Working copy (@) now at: msksykpx 2f6e298d (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ msksykpxotkr 891aeb03b623 '' files: new-file
โ โ kmkuslswpqwq 2bae881dc1bc '' files: new-file
โ โ โ znkkpsqqskkl 62d30ded0e8f 'e' files: e
โ โ โ vruxwmqvtpmx 86be7a223919 'd' files: d
โ โ โ royxmykxtrkr dffaa0d4dacc 'c' files: c
โ โโโฏ
โ โ zsuskulnrvyr 123b4d91f6e5 'b' files: b
โโโฏ
โ rlvkpnrzqnoo 7d980be7a1d4 'a' files: a
โ zzzzzzzzzzzz 000000000000 '' files:
[EOF]
");
// No concurrent operations
let output = work_dir.run_jj(["op", "log", "-n=5", "-T=description"]);
insta::assert_snapshot!(output, @r"
@ snapshot working copy
โ Updated to revision 7d980be7a1d499e4d316ab4c01242885032f7eaf for bisection
โ snapshot working copy
โ Updated to revision 123b4d91f6e5e39bfed39bae3bacf9380dc79078 for bisection
โ create bookmark e pointing to commit 62d30ded0e8fdf8cf87012e6223898b97977fc8e
[EOF]
");
}
#[test]
fn test_bisect_run_jj_command() {
let mut test_env = TestEnvironment::default();
let bisector_path = fake_bisector_path();
let bisection_script = test_env.set_up_fake_bisector();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["b"]);
create_commit(&work_dir, "d", &["c"]);
create_commit(&work_dir, "e", &["d"]);
std::fs::write(&bisection_script, ["jj new -mtesting", "fail"].join("\0")).unwrap();
insta::assert_snapshot!(work_dir.run_jj(["bisect", "run", "--range=..", &bisector_path]), @r"
Now evaluating: zsuskuln 123b4d91 b | b
fake-bisector testing commit 123b4d91f6e5e39bfed39bae3bacf9380dc79078
The revision is bad.
Now evaluating: rlvkpnrz 7d980be7 a | a
fake-bisector testing commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
The revision is bad.
Search complete. To discard any revisions created during search, run:
jj op restore 156d8a1abcb8
The first bad revision is: rlvkpnrz 7d980be7 a | a
[EOF]
------- stderr -------
Working copy (@) now at: kmkuslsw 17e2a972 (empty) (no description set)
Parent commit (@-) : zsuskuln 123b4d91 b | b
Added 0 files, modified 0 files, removed 3 files
Working copy (@) now at: kmkuslsw/0 55b3b4a8 (divergent) (empty) testing
Parent commit (@-) : kmkuslsw/1 17e2a972 (divergent) (empty) (no description set)
Working copy (@) now at: msksykpx 2f6e298d (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Added 0 files, modified 0 files, removed 1 files
Working copy (@) now at: kmkuslsw/0 2f80658c (divergent) (empty) testing
Parent commit (@-) : msksykpx 2f6e298d (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ kmkuslswpqwq 2f80658c4d26 'testing' files:
โ msksykpxotkr 2f6e298d59bd '' files:
โ โ kmkuslswpqwq 55b3b4a8b253 'testing' files:
โ โ kmkuslswpqwq 17e2a9721f61 '' files:
โ โ โ znkkpsqqskkl 62d30ded0e8f 'e' files: e
โ โ โ vruxwmqvtpmx 86be7a223919 'd' files: d
โ โ โ royxmykxtrkr dffaa0d4dacc 'c' files: c
โ โโโฏ
โ โ zsuskulnrvyr 123b4d91f6e5 'b' files: b
โโโฏ
โ rlvkpnrzqnoo 7d980be7a1d4 'a' files: a
โ zzzzzzzzzzzz 000000000000 '' files:
[EOF]
");
// No concurrent operations
let output = work_dir.run_jj(["op", "log", "-n=5", "-T=description"]);
insta::assert_snapshot!(output, @r"
@ new empty commit
โ Updated to revision 7d980be7a1d499e4d316ab4c01242885032f7eaf for bisection
โ new empty commit
โ Updated to revision 123b4d91f6e5e39bfed39bae3bacf9380dc79078 for bisection
โ create bookmark e pointing to commit 62d30ded0e8fdf8cf87012e6223898b97977fc8e
[EOF]
");
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"separate(" ",
change_id.short(),
commit_id.short(),
"'" ++ description.first_line() ++ "'",
"files: " ++ diff.files().map(|e| e.path())
)"#;
work_dir.run_jj(["log", "-T", template])
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_config_command.rs | cli/tests/test_config_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::env::join_paths;
use std::path::PathBuf;
use indoc::indoc;
use itertools::Itertools as _;
use regex::Regex;
use crate::common::TestEnvironment;
use crate::common::default_config_from_schema;
use crate::common::fake_editor_path;
use crate::common::force_interactive;
use crate::common::to_toml_value;
#[test]
fn test_config_list_single() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[test-table]
somekey = "some value"
"#,
);
let output = test_env.run_jj_in(".", ["config", "list", "test-table.somekey"]);
insta::assert_snapshot!(output, @r#"
test-table.somekey = "some value"
[EOF]
"#);
let output = test_env.run_jj_in(
".",
["config", "list", r#"-Tname ++ "\n""#, "test-table.somekey"],
);
insta::assert_snapshot!(output, @r"
test-table.somekey
[EOF]
");
}
#[test]
fn test_config_list_nonexistent() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["config", "list", "nonexistent-test-key"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching config key for nonexistent-test-key
[EOF]
");
let output = test_env.run_jj_in(".", ["config", "list", "--repo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No config to list
[EOF]
");
}
#[test]
fn test_config_list_table() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[test-table]
x = true
y.foo = "abc"
y.bar = 123
"z"."with space"."function()" = 5
"#,
);
let output = test_env.run_jj_in(".", ["config", "list", "test-table"]);
insta::assert_snapshot!(output, @r#"
test-table.x = true
test-table.y.foo = "abc"
test-table.y.bar = 123
test-table.z."with space"."function()" = 5
[EOF]
"#);
}
#[test]
fn test_config_list_inline_table() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
test-table = { x = true, y = 1 }
"#,
);
// Inline tables are expanded
let output = test_env.run_jj_in(".", ["config", "list", "test-table"]);
insta::assert_snapshot!(output, @r"
test-table.x = true
test-table.y = 1
[EOF]
");
// Inner value can also be addressed by a dotted name path
let output = test_env.run_jj_in(".", ["config", "list", "test-table.x"]);
insta::assert_snapshot!(output, @r"
test-table.x = true
[EOF]
");
}
#[test]
fn test_config_list_array() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
test-array = [1, "b", 3.4]
"#,
);
let output = test_env.run_jj_in(".", ["config", "list", "test-array"]);
insta::assert_snapshot!(output, @r#"
test-array = [1, "b", 3.4]
[EOF]
"#);
}
#[test]
fn test_config_list_array_of_tables() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[[test-table]]
x = 1
[[test-table]]
y = ["z"]
z."key=with whitespace" = []
"#,
);
// Array is a value, so is array of tables
let output = test_env.run_jj_in(".", ["config", "list", "test-table"]);
insta::assert_snapshot!(output, @r#"
test-table = [{ x = 1 }, { y = ["z"], z = { "key=with whitespace" = [] } }]
[EOF]
"#);
}
#[test]
fn test_config_list_all() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
test-val = [1, 2, 3]
[test-table]
x = true
y.foo = "abc"
y.bar = 123
"#,
);
let output = test_env.run_jj_in(".", ["config", "list"]);
insta::assert_snapshot!(
output.normalize_stdout_with(|s| find_stdout_lines(r"(test-val|test-table\b[^=]*)", &s)), @r#"
test-val = [1, 2, 3]
test-table.x = true
test-table.y.foo = "abc"
test-table.y.bar = 123
[EOF]
"#);
}
#[test]
fn test_config_list_multiline_string() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
multiline = '''
foo
bar
'''
"#,
);
let output = test_env.run_jj_in(".", ["config", "list", "multiline"]);
insta::assert_snapshot!(output, @r"
multiline = '''
foo
bar
'''
[EOF]
");
let output = test_env.run_jj_in(
".",
[
"config",
"list",
"multiline",
"--include-overridden",
"--config=multiline='single'",
],
);
insta::assert_snapshot!(output, @r"
# multiline = '''
# foo
# bar
# '''
multiline = 'single'
[EOF]
");
}
#[test]
fn test_config_list_layer() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
// Test with fresh new config file
let user_config_path = test_env.config_path().join("config.toml");
test_env.set_config_path(&user_config_path);
let work_dir = test_env.work_dir("repo");
// User
work_dir
.run_jj(["config", "set", "--user", "test-key", "test-val"])
.success();
work_dir
.run_jj([
"config",
"set",
"--user",
"test-layered-key",
"test-original-val",
])
.success();
let output = work_dir.run_jj(["config", "list", "--user"]);
insta::assert_snapshot!(output, @r#"
test-key = "test-val"
test-layered-key = "test-original-val"
[EOF]
"#);
// Repo
work_dir
.run_jj([
"config",
"set",
"--repo",
"test-layered-key",
"test-layered-val",
])
.success();
let output = work_dir.run_jj(["config", "list", "--user"]);
insta::assert_snapshot!(output, @r#"
test-key = "test-val"
[EOF]
"#);
let output = work_dir.run_jj(["config", "list", "--repo"]);
insta::assert_snapshot!(output, @r#"
test-layered-key = "test-layered-val"
[EOF]
"#);
// Workspace (new scope takes precedence over repo)
// Add a workspace-level setting
work_dir
.run_jj([
"config",
"set",
"--workspace",
"test-layered-wks-key",
"ws-val",
])
.success();
// Listing user shouldn't include workspace
let output = work_dir.run_jj(["config", "list", "--user"]);
insta::assert_snapshot!(output, @r#"
test-key = "test-val"
[EOF]
"#);
// Workspace
let output = work_dir.run_jj(["config", "list", "--workspace"]);
insta::assert_snapshot!(output, @r#"
test-layered-wks-key = "ws-val"
[EOF]
"#);
}
#[test]
fn test_config_list_origin() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
// Test with fresh new config file
let user_config_path = test_env.config_path().join("config.toml");
test_env.set_config_path(&user_config_path);
let work_dir = test_env.work_dir("repo");
// User
work_dir
.run_jj(["config", "set", "--user", "test-key", "test-val"])
.success();
work_dir
.run_jj([
"config",
"set",
"--user",
"test-layered-key",
"test-original-val",
])
.success();
// Repo
work_dir
.run_jj([
"config",
"set",
"--repo",
"test-layered-key",
"test-layered-val",
])
.success();
let output = work_dir.run_jj([
"config",
"list",
"-Tbuiltin_config_list_detailed",
"--config",
"test-cli-key=test-cli-val",
]);
insta::assert_snapshot!(output, @r#"
test-key = "test-val" # user $TEST_ENV/config/config.toml
test-layered-key = "test-layered-val" # repo $TEST_ENV/repo/.jj/repo/config.toml
user.name = "Test User" # env
user.email = "test.user@example.com" # env
debug.commit-timestamp = "2001-02-03T04:05:11+07:00" # env
debug.randomness-seed = 5 # env
debug.operation-timestamp = "2001-02-03T04:05:11+07:00" # env
operation.hostname = "host.example.com" # env
operation.username = "test-username" # env
test-cli-key = "test-cli-val" # cli
[EOF]
"#);
let output = work_dir.run_jj([
"config",
"list",
"-Tbuiltin_config_list_detailed",
"--color=debug",
"--include-defaults",
"--include-overridden",
"--config=test-key=test-cli-val",
"test-key",
]);
insta::assert_snapshot!(output, @r#"
[38;5;8m<<config_list overridden name::# test-key>><<config_list overridden:: = >><<config_list overridden value::"test-val">><<config_list overridden:: # >><<config_list overridden source::user>><<config_list overridden:: >><<config_list overridden path::$TEST_ENV/config/config.toml>><<config_list overridden::>>[39m
[38;5;2m<<config_list name::test-key>>[39m<<config_list:: = >>[38;5;3m<<config_list value::"test-cli-val">>[39m<<config_list:: # >>[38;5;4m<<config_list source::cli>>[39m<<config_list::>>
[EOF]
"#);
let output = work_dir.run_jj([
"config",
"list",
r#"-Tjson(self) ++ "\n""#,
"--include-defaults",
"--include-overridden",
"--config=test-key=test-cli-val",
"test-key",
]);
insta::with_settings!({
// Windows paths will be escaped in JSON syntax, which cannot be
// normalized as $TEST_ENV.
filters => [(r#""path":"[^"]*","#, r#""path":"<redacted>","#)],
}, {
insta::assert_snapshot!(output, @r#"
{"name":"test-key","value":"test-val","source":"user","path":"<redacted>","is_overridden":true}
{"name":"test-key","value":"test-cli-val","source":"cli","path":null,"is_overridden":false}
[EOF]
"#);
});
}
#[test]
fn test_config_layer_override_default() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let config_key = "merge-tools.vimdiff.program";
// Default
let output = work_dir.run_jj(["config", "list", config_key, "--include-defaults"]);
insta::assert_snapshot!(output, @r#"
merge-tools.vimdiff.program = "vim"
[EOF]
"#);
// User
test_env.add_config(format!(
"{config_key} = {value}\n",
value = to_toml_value("user")
));
let output = work_dir.run_jj(["config", "list", config_key]);
insta::assert_snapshot!(output, @r#"
merge-tools.vimdiff.program = "user"
[EOF]
"#);
// Repo
work_dir.write_file(
".jj/repo/config.toml",
format!("{config_key} = {value}\n", value = to_toml_value("repo")),
);
let output = work_dir.run_jj(["config", "list", config_key]);
insta::assert_snapshot!(output, @r#"
merge-tools.vimdiff.program = "repo"
[EOF]
"#);
// Command argument
let output = work_dir.run_jj([
"config",
"list",
config_key,
"--config",
&format!("{config_key}={value}", value = to_toml_value("command-arg")),
]);
insta::assert_snapshot!(output, @r#"
merge-tools.vimdiff.program = "command-arg"
[EOF]
"#);
// Allow printing overridden values
let output = work_dir.run_jj([
"config",
"list",
config_key,
"--include-overridden",
"--config",
&format!("{config_key}={value}", value = to_toml_value("command-arg")),
]);
insta::assert_snapshot!(output, @r#"
# merge-tools.vimdiff.program = "user"
# merge-tools.vimdiff.program = "repo"
merge-tools.vimdiff.program = "command-arg"
[EOF]
"#);
let output = work_dir.run_jj([
"config",
"list",
"--color=always",
config_key,
"--include-overridden",
]);
insta::assert_snapshot!(output, @r#"
[38;5;8m# merge-tools.vimdiff.program = "user"[39m
[38;5;2mmerge-tools.vimdiff.program[39m = [38;5;3m"repo"[39m
[EOF]
"#);
}
#[test]
fn test_config_layer_override_env() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let config_key = "ui.editor";
// Environment base
test_env.add_env_var("EDITOR", "env-base");
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["config", "list", config_key]);
insta::assert_snapshot!(output, @r#"
ui.editor = "env-base"
[EOF]
"#);
// User
test_env.add_config(format!(
"{config_key} = {value}\n",
value = to_toml_value("user")
));
let output = work_dir.run_jj(["config", "list", config_key]);
insta::assert_snapshot!(output, @r#"
ui.editor = "user"
[EOF]
"#);
// Repo
work_dir.write_file(
".jj/repo/config.toml",
format!("{config_key} = {value}\n", value = to_toml_value("repo")),
);
let output = work_dir.run_jj(["config", "list", config_key]);
insta::assert_snapshot!(output, @r#"
ui.editor = "repo"
[EOF]
"#);
// Environment override
test_env.add_env_var("JJ_EDITOR", "env-override");
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["config", "list", config_key]);
insta::assert_snapshot!(output, @r#"
ui.editor = "env-override"
[EOF]
"#);
// Command argument
let output = work_dir.run_jj([
"config",
"list",
config_key,
"--config",
&format!("{config_key}={value}", value = to_toml_value("command-arg")),
]);
insta::assert_snapshot!(output, @r#"
ui.editor = "command-arg"
[EOF]
"#);
// Allow printing overridden values
let output = work_dir.run_jj([
"config",
"list",
config_key,
"--include-overridden",
"--config",
&format!("{config_key}={value}", value = to_toml_value("command-arg")),
]);
insta::assert_snapshot!(output, @r#"
# ui.editor = "env-base"
# ui.editor = "user"
# ui.editor = "repo"
# ui.editor = "env-override"
ui.editor = "command-arg"
[EOF]
"#);
}
#[test]
fn test_config_layer_workspace() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "main"]).success();
let main_dir = test_env.work_dir("main");
let secondary_dir = test_env.work_dir("secondary");
let config_key = "ui.editor";
main_dir.write_file("file", "contents");
main_dir.run_jj(["new"]).success();
main_dir
.run_jj(["workspace", "add", "--name", "second", "../secondary"])
.success();
// Repo
main_dir.write_file(
".jj/repo/config.toml",
format!(
"{config_key} = {value}\n",
value = to_toml_value("main-repo")
),
);
let output = main_dir.run_jj(["config", "list", config_key]);
insta::assert_snapshot!(output, @r#"
ui.editor = "main-repo"
[EOF]
"#);
let output = secondary_dir.run_jj(["config", "list", config_key]);
insta::assert_snapshot!(output, @r#"
ui.editor = "main-repo"
[EOF]
"#);
}
#[test]
fn test_config_set_bad_opts() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["config", "set"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the following required arguments were not provided:
<--user|--repo|--workspace>
<NAME>
<VALUE>
Usage: jj config set <--user|--repo|--workspace> <NAME> <VALUE>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
let output = test_env.run_jj_in(".", ["config", "set", "--user", "", "x"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value '' for '<NAME>': TOML parse error at line 1, column 1
|
1 |
| ^
unquoted keys cannot be empty, expected letters, numbers, `-`, `_`
For more information, try '--help'.
[EOF]
[exit status: 2]
");
let output = test_env.run_jj_in(".", ["config", "set", "--user", "x", "['typo'}"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value '['typo'}' for '<VALUE>': TOML parse error at line 1, column 8
|
1 | ['typo'}
| ^
missing comma between array elements, expected `,`
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_config_set_for_user() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
// Test with fresh new config file
let user_config_path = test_env.config_path().join("config.toml");
test_env.set_config_path(&user_config_path);
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["config", "set", "--user", "test-key", "test-val"])
.success();
work_dir
.run_jj(["config", "set", "--user", "test-table.foo", "true"])
.success();
work_dir
.run_jj(["config", "set", "--user", "test-table.'bar()'", "0"])
.success();
// Ensure test-key successfully written to user config.
let user_config_toml = std::fs::read_to_string(&user_config_path)
.unwrap_or_else(|_| panic!("Failed to read file {}", user_config_path.display()));
insta::assert_snapshot!(user_config_toml, @r#"
#:schema https://docs.jj-vcs.dev/latest/config-schema.json
test-key = "test-val"
[test-table]
foo = true
'bar()' = 0
"#);
}
#[test]
fn test_config_set_for_user_directory() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["config", "set", "--user", "test-key", "test-val"])
.success();
insta::assert_snapshot!(
std::fs::read_to_string(test_env.last_config_file_path()).unwrap(),
@r#"
test-key = "test-val"
[template-aliases]
'format_time_range(time_range)' = 'time_range.start() ++ " - " ++ time_range.end()'
[git]
colocate = false
"#);
// Add one more config file to the directory
test_env.add_config("");
let output = test_env.run_jj_in(
".",
["config", "set", "--user", "test-key", "test-other-val"],
);
insta::assert_snapshot!(output, @r"
------- stderr -------
1: $TEST_ENV/config/config0001.toml
2: $TEST_ENV/config/config0002.toml
Choose a config file (default 1): 1
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.first_config_file_path()).unwrap(),
@r#"
test-key = "test-other-val"
[template-aliases]
'format_time_range(time_range)' = 'time_range.start() ++ " - " ++ time_range.end()'
[git]
colocate = false
"#);
insta::assert_snapshot!(
std::fs::read_to_string(test_env.last_config_file_path()).unwrap(),
@"");
}
#[test]
fn test_config_set_for_repo() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["config", "set", "--repo", "test-key", "test-val"])
.success();
work_dir
.run_jj(["config", "set", "--repo", "test-table.foo", "true"])
.success();
// Ensure test-key successfully written to user config.
let repo_config_toml = work_dir.read_file(".jj/repo/config.toml");
insta::assert_snapshot!(repo_config_toml, @r#"
#:schema https://docs.jj-vcs.dev/latest/config-schema.json
test-key = "test-val"
[test-table]
foo = true
"#);
}
#[test]
fn test_config_set_for_workspace() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["workspace", "add", "--name", "second", "../secondary"])
.success();
let work_dir = test_env.work_dir("secondary");
// set in workspace
work_dir
.run_jj(["config", "set", "--workspace", "test-key", "ws-val"])
.success();
// Read workspace config
let workspace_config = work_dir.read_file(".jj/workspace-config.toml");
insta::assert_snapshot!(workspace_config, @r#"
#:schema https://docs.jj-vcs.dev/latest/config-schema.json
test-key = "ws-val"
"#);
}
#[test]
fn test_config_set_toml_types() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
// Test with fresh new config file
let user_config_path = test_env.config_path().join("config.toml");
test_env.set_config_path(&user_config_path);
let work_dir = test_env.work_dir("repo");
let set_value = |key, value| {
work_dir
.run_jj(["config", "set", "--user", key, value])
.success();
};
set_value("test-table.integer", "42");
set_value("test-table.float", "3.14");
set_value("test-table.array", r#"["one", "two"]"#);
set_value("test-table.boolean", "true");
set_value("test-table.string", r#""foo""#);
set_value("test-table.invalid", r"a + b");
insta::assert_snapshot!(std::fs::read_to_string(&user_config_path).unwrap(), @r#"
#:schema https://docs.jj-vcs.dev/latest/config-schema.json
[test-table]
integer = 42
float = 3.14
array = ["one", "two"]
boolean = true
string = "foo"
invalid = "a + b"
"#);
}
#[test]
fn test_config_set_type_mismatch() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["config", "set", "--user", "test-table.foo", "test-val"])
.success();
let output = work_dir.run_jj(["config", "set", "--user", "test-table", "not-a-table"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to set test-table
Caused by: Would overwrite entire table test-table
[EOF]
[exit status: 1]
");
// But it's fine to overwrite arrays and inline tables
work_dir
.run_jj(["config", "set", "--user", "test-table.array", "[1,2,3]"])
.success();
work_dir
.run_jj(["config", "set", "--user", "test-table.array", "[4,5,6]"])
.success();
work_dir
.run_jj(["config", "set", "--user", "test-table.inline", "{ x = 42}"])
.success();
work_dir
.run_jj(["config", "set", "--user", "test-table.inline", "42"])
.success();
}
#[test]
fn test_config_set_nontable_parent() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["config", "set", "--user", "test-nontable", "test-val"])
.success();
let output = work_dir.run_jj(["config", "set", "--user", "test-nontable.foo", "test-val"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to set test-nontable.foo
Caused by: Would overwrite non-table value with parent table test-nontable
[EOF]
[exit status: 1]
");
}
#[test]
fn test_config_unset_non_existent_key() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["config", "unset", "--user", "nonexistent"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: "nonexistent" doesn't exist
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_config_unset_inline_table_key() {
let mut test_env = TestEnvironment::default();
// Test with fresh new config file
let user_config_path = test_env.config_path().join("config.toml");
test_env.set_config_path(&user_config_path);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["config", "set", "--user", "inline-table", "{ foo = true }"])
.success();
work_dir
.run_jj(["config", "unset", "--user", "inline-table.foo"])
.success();
let user_config_toml = std::fs::read_to_string(&user_config_path).unwrap();
insta::assert_snapshot!(user_config_toml, @r"
#:schema https://docs.jj-vcs.dev/latest/config-schema.json
inline-table = {}
");
}
#[test]
fn test_config_unset_table_like() {
let mut test_env = TestEnvironment::default();
// Test with fresh new config file
let user_config_path = test_env.config_path().join("config.toml");
test_env.set_config_path(&user_config_path);
std::fs::write(
&user_config_path,
indoc! {b"
inline-table = { foo = true }
[non-inline-table]
foo = true
"},
)
.unwrap();
// Inline table is syntactically a "value", so it can be deleted.
test_env
.run_jj_in(".", ["config", "unset", "--user", "inline-table"])
.success();
// Non-inline table cannot be deleted.
let output = test_env.run_jj_in(".", ["config", "unset", "--user", "non-inline-table"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to unset non-inline-table
Caused by: Would delete entire table non-inline-table
[EOF]
[exit status: 1]
");
let user_config_toml = std::fs::read_to_string(&user_config_path).unwrap();
insta::assert_snapshot!(user_config_toml, @r"
[non-inline-table]
foo = true
");
}
#[test]
fn test_config_unset_for_user() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
// Test with fresh new config file
let user_config_path = test_env.config_path().join("config.toml");
test_env.set_config_path(&user_config_path);
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["config", "set", "--user", "foo", "true"])
.success();
work_dir
.run_jj(["config", "unset", "--user", "foo"])
.success();
work_dir
.run_jj(["config", "set", "--user", "table.foo", "true"])
.success();
work_dir
.run_jj(["config", "unset", "--user", "table.foo"])
.success();
work_dir
.run_jj(["config", "set", "--user", "table.inline", "{ foo = true }"])
.success();
work_dir
.run_jj(["config", "unset", "--user", "table.inline"])
.success();
let user_config_toml = std::fs::read_to_string(&user_config_path).unwrap();
insta::assert_snapshot!(user_config_toml, @"[table]");
}
#[test]
fn test_config_unset_for_repo() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["config", "set", "--repo", "test-key", "test-val"])
.success();
work_dir
.run_jj(["config", "unset", "--repo", "test-key"])
.success();
let repo_config_toml = work_dir.read_file(".jj/repo/config.toml");
insta::assert_snapshot!(repo_config_toml, @"");
}
#[test]
fn test_config_unset_for_workspace() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["workspace", "add", "--name", "second", "../secondary"])
.success();
let work_dir = test_env.work_dir("secondary");
// set then unset
work_dir
.run_jj(["config", "set", "--workspace", "foo", "bar"])
.success();
work_dir
.run_jj(["config", "unset", "--workspace", "foo"])
.success();
let workspace_config = work_dir.read_file(".jj/workspace-config.toml");
insta::assert_snapshot!(workspace_config, @"");
}
#[test]
fn test_config_edit_missing_opt() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["config", "edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the following required arguments were not provided:
<--user|--repo|--workspace>
Usage: jj config edit <--user|--repo|--workspace>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_config_edit_user() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
// Remove one of the config file to disambiguate
std::fs::remove_file(test_env.last_config_file_path()).unwrap();
let edit_script = test_env.set_up_fake_editor();
let work_dir = test_env.work_dir("repo");
std::fs::write(edit_script, "dump-path path").unwrap();
work_dir.run_jj(["config", "edit", "--user"]).success();
let edited_path =
PathBuf::from(std::fs::read_to_string(test_env.env_root().join("path")).unwrap());
assert_eq!(
edited_path,
dunce::simplified(&test_env.last_config_file_path())
);
}
#[test]
fn test_config_edit_user_new_file() {
let mut test_env = TestEnvironment::default();
let user_config_path = test_env.config_path().join("config").join("file.toml");
test_env.set_up_fake_editor(); // set $EDIT_SCRIPT, but added configuration is ignored
test_env.add_env_var("EDITOR", fake_editor_path());
test_env.set_config_path(&user_config_path);
assert!(!user_config_path.exists());
test_env
.run_jj_in(".", ["config", "edit", "--user"])
.success();
assert!(
user_config_path.exists(),
"new file and directory should be created"
);
}
#[test]
fn test_config_edit_repo() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let repo_config_path = work_dir
.root()
.join(PathBuf::from_iter([".jj", "repo", "config.toml"]));
assert!(!repo_config_path.exists());
std::fs::write(edit_script, "dump-path path").unwrap();
work_dir.run_jj(["config", "edit", "--repo"]).success();
let edited_path =
PathBuf::from(std::fs::read_to_string(test_env.env_root().join("path")).unwrap());
assert_eq!(edited_path, dunce::simplified(&repo_config_path));
assert!(repo_config_path.exists(), "new file should be created");
}
#[test]
fn test_config_edit_invalid_config() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
// Test re-edit
std::fs::write(
&edit_script,
"write\ninvalid config here\0next invocation\n\0write\ntest=\"success\"",
)
.unwrap();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj_with(|cmd| {
force_interactive(cmd)
.args(["config", "edit", "--repo"])
.write_stdin("Y\n")
});
insta::assert_snapshot!(output, @r"
------- stderr -------
Editing file: $TEST_ENV/repo/.jj/repo/config.toml
Warning: An error has been found inside the config:
Caused by:
1: Configuration cannot be parsed as TOML document
2: TOML parse error at line 1, column 9
|
1 | invalid config here
| ^
key with no value, expected `=`
Do you want to keep editing the file? If not, previous config will be restored. (Yn): [EOF]
");
let output = work_dir.run_jj(["config", "get", "test"]);
insta::assert_snapshot!(output, @r"
success
[EOF]
"
);
// Test the restore previous config
std::fs::write(&edit_script, "write\ninvalid config here").unwrap();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj_with(|cmd| {
force_interactive(cmd)
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/datatest_runner.rs | cli/tests/datatest_runner.rs | mod datatest_config_schema;
datatest_stable::harness! {
{
test = datatest_config_schema::check_config_file_valid,
root = "src/config",
pattern = r".*\.toml",
},
{
test = datatest_config_schema::check_config_file_valid,
root = "tests/sample-configs/valid",
pattern = r".*\.toml",
},
{
test = datatest_config_schema::check_config_file_invalid,
root = "tests/sample-configs/invalid",
pattern = r".*\.toml",
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_commit_command.rs | cli/tests/test_commit_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::PathBuf;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_commit_with_description_from_cli() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Description applies to the current working-copy (not the new one)
work_dir.run_jj(["commit", "-m=first"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ eb9fd2ab82e7
โ 68a505386f93 first
โ 000000000000
[EOF]
");
}
#[test]
fn test_commit_with_editor() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
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
work_dir.run_jj(["describe", "-m=initial"]).success();
std::fs::write(&edit_script, ["dump editor0", "write\nmodified"].join("\0")).unwrap();
work_dir.run_jj(["commit"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 2094c8f2e360
โ a7ba1eb73836 modified
โ 000000000000
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor0")).unwrap(), @r#"
initial
JJ: Change ID: qpvuntsm
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
// Check that the editor content includes diff summary
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "foo\n");
work_dir.run_jj(["describe", "-m=add files"]).success();
std::fs::write(&edit_script, "dump editor1").unwrap();
work_dir.run_jj(["commit"]).success();
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor1")).unwrap(), @r#"
add files
JJ: Change ID: kkmpptxz
JJ: This commit contains the following changes:
JJ: A file1
JJ: A file2
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
}
#[test]
fn test_commit_with_editor_avoids_unc() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
std::fs::write(edit_script, "dump-path path").unwrap();
work_dir.run_jj(["commit"]).success();
let edited_path =
PathBuf::from(std::fs::read_to_string(test_env.env_root().join("path")).unwrap());
// While `assert!(!edited_path.starts_with("//?/"))` could work here in most
// cases, it fails when it is not safe to strip the prefix, such as paths
// over 260 chars.
assert_eq!(edited_path, dunce::simplified(&edited_path));
}
#[test]
fn test_commit_with_empty_description_from_cli() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["commit", "-m="]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 51b556e22ca0
โ cc8ff2284a8c
โ 000000000000
[EOF]
");
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: rlvkpnrz 51b556e2 (empty) (no description set)
Parent commit (@-) : qpvuntsm cc8ff228 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_commit_with_empty_description_from_editor() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Check that the text file gets initialized and leave it untouched.
std::fs::write(&edit_script, ["dump editor0"].join("\0")).unwrap();
let output = work_dir.run_jj(["commit"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 51b556e22ca0
โ cc8ff2284a8c
โ 000000000000
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor0")).unwrap(),
@r#"
JJ: Change ID: qpvuntsm
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
insta::assert_snapshot!(output, @r"
------- stderr -------
Hint: The commit message was left empty.
If this was not intentional, run `jj undo` to restore the previous state.
Or run `jj desc @-` to add a description to the parent commit.
Working copy (@) now at: rlvkpnrz 51b556e2 (empty) (no description set)
Parent commit (@-) : qpvuntsm cc8ff228 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_commit_interactive() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
let diff_editor = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
work_dir.run_jj(["describe", "-m=add files"]).success();
std::fs::write(edit_script, ["dump editor"].join("\0")).unwrap();
let diff_script = ["rm file2", "dump JJ-INSTRUCTIONS instrs"].join("\0");
std::fs::write(diff_editor, diff_script).unwrap();
let setup_opid = work_dir.current_operation_id();
// Create a commit interactively and select only file1
work_dir.run_jj(["commit", "-i"]).success();
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("instrs")).unwrap(), @r"
You are splitting the working-copy commit: qpvuntsm d849dc34 add files
The diff initially shows all changes. Adjust the right side until it shows the
contents you want for the first commit. The remainder will be included in the
new working-copy commit.
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
add files
JJ: Change ID: qpvuntsm
JJ: This commit contains the following changes:
JJ: A file1
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
// Try again with --tool=<name>, which implies --interactive
work_dir.run_jj(["op", "restore", &setup_opid]).success();
work_dir
.run_jj([
"commit",
"--config=ui.diff-editor='false'",
"--tool=fake-diff-editor",
])
.success();
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
add files
JJ: Change ID: qpvuntsm
JJ: This commit contains the following changes:
JJ: A file1
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
let output = work_dir.run_jj(["log", "--summary"]);
insta::assert_snapshot!(output, @r"
@ mzvwutvl test.user@example.com 2001-02-03 08:05:11 9b0176ab
โ (no description set)
โ A file2
โ qpvuntsm test.user@example.com 2001-02-03 08:05:11 6e6fa925
โ add files
โ A file1
โ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_commit_interactive_with_paths() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
let diff_editor = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file2", "");
work_dir.write_file("file3", "");
work_dir.run_jj(["new", "-medit"]).success();
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
work_dir.write_file("file3", "baz\n");
std::fs::write(edit_script, ["dump editor"].join("\0")).unwrap();
let diff_script = [
"files-before file2",
"files-after JJ-INSTRUCTIONS file1 file2",
"reset file2",
]
.join("\0");
std::fs::write(diff_editor, diff_script).unwrap();
// Select file1 and file2 by args, then select file1 interactively
let output = work_dir.run_jj(["commit", "-i", "file1", "file2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 50f426df (no description set)
Parent commit (@-) : rlvkpnrz eb640375 edit
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
edit
JJ: Change ID: rlvkpnrz
JJ: This commit contains the following changes:
JJ: A file1
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
let output = work_dir.run_jj(["log", "--summary"]);
insta::assert_snapshot!(output, @r"
@ kkmpptxz test.user@example.com 2001-02-03 08:05:09 50f426df
โ (no description set)
โ M file2
โ M file3
โ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 eb640375
โ edit
โ A file1
โ qpvuntsm test.user@example.com 2001-02-03 08:05:08 ff687a2f
โ (no description set)
โ A file2
โ A file3
โ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_commit_with_default_description() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
test_env.add_config(r#"template-aliases.default_commit_description = '"\n\nTESTED=TODO\n"'"#);
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
std::fs::write(edit_script, ["dump editor"].join("\0")).unwrap();
work_dir.run_jj(["commit"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ cba559ac1a48
โ 7276dfff8027 TESTED=TODO
โ 000000000000
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
TESTED=TODO
JJ: Change ID: qpvuntsm
JJ: This commit contains the following changes:
JJ: A file1
JJ: A file2
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
}
#[test]
fn test_commit_with_description_template() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
test_env.add_config(
r#"
[templates]
draft_commit_description = '''
concat(
description,
"\n",
indent(
"JJ: ",
concat(
"Author: " ++ format_detailed_signature(author) ++ "\n",
"Committer: " ++ format_detailed_signature(committer) ++ "\n",
"\n",
diff.stat(76),
),
),
)
'''
"#,
);
let work_dir = test_env.work_dir("repo");
std::fs::write(edit_script, ["dump editor"].join("\0")).unwrap();
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
work_dir.write_file("file3", "foobar\n");
// Only file1 should be included in the diff
work_dir.run_jj(["commit", "file1"]).success();
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
JJ: Author: Test User <test.user@example.com> (2001-02-03 08:05:08)
JJ: Committer: Test User <test.user@example.com> (2001-02-03 08:05:08)
JJ: file1 | 1 +
JJ: 1 file changed, 1 insertion(+), 0 deletions(-)
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
// Only file2 with modified author should be included in the diff
work_dir
.run_jj([
"commit",
"--author",
"Another User <another.user@example.com>",
"file2",
])
.success();
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
JJ: Author: Another User <another.user@example.com> (2001-02-03 08:05:08)
JJ: Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
JJ: file2 | 1 +
JJ: 1 file changed, 1 insertion(+), 0 deletions(-)
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
// Timestamp after the reset should be available to the template
work_dir.run_jj(["commit", "--reset-author"]).success();
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
JJ: Author: Test User <test.user@example.com> (2001-02-03 08:05:10)
JJ: Committer: Test User <test.user@example.com> (2001-02-03 08:05:10)
JJ: file3 | 1 +
JJ: 1 file changed, 1 insertion(+), 0 deletions(-)
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
}
#[test]
fn test_commit_without_working_copy() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["workspace", "forget"]).success();
let output = work_dir.run_jj(["commit", "-m=first"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: This command requires a working copy
[EOF]
[exit status: 1]
");
}
#[test]
fn test_commit_paths() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
work_dir.run_jj(["commit", "-m=first", "file1"]).success();
let output = work_dir.run_jj(["diff", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
Added regular file file1:
1: foo
[EOF]
");
let output = work_dir.run_jj(["diff"]);
insta::assert_snapshot!(output, @r"
Added regular file file2:
1: bar
[EOF]
");
}
#[test]
fn test_commit_paths_warning() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
let output = work_dir.run_jj(["commit", "-m=first", "file3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: The given paths do not match any file: file3
Working copy (@) now at: rlvkpnrz 4c6f0146 (no description set)
Parent commit (@-) : qpvuntsm 68a50538 (empty) first
[EOF]
");
let output = work_dir.run_jj(["diff"]);
insta::assert_snapshot!(output, @r"
Added regular file file1:
1: foo
Added regular file file2:
1: bar
[EOF]
");
}
#[test]
fn test_commit_reset_author() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
test_env.add_config(
r#"[template-aliases]
'format_signature(signature)' = 'signature.name() ++ " " ++ signature.email() ++ " " ++ signature.timestamp()'"#,
);
let get_signatures = || {
let template = r#"format_signature(author) ++ "\n" ++ format_signature(committer)"#;
work_dir.run_jj(["log", "-r@", "-T", template])
};
insta::assert_snapshot!(get_signatures(), @r"
@ Test User test.user@example.com 2001-02-03 04:05:07.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:07.000 +07:00
~
[EOF]
");
// Reset the author (the committer is always reset)
work_dir
.run_jj([
"commit",
"--config=user.name=Ove Ridder",
"--config=user.email=ove.ridder@example.com",
"--reset-author",
"-m1",
])
.success();
insta::assert_snapshot!(get_signatures(), @r"
@ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:09.000 +07:00
โ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:09.000 +07:00
~
[EOF]
");
}
#[test]
fn test_commit_trailers() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
test_env.add_config(
r#"[templates]
commit_trailers = '''"Reviewed-by: " ++ self.committer().email()'''"#,
);
work_dir.write_file("file1", "foo\n");
let output = work_dir.run_jj(["commit", "-m=first"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: rlvkpnrz 0c0495f3 (empty) (no description set)
Parent commit (@-) : qpvuntsm ae86ffd4 first
[EOF]
");
let output = work_dir.run_jj(["log", "--no-graph", "-r@-", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
first
Reviewed-by: test.user@example.com
[EOF]
");
// the new committer should appear in the trailer
let output = work_dir.run_jj(["commit", "--config=user.email=foo@bar.org", "-m=second"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: zsuskuln fd73eac2 (empty) (no description set)
Parent commit (@-) : rlvkpnrz 6e69e833 (empty) second
[EOF]
");
let output = work_dir.run_jj(["log", "--no-graph", "-r@-", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
second
Reviewed-by: foo@bar.org
[EOF]
");
// the trailer is added in the editor
std::fs::write(&edit_script, "dump editor0").unwrap();
let output = work_dir.run_jj(["commit", "--config=user.email=foo@bar.org"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: royxmykx dac9709c (empty) (no description set)
Parent commit (@-) : zsuskuln d9ced309 (empty) Reviewed-by: foo@bar.org
[EOF]
");
let editor0 = std::fs::read_to_string(test_env.env_root().join("editor0")).unwrap();
insta::assert_snapshot!(
format!("-----\n{editor0}-----\n"), @r#"
-----
Reviewed-by: foo@bar.org
JJ: Change ID: zsuskuln
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
-----
"#);
let output = work_dir.run_jj(["log", "--no-graph", "-r@-", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
Reviewed-by: foo@bar.org
[EOF]
");
}
#[test]
fn test_commit_with_editor_and_message_args() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
std::fs::write(&edit_script, "dump editor").unwrap();
work_dir
.run_jj(["commit", "-m", "message from command line", "--editor"])
.success();
// Verify editor was opened with the message from command line
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
message from command line
JJ: Change ID: qpvuntsm
JJ: This commit contains the following changes:
JJ: A file1
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c3a4bb8be8d7
โ f6acb1a163f2 message from command line
โ 000000000000
[EOF]
");
}
#[test]
fn test_commit_with_editor_and_empty_message() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
// Use --editor with an empty message. The trailers should be added because
// the editor will be opened.
std::fs::write(&edit_script, "dump editor").unwrap();
work_dir
.run_jj([
"commit",
"-m",
"",
"--editor",
"--config",
r#"templates.commit_trailers='"Trailer: value"'"#,
])
.success();
// Verify editor was opened with trailers added to the empty message
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
Trailer: value
JJ: Change ID: qpvuntsm
JJ: This commit contains the following changes:
JJ: A file1
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
}
#[test]
fn test_commit_with_editor_without_message() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
// --editor without -m should behave the same as without --editor (normal flow)
std::fs::write(&edit_script, "dump editor").unwrap();
let output = work_dir.run_jj(["commit", "--editor"]).success();
// Verify editor was opened
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
JJ: Change ID: qpvuntsm
JJ: This commit contains the following changes:
JJ: A file1
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ f5a89f0f6366
โ 38f3e84bb6a9
โ 000000000000
[EOF]
");
insta::assert_snapshot!(output, @r"
------- stderr -------
Hint: The commit message was left empty.
If this was not intentional, run `jj undo` to restore the previous state.
Or run `jj desc @-` to add a description to the parent commit.
Working copy (@) now at: rlvkpnrz f5a89f0f (empty) (no description set)
Parent commit (@-) : qpvuntsm 38f3e84b (no description set)
[EOF]
");
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"commit_id.short() ++ " " ++ description"#;
work_dir.run_jj(["log", "-T", template])
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_git_push.rs | cli/tests/test_git_push.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::to_toml_value;
fn git_repo_dir_for_jj_repo(work_dir: &TestWorkDir<'_>) -> std::path::PathBuf {
work_dir
.root()
.join(".jj")
.join("repo")
.join("store")
.join("git")
}
fn set_up(test_env: &TestEnvironment) {
test_env.run_jj_in(".", ["git", "init", "origin"]).success();
let origin_dir = test_env.work_dir("origin");
let origin_git_repo_path = git_repo_dir_for_jj_repo(&origin_dir);
origin_dir
.run_jj(["describe", "-m=description 1"])
.success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "bookmark1"])
.success();
origin_dir
.run_jj(["new", "root()", "-m=description 2"])
.success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "bookmark2"])
.success();
origin_dir.run_jj(["git", "export"]).success();
test_env
.run_jj_in(
".",
[
"git",
"clone",
"--config=remotes.origin.auto-track-bookmarks='*'",
origin_git_repo_path.to_str().unwrap(),
"local",
],
)
.success();
}
#[test]
fn test_git_push_nothing() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
// Show the setup. `insta` has trouble if this is done inside `set_up()`
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
bookmark1: qpvuntsm 9b2e76de (empty) description 1
@origin: qpvuntsm 9b2e76de (empty) description 1
bookmark2: zsuskuln 38a20473 (empty) description 2
@origin: zsuskuln 38a20473 (empty) description 2
[EOF]
");
// No bookmarks to push yet
let output = work_dir.run_jj(["git", "push", "--all"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
}
#[test]
fn test_git_push_current_bookmark() {
let test_env = TestEnvironment::default();
set_up(&test_env);
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
let work_dir = test_env.work_dir("local");
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
// Update some bookmarks. `bookmark1` is not a current bookmark, but
// `bookmark2` and `my-bookmark` are.
work_dir
.run_jj(["describe", "bookmark1", "-m", "modified bookmark1 commit"])
.success();
work_dir.run_jj(["new", "bookmark2"]).success();
work_dir
.run_jj(["bookmark", "set", "bookmark2", "-r@"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "my-bookmark"])
.success();
work_dir.run_jj(["describe", "-m", "foo"]).success();
// Check the setup
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
bookmark1: qpvuntsm e5ce6d9a (empty) modified bookmark1 commit
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 9b2e76de (hidden) (empty) description 1
bookmark2: yostqsxw 88ca14a7 (empty) foo
@origin (behind by 1 commits): zsuskuln 38a20473 (empty) description 2
my-bookmark: yostqsxw 88ca14a7 (empty) foo
@origin (not created yet)
[EOF]
");
// First dry-run. `bookmark1` should not get pushed.
let output = work_dir.run_jj(["git", "push", "--dry-run"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move forward bookmark bookmark2 from 38a204733702 to 88ca14a7d46f
Add bookmark my-bookmark to 88ca14a7d46f
Dry-run requested, not pushing.
[EOF]
");
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move forward bookmark bookmark2 from 38a204733702 to 88ca14a7d46f
Add bookmark my-bookmark to 88ca14a7d46f
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
bookmark1: qpvuntsm e5ce6d9a (empty) modified bookmark1 commit
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 9b2e76de (hidden) (empty) description 1
bookmark2: yostqsxw 88ca14a7 (empty) foo
@origin: yostqsxw 88ca14a7 (empty) foo
my-bookmark: yostqsxw 88ca14a7 (empty) foo
@origin: yostqsxw 88ca14a7 (empty) foo
[EOF]
");
// Try pushing backwards
work_dir
.run_jj([
"bookmark",
"set",
"bookmark2",
"-rbookmark2-",
"--allow-backwards",
])
.success();
// 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, @r"
------- stderr -------
Warning: No bookmarks found in the default push revset: remote_bookmarks(remote=origin)..@
Nothing changed.
[EOF]
");
// We can move a bookmark backwards
let output = work_dir.run_jj(["git", "push", "-bbookmark2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move backward bookmark bookmark2 from 88ca14a7d46f to 38a204733702
[EOF]
");
}
#[test]
fn test_git_push_parent_bookmark() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
work_dir.run_jj(["edit", "bookmark1"]).success();
work_dir
.run_jj(["describe", "-m", "modified bookmark1 commit"])
.success();
work_dir
.run_jj(["new", "-m", "non-empty description"])
.success();
work_dir.write_file("file", "file");
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move sideways bookmark bookmark1 from 9b2e76de3920 to 80560a3e08e2
[EOF]
");
}
#[test]
fn test_git_push_no_matching_bookmark() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No bookmarks found in the default push revset: remote_bookmarks(remote=origin)..@
Nothing changed.
[EOF]
");
}
#[test]
fn test_git_push_matching_bookmark_unchanged() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
work_dir.run_jj(["new", "bookmark1"]).success();
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No bookmarks found in the default push revset: remote_bookmarks(remote=origin)..@
Nothing changed.
[EOF]
");
}
/// Test that `jj git push` without arguments pushes a bookmark to the specified
/// remote even if it's already up to date on another remote
/// (`remote_bookmarks(remote=<remote>)..@` vs. `remote_bookmarks()..@`).
#[test]
fn test_git_push_other_remote_has_bookmark() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
// Create another remote (but actually the same)
let other_remote_path = test_env
.env_root()
.join("origin")
.join(".jj")
.join("repo")
.join("store")
.join("git");
work_dir
.run_jj([
"git",
"remote",
"add",
"other",
other_remote_path.to_str().unwrap(),
])
.success();
// Modify bookmark1 and push it to `origin`
work_dir.run_jj(["edit", "bookmark1"]).success();
work_dir.run_jj(["describe", "-m=modified"]).success();
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move sideways bookmark bookmark1 from 9b2e76de3920 to a843bfad2abb
[EOF]
");
// Since it's already pushed to origin, nothing will happen if push again
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No bookmarks found in the default push revset: remote_bookmarks(remote=origin)..@
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.
//
// 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
.run_jj(["bookmark", "track", "bookmark1", "--remote=other"])
.success();
let output = work_dir.run_jj(["git", "push", "--remote=other"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to other:
Add bookmark bookmark1 to a843bfad2abb
[EOF]
");
}
#[test]
fn test_git_push_forward_unexpectedly_moved() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
// Move bookmark1 forward on the remote
let origin_dir = test_env.work_dir("origin");
origin_dir
.run_jj(["new", "bookmark1", "-m=remote"])
.success();
origin_dir.write_file("remote", "remote");
origin_dir
.run_jj(["bookmark", "set", "bookmark1", "-r@"])
.success();
origin_dir.run_jj(["git", "export"]).success();
// Move bookmark1 forward to another commit locally
work_dir.run_jj(["new", "bookmark1", "-m=local"]).success();
work_dir.write_file("local", "local");
work_dir
.run_jj(["bookmark", "set", "bookmark1", "-r@"])
.success();
// Pushing should fail
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Move forward bookmark bookmark1 from 9b2e76de3920 to 624f94a35f00
Warning: The following references unexpectedly moved on the remote:
refs/heads/bookmark1 (reason: stale info)
Hint: Try fetching from the remote, then make the bookmark point to where you want it to be, and push again.
Error: Failed to push some bookmarks
[EOF]
[exit status: 1]
");
// The ref name should be colorized
let output = work_dir.run_jj(["git", "push", "--color=always"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Move forward bookmark bookmark1 from 9b2e76de3920 to 624f94a35f00
[1m[38;5;3mWarning: [39mThe following references unexpectedly moved on the remote:[0m
[38;5;2mrefs/heads/bookmark1[39m (reason: stale info)
[1m[38;5;6mHint: [0m[39mTry fetching from the remote, then make the bookmark point to where you want it to be, and push again.[39m
[1m[38;5;1mError: [39mFailed to push some bookmarks[0m
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_push_sideways_unexpectedly_moved() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
// Move bookmark1 forward on the remote
let origin_dir = test_env.work_dir("origin");
origin_dir
.run_jj(["new", "bookmark1", "-m=remote"])
.success();
origin_dir.write_file("remote", "remote");
origin_dir
.run_jj(["bookmark", "set", "bookmark1", "-r@"])
.success();
insta::assert_snapshot!(get_bookmark_output(&origin_dir), @r"
bookmark1: vruxwmqv 7ce4029e remote
@git (behind by 1 commits): qpvuntsm 9b2e76de (empty) description 1
bookmark2: zsuskuln 38a20473 (empty) description 2
@git: zsuskuln 38a20473 (empty) description 2
[EOF]
");
origin_dir.run_jj(["git", "export"]).success();
// Move bookmark1 sideways to another commit locally
work_dir.run_jj(["new", "root()", "-m=local"]).success();
work_dir.write_file("local", "local");
work_dir
.run_jj(["bookmark", "set", "bookmark1", "--allow-backwards", "-r@"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
bookmark1: kmkuslsw 827b8a38 local
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm 9b2e76de (empty) description 1
bookmark2: zsuskuln 38a20473 (empty) description 2
@origin: zsuskuln 38a20473 (empty) description 2
[EOF]
");
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Move sideways bookmark bookmark1 from 9b2e76de3920 to 827b8a385853
Warning: The following references unexpectedly moved on the remote:
refs/heads/bookmark1 (reason: stale info)
Hint: Try fetching from the remote, then make the bookmark point to where you want it to be, and push again.
Error: Failed to push some bookmarks
[EOF]
[exit status: 1]
");
// The ref name should be colorized
let output = work_dir.run_jj(["git", "push", "--color=always"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Move sideways bookmark bookmark1 from 9b2e76de3920 to 827b8a385853
[1m[38;5;3mWarning: [39mThe following references unexpectedly moved on the remote:[0m
[38;5;2mrefs/heads/bookmark1[39m (reason: stale info)
[1m[38;5;6mHint: [0m[39mTry fetching from the remote, then make the bookmark point to where you want it to be, and push again.[39m
[1m[38;5;1mError: [39mFailed to push some bookmarks[0m
[EOF]
[exit status: 1]
");
}
// This tests whether the push checks that the remote bookmarks are in expected
// positions.
#[test]
fn test_git_push_deletion_unexpectedly_moved() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
// Move bookmark1 forward on the remote
let origin_dir = test_env.work_dir("origin");
origin_dir
.run_jj(["new", "bookmark1", "-m=remote"])
.success();
origin_dir.write_file("remote", "remote");
origin_dir
.run_jj(["bookmark", "set", "bookmark1", "-r@"])
.success();
insta::assert_snapshot!(get_bookmark_output(&origin_dir), @r"
bookmark1: vruxwmqv 7ce4029e remote
@git (behind by 1 commits): qpvuntsm 9b2e76de (empty) description 1
bookmark2: zsuskuln 38a20473 (empty) description 2
@git: zsuskuln 38a20473 (empty) description 2
[EOF]
");
origin_dir.run_jj(["git", "export"]).success();
// Delete bookmark1 locally
work_dir
.run_jj(["bookmark", "delete", "bookmark1"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
bookmark1 (deleted)
@origin: qpvuntsm 9b2e76de (empty) description 1
bookmark2: zsuskuln 38a20473 (empty) description 2
@origin: zsuskuln 38a20473 (empty) description 2
[EOF]
");
let output = work_dir.run_jj(["git", "push", "--bookmark", "bookmark1"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Delete bookmark bookmark1 from 9b2e76de3920
Warning: The following references unexpectedly moved on the remote:
refs/heads/bookmark1 (reason: stale info)
Hint: Try fetching from the remote, then make the bookmark point to where you want it to be, and push again.
Error: Failed to push some bookmarks
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_push_unexpectedly_deleted() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
// Delete bookmark1 forward on the remote
let origin_dir = test_env.work_dir("origin");
origin_dir
.run_jj(["bookmark", "delete", "bookmark1"])
.success();
insta::assert_snapshot!(get_bookmark_output(&origin_dir), @r"
bookmark1 (deleted)
@git: qpvuntsm 9b2e76de (empty) description 1
bookmark2: zsuskuln 38a20473 (empty) description 2
@git: zsuskuln 38a20473 (empty) description 2
[EOF]
");
origin_dir.run_jj(["git", "export"]).success();
// Move bookmark1 sideways to another commit locally
work_dir.run_jj(["new", "root()", "-m=local"]).success();
work_dir.write_file("local", "local");
work_dir
.run_jj(["bookmark", "set", "bookmark1", "--allow-backwards", "-r@"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
bookmark1: kpqxywon 09919fb0 local
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm 9b2e76de (empty) description 1
bookmark2: zsuskuln 38a20473 (empty) description 2
@origin: zsuskuln 38a20473 (empty) description 2
[EOF]
");
// Pushing a moved bookmark fails if deleted on remote
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Move sideways bookmark bookmark1 from 9b2e76de3920 to 09919fb051bf
Warning: The following references unexpectedly moved on the remote:
refs/heads/bookmark1 (reason: stale info)
Hint: Try fetching from the remote, then make the bookmark point to where you want it to be, and push again.
Error: Failed to push some bookmarks
[EOF]
[exit status: 1]
");
work_dir
.run_jj(["bookmark", "delete", "bookmark1"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
bookmark1 (deleted)
@origin: qpvuntsm 9b2e76de (empty) description 1
bookmark2: zsuskuln 38a20473 (empty) description 2
@origin: zsuskuln 38a20473 (empty) description 2
[EOF]
");
// 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 -------
Changes to push to origin:
Delete bookmark bookmark1 from 9b2e76de3920
Warning: The following references unexpectedly moved on the remote:
refs/heads/bookmark1 (reason: stale info)
Hint: Try fetching from the remote, then make the bookmark point to where you want it to be, and push again.
Error: Failed to push some bookmarks
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_push_creation_unexpectedly_already_exists() {
let test_env = TestEnvironment::default();
set_up(&test_env);
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
let work_dir = test_env.work_dir("local");
// Forget bookmark1 locally
work_dir
.run_jj(["bookmark", "forget", "--include-remotes", "bookmark1"])
.success();
// Create a new bookmark1
work_dir
.run_jj(["new", "root()", "-m=new bookmark1"])
.success();
work_dir.write_file("local", "local");
work_dir
.run_jj(["bookmark", "create", "-r@", "bookmark1"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
bookmark1: yostqsxw a43cb801 new bookmark1
@origin (not created yet)
bookmark2: zsuskuln 38a20473 (empty) description 2
@origin: zsuskuln 38a20473 (empty) description 2
[EOF]
");
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Add bookmark bookmark1 to a43cb8011c85
Warning: The following references unexpectedly moved on the remote:
refs/heads/bookmark1 (reason: stale info)
Hint: Try fetching from the remote, then make the bookmark point to where you want it to be, and push again.
Error: Failed to push some bookmarks
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_push_locally_created_and_rewritten() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
// Ensure that remote bookmarks aren't tracked automatically
test_env.add_config("remotes.origin.auto-track-bookmarks = '~*'");
// Push locally-created bookmark
work_dir.run_jj(["new", "root()", "-mlocal 1"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "my"])
.success();
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Refusing to create new remote bookmark my@origin
Hint: Run `jj bookmark track my --remote=origin` and try again.
Nothing changed.
[EOF]
");
// Either --allow-new or git.push-new-bookmarks=true should work
let output = work_dir.run_jj(["git", "push", "--allow-new", "--dry-run"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: --allow-new is deprecated, track bookmarks manually or configure remotes.<name>.auto-track-bookmarks instead.
Changes to push to origin:
Add bookmark my to e0cba5e497ee
Dry-run requested, not pushing.
[EOF]
");
let output = work_dir.run_jj([
"git",
"push",
"--config=git.push-new-bookmarks=true",
"--dry-run",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Deprecated CLI-provided config: `git.push-new-bookmarks` is deprecated; use `remotes.<name>.auto-track-bookmarks` instead.
Example: jj config set --user remotes.origin.auto-track-bookmarks '*'
For details, see: https://docs.jj-vcs.dev/latest/config/#automatic-tracking-of-bookmarks
Changes to push to origin:
Add bookmark my to e0cba5e497ee
Dry-run requested, not pushing.
[EOF]
");
// Absent-tracked bookmark can be pushed without --allow-new
work_dir
.run_jj(["bookmark", "track", "my", "--remote=origin"])
.success();
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Add bookmark my to e0cba5e497ee
[EOF]
");
// 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), @r"
bookmark1: qpvuntsm 9b2e76de (empty) description 1
@origin: qpvuntsm 9b2e76de (empty) description 1
bookmark2: zsuskuln 38a20473 (empty) description 2
@origin: zsuskuln 38a20473 (empty) description 2
my: vruxwmqv 9ebc3217 (empty) local 2
@origin (ahead by 1 commits, behind by 1 commits): vruxwmqv/1 e0cba5e4 (hidden) (empty) local 1
[EOF]
");
let output = work_dir.run_jj(["git", "push"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move sideways bookmark my from e0cba5e497ee to 9ebc3217a0b8
[EOF]
");
}
#[test]
fn test_git_push_multiple() {
let test_env = TestEnvironment::default();
set_up(&test_env);
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
let origin_dir = test_env.work_dir("origin");
let work_dir = test_env.work_dir("local");
work_dir
.run_jj(["bookmark", "delete", "bookmark1"])
.success();
work_dir
.run_jj(["bookmark", "set", "--allow-backwards", "bookmark2", "-r@"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "my-bookmark"])
.success();
work_dir.run_jj(["describe", "-m", "foo"]).success();
// Make conflicting changes on bookmark3
work_dir
.run_jj(["bookmark", "set", "bookmark3", "-rbookmark2"])
.success();
origin_dir
.run_jj(["bookmark", "set", "bookmark3", "-rbookmark1"])
.success();
origin_dir.run_jj(["git", "export"]).success();
// Check the setup
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"
bookmark1 (deleted)
@origin: qpvuntsm 9b2e76de (empty) description 1
bookmark2: yqosqzyt 352fa187 (empty) foo
@origin (ahead by 1 commits, behind by 1 commits): zsuskuln 38a20473 (empty) description 2
bookmark3: yqosqzyt 352fa187 (empty) foo
@origin (not created yet)
my-bookmark: yqosqzyt 352fa187 (empty) foo
@origin (not created yet)
[EOF]
");
// First dry-run
let output = work_dir.run_jj(["git", "push", "--all", "--deleted", "--dry-run"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Delete bookmark bookmark1 from 9b2e76de3920
Move sideways bookmark bookmark2 from 38a204733702 to 352fa1879f75
Add bookmark bookmark3 to 352fa1879f75
Add bookmark my-bookmark to 352fa1879f75
Dry-run requested, not pushing.
[EOF]
");
// Dry run requesting two specific bookmarks
let output = work_dir.run_jj(["git", "push", "-b=bookmark1", "-b=my-bookmark", "--dry-run"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Delete bookmark bookmark1 from 9b2e76de3920
Add bookmark my-bookmark to 352fa1879f75
Dry-run requested, not pushing.
[EOF]
");
// Dry run requesting two specific bookmarks twice
let output = work_dir.run_jj([
"git",
"push",
"-b=bookmark1",
"-b=my-bookmark",
"-b=bookmark1",
"-b=my-*",
"--dry-run",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Delete bookmark bookmark1 from 9b2e76de3920
Add bookmark my-bookmark to 352fa1879f75
Dry-run requested, not pushing.
[EOF]
");
// Dry run with glob pattern
let output = work_dir.run_jj(["git", "push", "-b='bookmark?'", "--dry-run"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Delete bookmark bookmark1 from 9b2e76de3920
Move sideways bookmark bookmark2 from 38a204733702 to 352fa1879f75
Add bookmark bookmark3 to 352fa1879f75
Dry-run requested, not pushing.
[EOF]
");
// Unmatched bookmark name
let output = work_dir.run_jj(["git", "push", "-b=foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching bookmarks for names: foo
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["git", "push", "-b=foo", "-b='?bookmark'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching bookmarks for names: foo
Nothing changed.
[EOF]
");
// --deleted is required to push deleted bookmarks even with --all
let output = work_dir.run_jj(["git", "push", "--all", "--dry-run"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Warning: Refusing to push deleted bookmark bookmark1
Hint: Push deleted bookmarks with --deleted or forget the bookmark to suppress this warning.
Changes to push to origin:
Move sideways bookmark bookmark2 from 38a204733702 to 352fa1879f75
Add bookmark bookmark3 to 352fa1879f75
Add bookmark my-bookmark to 352fa1879f75
Dry-run requested, not pushing.
[EOF]
");
let output = work_dir.run_jj(["git", "push", "--all", "--deleted", "--dry-run"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Delete bookmark bookmark1 from 9b2e76de3920
Move sideways bookmark bookmark2 from 38a204733702 to 352fa1879f75
Add bookmark bookmark3 to 352fa1879f75
Add bookmark my-bookmark to 352fa1879f75
Dry-run requested, not pushing.
[EOF]
");
// All pushed bookmarks should be committed to the operation. Therefore, the
// subsequent "git import" should be noop.
let output = work_dir.run_jj(["git", "push", "--all", "--deleted"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Changes to push to origin:
Delete bookmark bookmark1 from 9b2e76de3920
Move sideways bookmark bookmark2 from 38a204733702 to 352fa1879f75
Add bookmark bookmark3 to 352fa1879f75
Add bookmark my-bookmark to 352fa1879f75
Warning: The following references unexpectedly moved on the remote:
refs/heads/bookmark3 (reason: stale info)
Hint: Try fetching from the remote, then make the bookmark point to where you want it to be, and push again.
Error: Failed to push some bookmarks
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["git", "import"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Nothing changed.
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"
bookmark2: yqosqzyt 352fa187 (empty) foo
@origin: yqosqzyt 352fa187 (empty) foo
bookmark3: yqosqzyt 352fa187 (empty) foo
@origin (not created yet)
my-bookmark: yqosqzyt 352fa187 (empty) foo
@origin: yqosqzyt 352fa187 (empty) foo
[EOF]
");
let output = work_dir.run_jj(["log", "-rall()"]);
insta::assert_snapshot!(output, @"
@ yqosqzyt test.user@example.com 2001-02-03 08:05:17 bookmark2 bookmark3* my-bookmark 352fa187
โ (empty) foo
โ โ zsuskuln test.user@example.com 2001-02-03 08:05:10 38a20473
โโโฏ (empty) description 2
โ โ qpvuntsm test.user@example.com 2001-02-03 08:05:08 9b2e76de
โโโฏ (empty) description 1
โ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_git_push_changes() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
work_dir.run_jj(["describe", "-m", "foo"]).success();
work_dir.write_file("file", "contents");
work_dir.run_jj(["new", "-m", "bar"]).success();
work_dir.write_file("file", "modified");
let output = work_dir.run_jj(["git", "push", "--change", "@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Creating bookmark push-yostqsxwqrlt for revision yostqsxwqrlt
Changes to push to origin:
Add bookmark push-yostqsxwqrlt to 916414184c47
[EOF]
");
// test pushing two changes at once
work_dir.write_file("file", "modified2");
let output = work_dir.run_jj(["git", "push", "-c=(@|@-)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Creating bookmark push-yqosqzytrlsw for revision yqosqzytrlsw
Changes to push to origin:
Move sideways bookmark push-yostqsxwqrlt from 916414184c47 to 2723f6111cb9
Add bookmark push-yqosqzytrlsw to 0f8164cd580b
[EOF]
");
// specifying the same change twice doesn't break things
work_dir.write_file("file", "modified3");
let output = work_dir.run_jj(["git", "push", "-c=(@|@)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move sideways bookmark push-yostqsxwqrlt from 2723f6111cb9 to ee4011999491
[EOF]
");
// 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, @r"
------- stderr -------
Changes to push to origin:
Move sideways bookmark push-yostqsxwqrlt from ee4011999491 to 1b393e646dec
[EOF]
");
// try again with --change that could move the bookmark forward
work_dir.write_file("file", "modified5");
work_dir
.run_jj([
"bookmark",
"set",
"-r=@-",
"--allow-backwards",
"push-yostqsxwqrlt",
])
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_evolog_command.rs | cli/tests/test_evolog_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::TestEnvironment;
use crate::common::to_toml_value;
#[test]
fn test_evolog_with_or_without_diff() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.run_jj(["new", "-m", "my description"]).success();
work_dir.write_file("file1", "foo\nbar\n");
work_dir.write_file("file2", "foo\n");
work_dir
.run_jj(["rebase", "-r", "@", "-o", "root()"])
.success();
work_dir.write_file("file1", "resolved\n");
let output = work_dir.run_jj(["evolog"]);
insta::assert_snapshot!(output, @r"
@ rlvkpnrz test.user@example.com 2001-02-03 08:05:10 33c10ace
โ my description
โ -- operation 29abe568fb5a snapshot working copy
ร rlvkpnrz/1 test.user@example.com 2001-02-03 08:05:09 984f03b9 (hidden) (conflict)
โ my description
โ -- operation 863adc9ab542 rebase commit 51e08f95160c897080d035d330aead3ee6ed5588
โ rlvkpnrz/2 test.user@example.com 2001-02-03 08:05:09 51e08f95 (hidden)
โ my description
โ -- operation 826347115e2d snapshot working copy
โ rlvkpnrz/3 test.user@example.com 2001-02-03 08:05:08 b955b72e (hidden)
(empty) my description
-- operation e0f8e58b3800 new empty commit
[EOF]
");
// Color
let output = work_dir.run_jj(["--color=always", "evolog"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m [1m[38;5;13mr[38;5;8mlvkpnrz[39m [38;5;3mtest.user@example.com[39m [38;5;14m2001-02-03 08:05:10[39m [38;5;12m3[38;5;8m3c10ace[39m[0m
โ [1mmy description[0m
โ [38;5;8m--[39m operation [38;5;4m29abe568fb5a[39m snapshot working copy
[1m[38;5;1mร[0m [1m[39mr[0m[38;5;8mlvkpnrz[1m[39m/1[0m [38;5;3mtest.user@example.com[39m [38;5;6m2001-02-03 08:05:09[39m [1m[38;5;4m9[0m[38;5;8m84f03b9[39m (hidden) [38;5;1m(conflict)[39m
โ my description
โ [38;5;8m--[39m operation [38;5;4m863adc9ab542[39m rebase commit 51e08f95160c897080d035d330aead3ee6ed5588
โ [1m[39mr[0m[38;5;8mlvkpnrz[1m[39m/2[0m [38;5;3mtest.user@example.com[39m [38;5;6m2001-02-03 08:05:09[39m [1m[38;5;4m5[0m[38;5;8m1e08f95[39m (hidden)
โ my description
โ [38;5;8m--[39m operation [38;5;4m826347115e2d[39m snapshot working copy
โ [1m[39mr[0m[38;5;8mlvkpnrz[1m[39m/3[0m [38;5;3mtest.user@example.com[39m [38;5;6m2001-02-03 08:05:08[39m [1m[38;5;4mb[0m[38;5;8m955b72e[39m (hidden)
[38;5;2m(empty)[39m my description
[38;5;8m--[39m operation [38;5;4me0f8e58b3800[39m new empty commit
[EOF]
");
// There should be no diff caused by the rebase because it was a pure rebase
// (even even though it resulted in a conflict).
let output = work_dir.run_jj(["evolog", "-p"]);
insta::assert_snapshot!(output, @r#"
@ rlvkpnrz test.user@example.com 2001-02-03 08:05:10 33c10ace
โ my description
โ -- operation 29abe568fb5a snapshot working copy
โ Resolved conflict in file1:
โ 1 : <<<<<<< conflict 1 of 1
โ 2 : %%%%%%% diff from: qpvuntsm c664a51b (parents of rebased revision)
โ 3 : \\\\\\\ to: zzzzzzzz 00000000 (rebase destination)
โ 4 : -foo
โ 5 : +++++++ rlvkpnrz 51e08f95 "my description" (rebased revision)
โ 6 : foo
โ 7 : bar
โ 8 1: >>>>>>> conflict 1 of 1 endsresolved
ร rlvkpnrz/1 test.user@example.com 2001-02-03 08:05:09 984f03b9 (hidden) (conflict)
โ my description
โ -- operation 863adc9ab542 rebase commit 51e08f95160c897080d035d330aead3ee6ed5588
โ rlvkpnrz/2 test.user@example.com 2001-02-03 08:05:09 51e08f95 (hidden)
โ my description
โ -- operation 826347115e2d snapshot working copy
โ Modified regular file file1:
โ 1 1: foo
โ 2: bar
โ Added regular file file2:
โ 1: foo
โ rlvkpnrz/3 test.user@example.com 2001-02-03 08:05:08 b955b72e (hidden)
(empty) my description
-- operation e0f8e58b3800 new empty commit
Modified commit description:
1: my description
[EOF]
"#);
// Multiple starting revisions
let output = work_dir.run_jj(["evolog", "-r.."]);
insta::assert_snapshot!(output, @r"
@ rlvkpnrz test.user@example.com 2001-02-03 08:05:10 33c10ace
โ my description
โ -- operation 29abe568fb5a snapshot working copy
ร rlvkpnrz/1 test.user@example.com 2001-02-03 08:05:09 984f03b9 (hidden) (conflict)
โ my description
โ -- operation 863adc9ab542 rebase commit 51e08f95160c897080d035d330aead3ee6ed5588
โ rlvkpnrz/2 test.user@example.com 2001-02-03 08:05:09 51e08f95 (hidden)
โ my description
โ -- operation 826347115e2d snapshot working copy
โ rlvkpnrz/3 test.user@example.com 2001-02-03 08:05:08 b955b72e (hidden)
(empty) my description
-- operation e0f8e58b3800 new empty commit
โ qpvuntsm test.user@example.com 2001-02-03 08:05:08 c664a51b
โ (no description set)
โ -- operation ca1226de0084 snapshot working copy
โ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
[EOF]
");
// Test `--limit`
let output = work_dir.run_jj(["evolog", "--limit=2"]);
insta::assert_snapshot!(output, @r"
@ rlvkpnrz test.user@example.com 2001-02-03 08:05:10 33c10ace
โ my description
โ -- operation 29abe568fb5a snapshot working copy
ร rlvkpnrz/1 test.user@example.com 2001-02-03 08:05:09 984f03b9 (hidden) (conflict)
โ my description
โ -- operation 863adc9ab542 rebase commit 51e08f95160c897080d035d330aead3ee6ed5588
[EOF]
");
// Test `--no-graph`
let output = work_dir.run_jj(["evolog", "--no-graph"]);
insta::assert_snapshot!(output, @r"
rlvkpnrz test.user@example.com 2001-02-03 08:05:10 33c10ace
my description
-- operation 29abe568fb5a snapshot working copy
rlvkpnrz/1 test.user@example.com 2001-02-03 08:05:09 984f03b9 (hidden) (conflict)
my description
-- operation 863adc9ab542 rebase commit 51e08f95160c897080d035d330aead3ee6ed5588
rlvkpnrz/2 test.user@example.com 2001-02-03 08:05:09 51e08f95 (hidden)
my description
-- operation 826347115e2d snapshot working copy
rlvkpnrz/3 test.user@example.com 2001-02-03 08:05:08 b955b72e (hidden)
(empty) my description
-- operation e0f8e58b3800 new empty commit
[EOF]
");
// Test `--git` format, and that it implies `-p`
let output = work_dir.run_jj(["evolog", "--no-graph", "--git"]);
insta::assert_snapshot!(output, @r#"
rlvkpnrz test.user@example.com 2001-02-03 08:05:10 33c10ace
my description
-- operation 29abe568fb5a snapshot working copy
diff --git a/file1 b/file1
index 0000000000..2ab19ae607 100644
--- a/file1
+++ b/file1
@@ -1,8 +1,1 @@
-<<<<<<< conflict 1 of 1
-%%%%%%% diff from: qpvuntsm c664a51b (parents of rebased revision)
-\\\\\\\ to: zzzzzzzz 00000000 (rebase destination)
--foo
-+++++++ rlvkpnrz 51e08f95 "my description" (rebased revision)
-foo
-bar
->>>>>>> conflict 1 of 1 ends
+resolved
rlvkpnrz/1 test.user@example.com 2001-02-03 08:05:09 984f03b9 (hidden) (conflict)
my description
-- operation 863adc9ab542 rebase commit 51e08f95160c897080d035d330aead3ee6ed5588
rlvkpnrz/2 test.user@example.com 2001-02-03 08:05:09 51e08f95 (hidden)
my description
-- operation 826347115e2d snapshot working copy
diff --git a/file1 b/file1
index 257cc5642c..3bd1f0e297 100644
--- a/file1
+++ b/file1
@@ -1,1 +1,2 @@
foo
+bar
diff --git a/file2 b/file2
new file mode 100644
index 0000000000..257cc5642c
--- /dev/null
+++ b/file2
@@ -0,0 +1,1 @@
+foo
rlvkpnrz/3 test.user@example.com 2001-02-03 08:05:08 b955b72e (hidden)
(empty) my description
-- operation e0f8e58b3800 new empty commit
diff --git a/JJ-COMMIT-DESCRIPTION b/JJ-COMMIT-DESCRIPTION
--- JJ-COMMIT-DESCRIPTION
+++ JJ-COMMIT-DESCRIPTION
@@ -0,0 +1,1 @@
+my description
[EOF]
"#);
}
#[test]
fn test_evolog_template() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "origin"])
.success();
let origin_dir = test_env.work_dir("origin");
origin_dir
.run_jj(["bookmark", "set", "-r@", "main"])
.success();
test_env
.run_jj_in(".", ["git", "clone", "origin", "local"])
.success();
let work_dir = test_env.work_dir("local");
// default template with operation
let output = work_dir.run_jj(["evolog", "-r@"]);
insta::assert_snapshot!(output, @r"
@ kkmpptxz test.user@example.com 2001-02-03 08:05:09 2b17ac71
(empty) (no description set)
-- operation 2931515731a6 add workspace 'default'
[EOF]
");
let output = work_dir.run_jj(["evolog", "-r@", "--color=debug"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m<<evolog commit node working_copy mutable::@>>[0m [1m[38;5;13m<<evolog working_copy mutable commit change_id shortest prefix::k>>[38;5;8m<<evolog working_copy mutable commit change_id shortest rest::kmpptxz>>[39m<<evolog working_copy mutable:: >>[38;5;3m<<evolog working_copy mutable commit author email local::test.user>><<evolog working_copy mutable commit author email::@>><<evolog working_copy mutable commit author email domain::example.com>>[39m<<evolog working_copy mutable:: >>[38;5;14m<<evolog working_copy mutable commit committer timestamp local format::2001-02-03 08:05:09>>[39m<<evolog working_copy mutable:: >>[38;5;12m<<evolog working_copy mutable commit commit_id shortest prefix::2>>[38;5;8m<<evolog working_copy mutable commit commit_id shortest rest::b17ac71>>[39m<<evolog working_copy mutable::>>[0m
[1m[38;5;10m<<evolog working_copy mutable empty::(empty)>>[39m<<evolog working_copy mutable:: >>[38;5;10m<<evolog working_copy mutable empty description placeholder::(no description set)>>[39m<<evolog working_copy mutable::>>[0m
[38;5;8m<<evolog separator::-->>[39m<<evolog:: operation >>[38;5;4m<<evolog operation id short::2931515731a6>>[39m<<evolog:: >><<evolog operation description first_line::add workspace 'default'>><<evolog::>>
[EOF]
");
// default template without operation
let output = work_dir.run_jj(["evolog", "-rmain@origin"]);
insta::assert_snapshot!(output, @r"
โ qpvuntsm test.user@example.com 2001-02-03 08:05:07 main@origin e8849ae1
(empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["evolog", "-rmain@origin", "--color=debug"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;14m<<evolog commit node immutable::โ>>[0m [1m[38;5;5m<<evolog immutable commit change_id shortest prefix::q>>[0m[38;5;8m<<evolog immutable commit change_id shortest rest::pvuntsm>>[39m<<evolog immutable:: >>[38;5;3m<<evolog immutable commit author email local::test.user>><<evolog immutable commit author email::@>><<evolog immutable commit author email domain::example.com>>[39m<<evolog immutable:: >>[38;5;6m<<evolog immutable commit committer timestamp local format::2001-02-03 08:05:07>>[39m<<evolog immutable:: >>[38;5;5m<<evolog immutable commit bookmarks name::main>><<evolog immutable commit bookmarks::@>><<evolog immutable commit bookmarks remote::origin>>[39m<<evolog immutable:: >>[1m[38;5;4m<<evolog immutable commit commit_id shortest prefix::e>>[0m[38;5;8m<<evolog immutable commit commit_id shortest rest::8849ae1>>[39m<<evolog immutable::>>
[38;5;2m<<evolog immutable empty::(empty)>>[39m<<evolog immutable:: >>[38;5;2m<<evolog immutable empty description placeholder::(no description set)>>[39m<<evolog immutable::>>
[EOF]
");
// default template with root commit
let output = work_dir.run_jj(["evolog", "-rroot()"]);
insta::assert_snapshot!(output, @r"
โ zzzzzzzz root() 00000000
[EOF]
");
let output = work_dir.run_jj(["evolog", "-rroot()", "--color=debug"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;14m<<evolog commit node immutable::โ>>[0m [1m[38;5;5m<<evolog immutable commit change_id shortest prefix::z>>[0m[38;5;8m<<evolog immutable commit change_id shortest rest::zzzzzzz>>[39m<<evolog immutable:: >>[38;5;2m<<evolog immutable root::root()>>[39m<<evolog immutable:: >>[1m[38;5;4m<<evolog immutable commit commit_id shortest prefix::0>>[0m[38;5;8m<<evolog immutable commit commit_id shortest rest::0000000>>[39m<<evolog immutable::>>
[EOF]
");
// JSON output with operation
let output = work_dir.run_jj(["evolog", "-r@", "-Tjson(self)", "--no-graph"]);
insta::assert_snapshot!(output, @r#"{"commit":{"commit_id":"2b17ac719c7db025e2514f5708d2b0328fc6b268","parents":["0000000000000000000000000000000000000000"],"change_id":"kkmpptxzrspxrzommnulwmwkkqwworpl","description":"","author":{"name":"Test User","email":"test.user@example.com","timestamp":"2001-02-03T04:05:09+07:00"},"committer":{"name":"Test User","email":"test.user@example.com","timestamp":"2001-02-03T04:05:09+07:00"}},"operation":{"id":"2931515731a6903101194e8e889efb13f7494077d8ec2650e2ec40ad69c32fe45385a3d333d1792ffbc410655f1e98daa404f709062a7908bc0b03a0241825bc","parents":["00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"],"time":{"start":"2001-02-03T04:05:09+07:00","end":"2001-02-03T04:05:09+07:00"},"description":"add workspace 'default'","hostname":"host.example.com","username":"test-username","is_snapshot":false,"tags":{}}}[EOF]"#);
// JSON output without operation
let output = work_dir.run_jj(["evolog", "-rmain@origin", "-Tjson(self)", "--no-graph"]);
insta::assert_snapshot!(output, @r#"{"commit":{"commit_id":"e8849ae12c709f2321908879bc724fdb2ab8a781","parents":["0000000000000000000000000000000000000000"],"change_id":"qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu","description":"","author":{"name":"Test User","email":"test.user@example.com","timestamp":"2001-02-03T04:05:07+07:00"},"committer":{"name":"Test User","email":"test.user@example.com","timestamp":"2001-02-03T04:05:07+07:00"}},"operation":null}[EOF]"#);
}
#[test]
fn test_evolog_with_custom_symbols() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.run_jj(["new", "-m", "my description"]).success();
work_dir.write_file("file1", "foo\nbar\n");
work_dir.write_file("file2", "foo\n");
work_dir
.run_jj(["rebase", "-r", "@", "-o", "root()"])
.success();
work_dir.write_file("file1", "resolved\n");
let config = "templates.log_node='if(current_working_copy, \"$\", \"โ\")'";
let output = work_dir.run_jj(["evolog", "--config", config]);
insta::assert_snapshot!(output, @r"
$ rlvkpnrz test.user@example.com 2001-02-03 08:05:10 33c10ace
โ my description
โ -- operation 9989311c94df snapshot working copy
โ rlvkpnrz/1 test.user@example.com 2001-02-03 08:05:09 984f03b9 (hidden) (conflict)
โ my description
โ -- operation 863adc9ab542 rebase commit 51e08f95160c897080d035d330aead3ee6ed5588
โ rlvkpnrz/2 test.user@example.com 2001-02-03 08:05:09 51e08f95 (hidden)
โ my description
โ -- operation 826347115e2d snapshot working copy
โ rlvkpnrz/3 test.user@example.com 2001-02-03 08:05:08 b955b72e (hidden)
(empty) my description
-- operation e0f8e58b3800 new empty commit
[EOF]
");
}
#[test]
fn test_evolog_word_wrap() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let render = |args: &[&str], columns: u32, word_wrap: bool| {
let word_wrap = to_toml_value(word_wrap);
work_dir.run_jj_with(|cmd| {
cmd.args(args)
.arg(format!("--config=ui.log-word-wrap={word_wrap}"))
.env("COLUMNS", columns.to_string())
})
};
work_dir.run_jj(["describe", "-m", "first"]).success();
// ui.log-word-wrap option applies to both graph/no-graph outputs
insta::assert_snapshot!(render(&["evolog"], 40, false), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:08 68a50538
โ (empty) first
โ -- operation 75545f7ff2df describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
[EOF]
");
insta::assert_snapshot!(render(&["evolog"], 40, true), @r"
@ qpvuntsm test.user@example.com
โ 2001-02-03 08:05:08 68a50538
โ (empty) first
โ -- operation 75545f7ff2df describe
โ commit
โ e8849ae12c709f2321908879bc724fdb2ab8a781
โ qpvuntsm/1 test.user@example.com
2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add
workspace 'default'
[EOF]
");
insta::assert_snapshot!(render(&["evolog", "--no-graph"], 40, false), @r"
qpvuntsm test.user@example.com 2001-02-03 08:05:08 68a50538
(empty) first
-- operation 75545f7ff2df describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
qpvuntsm/1 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
[EOF]
");
insta::assert_snapshot!(render(&["evolog", "--no-graph"], 40, true), @r"
qpvuntsm test.user@example.com
2001-02-03 08:05:08 68a50538
(empty) first
-- operation 75545f7ff2df describe
commit
e8849ae12c709f2321908879bc724fdb2ab8a781
qpvuntsm/1 test.user@example.com
2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace
'default'
[EOF]
");
}
#[test]
fn test_evolog_squash() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "first"]).success();
work_dir.write_file("file1", "foo\n");
work_dir.run_jj(["new", "-m", "second"]).success();
work_dir.write_file("file1", "foo\nbar\n");
// not partial
work_dir.run_jj(["squash", "-m", "squashed 1"]).success();
work_dir.run_jj(["describe", "-m", "third"]).success();
work_dir.write_file("file1", "foo\nbar\nbaz\n");
work_dir.write_file("file2", "foo2\n");
work_dir.write_file("file3", "foo3\n");
// partial
work_dir
.run_jj(["squash", "-m", "squashed 2", "file1"])
.success();
work_dir.run_jj(["new", "-m", "fourth"]).success();
work_dir.write_file("file4", "foo4\n");
work_dir.run_jj(["new", "-m", "fifth"]).success();
work_dir.write_file("file5", "foo5\n");
// multiple sources
work_dir
.run_jj([
"squash",
"-msquashed 3",
"--from=subject(fourth)|subject(fifth)",
"--into=subject(squash*)",
])
.success();
let output = work_dir.run_jj(["evolog", "-p", "-rsubject(squash*)"]);
insta::assert_snapshot!(output, @r"
โ qpvuntsm test.user@example.com 2001-02-03 08:05:15 5f3281c6
โโโฌโโฎ squashed 3
โ โ โ -- operation 69ecc16188a1 squash commits into 5ec0619af5cb4f7707a556a71a6f96af0bc294d2
โ โ โ Modified commit description:
โ โ โ 1 : <<<<<<< conflict 1 of 1
โ โ โ 2 : +++++++ side #1
โ โ โ 3 1: squashed 2
โ โ โ 4 : %%%%%%% diff from base #1 to side #2
โ โ โ 5 : +fourth
โ โ โ 6 1: %%%%%%% diff from base #2 to side #3
โ โ โ 7 : +fifth
โ โ โ 8 : >>>>>>> conflict 1 of 1 ends
โ โ โ vruxwmqv/0 test.user@example.com 2001-02-03 08:05:15 770795d0 (hidden)
โ โ โ fifth
โ โ โ -- operation b22b0aceb94e snapshot working copy
โ โ โ Added regular file file5:
โ โ โ 1: foo5
โ โ โ vruxwmqv/1 test.user@example.com 2001-02-03 08:05:14 2e0123d1 (hidden)
โ โ (empty) fifth
โ โ -- operation fc852ed87801 new empty commit
โ โ Modified commit description:
โ โ 1: fifth
โ โ yqosqzyt/0 test.user@example.com 2001-02-03 08:05:14 ea8161b6 (hidden)
โ โ fourth
โ โ -- operation 3b09d55dfa6e snapshot working copy
โ โ Added regular file file4:
โ โ 1: foo4
โ โ yqosqzyt/1 test.user@example.com 2001-02-03 08:05:13 1de5fdb6 (hidden)
โ (empty) fourth
โ -- operation 9404a551035a new empty commit
โ Modified commit description:
โ 1: fourth
โ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:12 5ec0619a (hidden)
โโโฎ squashed 2
โ โ -- operation fa9796d12627 squash commits into 690858846504af0e42fde980fdacf9851559ebb8
โ โ Modified commit description:
โ โ 1 : <<<<<<< conflict 1 of 1
โ โ 2 : +++++++ side #1
โ โ 3 1: squashed 1
โ โ 4 1: %%%%%%% diff from base to side #2
โ โ 5 : +third
โ โ 6 : >>>>>>> conflict 1 of 1 ends
โ โ Removed regular file file2:
โ โ 1 : foo2
โ โ Removed regular file file3:
โ โ 1 : foo3
โ โ zsuskuln/3 test.user@example.com 2001-02-03 08:05:12 cce957f1 (hidden)
โ โ third
โ โ -- operation de96267cd621 snapshot working copy
โ โ Modified regular file file1:
โ โ 1 1: foo
โ โ 2 2: bar
โ โ 3: baz
โ โ Added regular file file2:
โ โ 1: foo2
โ โ Added regular file file3:
โ โ 1: foo3
โ โ zsuskuln/4 test.user@example.com 2001-02-03 08:05:11 3a2a4253 (hidden)
โ โ (empty) third
โ โ -- operation 4611a6121e8a describe commit ebec10f449ad7ab92c7293efab5e3db2d8e9fea1
โ โ Modified commit description:
โ โ 1: third
โ โ zsuskuln/5 test.user@example.com 2001-02-03 08:05:10 ebec10f4 (hidden)
โ (empty) (no description set)
โ -- operation 65c81703100d squash commits into 5878cbe03cdf599c9353e5a1a52a01f4c5e0e0fa
โ qpvuntsm/2 test.user@example.com 2001-02-03 08:05:10 69085884 (hidden)
โโโฎ squashed 1
โ โ -- operation 65c81703100d squash commits into 5878cbe03cdf599c9353e5a1a52a01f4c5e0e0fa
โ โ Modified commit description:
โ โ 1 : <<<<<<< conflict 1 of 1
โ โ 2 : %%%%%%% diff from base to side #1
โ โ 3 : +first
โ โ 4 : +++++++ side #2
โ โ 5 : second
โ โ 6 : >>>>>>> conflict 1 of 1 ends
โ โ 1: squashed 1
โ โ kkmpptxz/0 test.user@example.com 2001-02-03 08:05:10 a3759c9d (hidden)
โ โ second
โ โ -- operation a7b202f56742 snapshot working copy
โ โ Modified regular file file1:
โ โ 1 1: foo
โ โ 2: bar
โ โ kkmpptxz/1 test.user@example.com 2001-02-03 08:05:09 a5b2f625 (hidden)
โ (empty) second
โ -- operation 26f649a0cdfa new empty commit
โ Modified commit description:
โ 1: second
โ qpvuntsm/3 test.user@example.com 2001-02-03 08:05:09 5878cbe0 (hidden)
โ first
โ -- operation af15122a5868 snapshot working copy
โ Added regular file file1:
โ 1: foo
โ qpvuntsm/4 test.user@example.com 2001-02-03 08:05:08 68a50538 (hidden)
โ (empty) first
โ -- operation 75545f7ff2df describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ Modified commit description:
โ 1: first
โ qpvuntsm/5 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
[EOF]
");
}
#[test]
fn test_evolog_abandoned_op() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "");
work_dir.run_jj(["describe", "-mfile1"]).success();
work_dir.write_file("file2", "");
work_dir.run_jj(["describe", "-mfile2"]).success();
insta::assert_snapshot!(work_dir.run_jj(["evolog", "--summary"]), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:09 e1869e5d
โ file2
โ -- operation 043c31d6dd84 describe commit 32cabcfa05c604a36074d74ae59964e4e5eb18e9
โ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:09 32cabcfa (hidden)
โ file1
โ -- operation baef907e5b55 snapshot working copy
โ A file2
โ qpvuntsm/2 test.user@example.com 2001-02-03 08:05:08 cb5ebdc6 (hidden)
โ file1
โ -- operation c4cf439c43a8 describe commit 093c3c9624b6cfe22b310586f5638792aa80e6d7
โ qpvuntsm/3 test.user@example.com 2001-02-03 08:05:08 093c3c96 (hidden)
โ (no description set)
โ -- operation f41b80dc73b6 snapshot working copy
โ A file1
โ qpvuntsm/4 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
[EOF]
");
// Truncate up to the last "describe -mfile2" operation
work_dir.run_jj(["op", "abandon", "..@-"]).success();
// Unreachable predecessors are omitted, therefore the bottom commit shows
// diffs from the empty tree.
insta::assert_snapshot!(work_dir.run_jj(["evolog", "--summary"]), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:09 e1869e5d
โ file2
โ -- operation ab2192a635be describe commit 32cabcfa05c604a36074d74ae59964e4e5eb18e9
โ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:09 32cabcfa (hidden)
file1
A file1
A file2
[EOF]
");
}
#[test]
fn test_evolog_with_no_template() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["evolog", "-T"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: a value is required for '--template <TEMPLATE>' but none was supplied
For more information, try '--help'.
Hint: The following template aliases are defined:
- builtin_config_list
- builtin_config_list_detailed
- builtin_draft_commit_description
- builtin_evolog_compact
- builtin_log_comfortable
- builtin_log_compact
- builtin_log_compact_full_description
- builtin_log_detailed
- builtin_log_node
- builtin_log_node_ascii
- builtin_log_oneline
- builtin_log_redacted
- builtin_op_log_comfortable
- builtin_op_log_compact
- builtin_op_log_node
- builtin_op_log_node_ascii
- builtin_op_log_oneline
- builtin_op_log_redacted
- commit_summary_separator
- default_commit_description
- description_placeholder
- email_placeholder
- empty_commit_marker
- git_format_patch_email_headers
- name_placeholder
[EOF]
[exit status: 2]
");
}
#[test]
fn test_evolog_reversed_no_graph() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "a"]).success();
work_dir.run_jj(["describe", "-m", "b"]).success();
work_dir.run_jj(["describe", "-m", "c"]).success();
let output = work_dir.run_jj(["evolog", "--reversed", "--no-graph"]);
insta::assert_snapshot!(output, @r"
qpvuntsm/3 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
qpvuntsm/2 test.user@example.com 2001-02-03 08:05:08 b86e28cd (hidden)
(empty) a
-- operation ab34d1de4875 describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
qpvuntsm/1 test.user@example.com 2001-02-03 08:05:09 9f43967b (hidden)
(empty) b
-- operation 3851e9877d51 describe commit b86e28cd6862624ad77e1aaf31e34b2c7545bebd
qpvuntsm test.user@example.com 2001-02-03 08:05:10 b28cda4b
(empty) c
-- operation 5f4c7b5cb177 describe commit 9f43967b1cdbce4ab322cb7b4636fc0362c38373
[EOF]
");
let output = work_dir.run_jj(["evolog", "--limit=2", "--reversed", "--no-graph"]);
insta::assert_snapshot!(output, @r"
qpvuntsm/1 test.user@example.com 2001-02-03 08:05:09 9f43967b (hidden)
(empty) b
-- operation 3851e9877d51 describe commit b86e28cd6862624ad77e1aaf31e34b2c7545bebd
qpvuntsm test.user@example.com 2001-02-03 08:05:10 b28cda4b
(empty) c
-- operation 5f4c7b5cb177 describe commit 9f43967b1cdbce4ab322cb7b4636fc0362c38373
[EOF]
");
}
#[test]
fn test_evolog_reverse_with_graph() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m", "a"]).success();
work_dir.run_jj(["describe", "-m", "b"]).success();
work_dir.run_jj(["describe", "-m", "c"]).success();
work_dir
.run_jj(["new", "-r", "subject(c)", "-m", "d"])
.success();
work_dir
.run_jj(["new", "-r", "subject(c)", "-m", "e"])
.success();
work_dir
.run_jj([
"squash",
"--from=subject(d)|subject(e)",
"--to=subject(c)",
"-m",
"c+d+e",
])
.success();
let output = work_dir.run_jj(["evolog", "-r", "subject(c+d+e)", "--reversed"]);
insta::assert_snapshot!(output, @r"
โ qpvuntsm/4 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
โ (empty) (no description set)
โ -- operation 8f47435a3990 add workspace 'default'
โ qpvuntsm/3 test.user@example.com 2001-02-03 08:05:08 b86e28cd (hidden)
โ (empty) a
โ -- operation ab34d1de4875 describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
โ qpvuntsm/2 test.user@example.com 2001-02-03 08:05:09 9f43967b (hidden)
โ (empty) b
โ -- operation 3851e9877d51 describe commit b86e28cd6862624ad77e1aaf31e34b2c7545bebd
โ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:10 b28cda4b (hidden)
โ (empty) c
โ -- operation 5f4c7b5cb177 describe commit 9f43967b1cdbce4ab322cb7b4636fc0362c38373
โ โ mzvwutvl/0 test.user@example.com 2001-02-03 08:05:11 6a4ff8aa (hidden)
โโโฏ (empty) d
โ -- operation bc5f758ddd39 new empty commit
โ โ royxmykx/0 test.user@example.com 2001-02-03 08:05:12 7dea2d1d (hidden)
โโโฏ (empty) e
โ -- operation 984a0df6c274 new empty commit
โ qpvuntsm test.user@example.com 2001-02-03 08:05:13 78fdd026
(empty) c+d+e
-- operation 77d2222953aa squash commits into b28cda4b118fc50495ca34a24f030abc078d032e
[EOF]
");
let output = work_dir.run_jj(["evolog", "-rsubject(c+d+e)", "--limit=3", "--reversed"]);
insta::assert_snapshot!(output, @r"
โ mzvwutvl/0 test.user@example.com 2001-02-03 08:05:11 6a4ff8aa (hidden)
โ (empty) d
โ -- operation bc5f758ddd39 new empty commit
โ โ royxmykx/0 test.user@example.com 2001-02-03 08:05:12 7dea2d1d (hidden)
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_file_chmod_command.rs | cli/tests/test_file_chmod_command.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
#[cfg(unix)]
use std::path::Path;
use jj_lib::file_util::check_symlink_support;
use jj_lib::file_util::symlink_file;
#[cfg(unix)]
use regex::Regex;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit_with_files;
/// Assert that a file's executable bit matches the expected value.
#[cfg(unix)]
#[track_caller]
fn assert_file_executable(path: &Path, expected: bool) {
let perms = path.metadata().unwrap().permissions();
let actual = (perms.mode() & 0o100) == 0o100;
assert_eq!(actual, expected);
}
/// Set the executable bit of a file on the filesystem.
#[cfg(unix)]
#[track_caller]
pub fn set_file_executable(path: &Path, executable: bool) {
let prev_mode = path.metadata().unwrap().permissions().mode();
let is_executable = prev_mode & 0o100 != 0;
assert_ne!(executable, is_executable, "why are you calling this?");
let new_mode = if executable { 0o755 } else { 0o644 };
std::fs::set_permissions(path, PermissionsExt::from_mode(new_mode)).unwrap();
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
work_dir.run_jj(["log", "-T", "bookmarks"])
}
#[test]
fn test_chmod_regular_conflict() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
create_commit_with_files(&work_dir, "n", &["base"], &[("file", "n\n")]);
create_commit_with_files(&work_dir, "x", &["base"], &[("file", "x\n")]);
// Test chmodding a file. The effect will be visible in the conflict below.
work_dir
.run_jj(["file", "chmod", "x", "file", "-r=x"])
.success();
create_commit_with_files(&work_dir, "conflict", &["x", "n"], &[]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ conflict
โโโฎ
โ โ n
โ โ x
โโโฏ
โ base
โ
[EOF]
");
let output = work_dir.run_jj(["debug", "tree"]);
insta::assert_snapshot!(output, @r#"
file: Ok(Conflicted([Some(File { id: FileId("587be6b4c3f93f93c489c0111bba5596147a26cb"), executable: true, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("8ba3a16384aacc37d01564b28401755ce8053f51"), executable: false, copy_id: CopyId("") })]))
[EOF]
"#);
let output = work_dir.run_jj(["file", "show", "file"]);
insta::assert_snapshot!(output, @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: royxmykx 02247291 "x"
-base
+x
+++++++ zsuskuln eb0ba805 "n"
n
>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
// Test chmodding a conflict
work_dir.run_jj(["file", "chmod", "x", "file"]).success();
let output = work_dir.run_jj(["debug", "tree"]);
insta::assert_snapshot!(output, @r#"
file: Ok(Conflicted([Some(File { id: FileId("587be6b4c3f93f93c489c0111bba5596147a26cb"), executable: true, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: true, copy_id: CopyId("") }), Some(File { id: FileId("8ba3a16384aacc37d01564b28401755ce8053f51"), executable: true, copy_id: CopyId("") })]))
[EOF]
"#);
let output = work_dir.run_jj(["file", "show", "file"]);
insta::assert_snapshot!(output, @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: royxmykx 02247291 "x"
-base
+x
+++++++ zsuskuln eb0ba805 "n"
n
>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
work_dir.run_jj(["file", "chmod", "n", "file"]).success();
let output = work_dir.run_jj(["debug", "tree"]);
insta::assert_snapshot!(output, @r#"
file: Ok(Conflicted([Some(File { id: FileId("587be6b4c3f93f93c489c0111bba5596147a26cb"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("8ba3a16384aacc37d01564b28401755ce8053f51"), executable: false, copy_id: CopyId("") })]))
[EOF]
"#);
let output = work_dir.run_jj(["file", "show", "file"]);
insta::assert_snapshot!(output, @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: royxmykx 02247291 "x"
-base
+x
+++++++ zsuskuln eb0ba805 "n"
n
>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
// Unmatched paths should generate warnings
let output = work_dir.run_jj(["file", "chmod", "x", "nonexistent", "file"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
Working copy (@) now at: yostqsxw e9f9b6bd conflict | (conflict) conflict
Parent commit (@-) : royxmykx 02247291 x | x
Parent commit (@-) : zsuskuln eb0ba805 n | n
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict including an executable
[EOF]
");
}
#[test]
fn test_chmod_nonfile() {
if !check_symlink_support().unwrap() {
eprintln!("Skipping test because symlink isn't supported");
return;
}
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
symlink_file("target", work_dir.root().join("symlink")).unwrap();
let output = work_dir.run_jj(["show"]);
insta::assert_snapshot!(output, @r"
Commit ID: 82976318a088d30054540d1a11ffb4c79fb5d47e
Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
Author : Test User <test.user@example.com> (2001-02-03 08:05:08)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:08)
(no description set)
Added symlink symlink:
1: target
[EOF]
");
let output = work_dir.run_jj(["file", "chmod", "n", "symlink"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Found neither a file nor a conflict at 'symlink'.
[EOF]
[exit status: 1]
");
}
// TODO: Test demonstrating that conflicts whose *base* is not a file are
// chmod-dable
#[test]
fn test_chmod_file_dir_deletion_conflicts() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
create_commit_with_files(&work_dir, "file", &["base"], &[("file", "a\n")]);
create_commit_with_files(&work_dir, "deletion", &["base"], &[]);
work_dir.remove_file("file");
create_commit_with_files(&work_dir, "dir", &["base"], &[]);
work_dir.remove_file("file");
work_dir.create_dir("file");
// Without a placeholder file, `jj` ignores an empty directory
work_dir.write_file("file/placeholder", "");
// Create a file-dir conflict and a file-deletion conflict
create_commit_with_files(&work_dir, "file_dir", &["file", "dir"], &[]);
create_commit_with_files(&work_dir, "file_deletion", &["file", "deletion"], &[]);
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ file_deletion
โโโฎ
โ โ deletion
โ โ ร file_dir
โญโโโโค
โ โ โ dir
โ โโโฏ
โ โ file
โโโฏ
โ base
โ
[EOF]
");
// The file-dir conflict cannot be chmod-ed
let output = work_dir.run_jj(["debug", "tree", "-r=file_dir"]);
insta::assert_snapshot!(output, @r#"
file: Ok(Conflicted([Some(File { id: FileId("78981922613b2afb6025042ff6bd878ac1994e85"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), Some(Tree(TreeId("133bb38fc4e4bf6b551f1f04db7e48f04cac2877")))]))
[EOF]
"#);
let output = work_dir.run_jj(["file", "show", "-r=file_dir", "file"]);
insta::assert_snapshot!(output, @r#"
Conflict:
Removing file with id df967b96a579e45a18b8251732d16804b2e56a55 (rlvkpnrz 1792382a "base")
Adding file with id 78981922613b2afb6025042ff6bd878ac1994e85 (zsuskuln bc9cdea1 "file")
Adding tree with id 133bb38fc4e4bf6b551f1f04db7e48f04cac2877 (vruxwmqv 223cb383 "dir")
[EOF]
"#);
let output = work_dir.run_jj(["file", "chmod", "x", "file", "-r=file_dir"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Some of the sides of the conflict are not files at 'file'.
[EOF]
[exit status: 1]
");
// The file_deletion conflict can be chmod-ed
let output = work_dir.run_jj(["debug", "tree", "-r=file_deletion"]);
insta::assert_snapshot!(output, @r#"
file: Ok(Conflicted([Some(File { id: FileId("78981922613b2afb6025042ff6bd878ac1994e85"), executable: false, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: false, copy_id: CopyId("") }), None]))
[EOF]
"#);
let output = work_dir.run_jj(["file", "show", "-r=file_deletion", "file"]);
insta::assert_snapshot!(output, @r#"
<<<<<<< conflict 1 of 1
+++++++ zsuskuln bc9cdea1 "file"
a
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: royxmykx d7d39332 "deletion"
-base
>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
let output = work_dir.run_jj(["file", "chmod", "x", "file", "-r=file_deletion"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kmkuslsw 0b9a6da5 file_deletion | (conflict) file_deletion
Parent commit (@-) : zsuskuln bc9cdea1 file | file
Parent commit (@-) : royxmykx d7d39332 deletion | deletion
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict including 1 deletion and an executable
New conflicts appeared in 1 commits:
kmkuslsw 0b9a6da5 file_deletion | (conflict) file_deletion
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new kmkuslsw
Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved, you can inspect the result with `jj diff`.
Then run `jj squash` to move the resolution into the conflicted commit.
[EOF]
");
let output = work_dir.run_jj(["debug", "tree", "-r=file_deletion"]);
insta::assert_snapshot!(output, @r#"
file: Ok(Conflicted([Some(File { id: FileId("78981922613b2afb6025042ff6bd878ac1994e85"), executable: true, copy_id: CopyId("") }), Some(File { id: FileId("df967b96a579e45a18b8251732d16804b2e56a55"), executable: true, copy_id: CopyId("") }), None]))
[EOF]
"#);
let output = work_dir.run_jj(["file", "show", "-r=file_deletion", "file"]);
insta::assert_snapshot!(output, @r#"
<<<<<<< conflict 1 of 1
+++++++ zsuskuln bc9cdea1 "file"
a
%%%%%%% diff from: rlvkpnrz 1792382a "base"
\\\\\\\ to: royxmykx d7d39332 "deletion"
-base
>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
}
#[cfg(unix)]
#[test]
fn test_chmod_exec_bit_settings() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
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
let timestamp_regex = Regex::new(r"\b\d{10,}\b").unwrap();
let redact_timestamp = |output: String| {
let output = timestamp_regex.replace_all(&output, "<timestamp>");
output.into_owned()
};
// Load with an explicit "auto" value to test the deserialization.
test_env.add_config(r#"working-copy.exec-bit-change = "auto""#);
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
let output = work_dir.run_jj(["debug", "local-working-copy"]);
insta::assert_snapshot!(output.normalize_stdout_with(redact_timestamp), @r#"
Current operation: OperationId("8c58a72d1118aa7d8b1295949a7fa8c6fcda63a3c89813faf2b8ca599ceebf8adcfcbeb8f0bbb6439c86b47dd68b9cf85074c9e57214c3fb4b632e0c9e87ad65")
Current tree: MergedTree { tree_ids: Resolved(TreeId("6d5f482d15035cdd7733b1b551d1fead28d22592")), labels: Unlabeled, .. }
Normal { exec_bit: ExecBit(false) } 5 <timestamp> None "file"
[EOF]
"#); // in-repo: false, on-disk: false (1/4)
// 1. Start respecting the executable bit
test_env.add_config(r#"working-copy.exec-bit-change = "respect""#);
create_commit_with_files(&work_dir, "respect", &["base"], &[]);
set_file_executable(path, true);
let output = work_dir.run_jj(["debug", "local-working-copy"]);
insta::assert_snapshot!(output.normalize_stdout_with(redact_timestamp), @r#"
Current operation: OperationId("3a6a78820e6892164ed55680b92fa679fbb4d6acd4135c7413d1b815bedcd2c24c85ac8f4f96c96f76012f33d31ffbf50473b938feadf36fcd9c92997789aeca")
Current tree: MergedTree { tree_ids: Resolved(TreeId("5201dbafb66dc1b28b029a262e1b206f6f93df1e")), labels: Unlabeled, .. }
Normal { exec_bit: ExecBit(true) } 5 <timestamp> None "file"
[EOF]
"#); // in-repo: true, on-disk: true (2/4)
work_dir.run_jj(["file", "chmod", "n", "file"]).success();
assert_file_executable(path, false);
work_dir.run_jj(["file", "chmod", "x", "file"]).success();
assert_file_executable(path, true);
// 2. Now ignore the executable bit
create_commit_with_files(&work_dir, "ignore", &["base"], &[]);
test_env.add_config(r#"working-copy.exec-bit-change = "ignore""#);
set_file_executable(path, true);
// chmod should affect the repo state, but not the on-disk file.
work_dir.run_jj(["file", "chmod", "n", "file"]).success();
assert_file_executable(path, true);
let output = work_dir.run_jj(["debug", "local-working-copy"]);
insta::assert_snapshot!(output.normalize_stdout_with(redact_timestamp), @r#"
Current operation: OperationId("cab1801e16b54d5b413f638bdf74388520b51232c88db6b314ef64b054607ab82ae6ef0b1f707b52aa8d2131511f6f48f8ca52e465621ff38c442b0ec893f309")
Current tree: MergedTree { tree_ids: Resolved(TreeId("6d5f482d15035cdd7733b1b551d1fead28d22592")), labels: Unlabeled, .. }
Normal { exec_bit: ExecBit(true) } 5 <timestamp> None "file"
[EOF]
"#); // in-repo: false, on-disk: true (3/4)
set_file_executable(path, false);
work_dir.run_jj(["file", "chmod", "x", "file"]).success();
assert_file_executable(path, false);
let output = work_dir.run_jj(["debug", "local-working-copy"]);
insta::assert_snapshot!(output.normalize_stdout_with(redact_timestamp), @r#"
Current operation: OperationId("def8ce6211dcff6d2784d5309d36079c1cb6eeb70821ae144982c76d38ed76fedc8b84e4daddaac70f6a0aae1c301ff5b60e1baa6ac371dabd77cec3537d2c39")
Current tree: MergedTree { tree_ids: Resolved(TreeId("5201dbafb66dc1b28b029a262e1b206f6f93df1e")), labels: Unlabeled, .. }
Normal { exec_bit: ExecBit(false) } 5 <timestamp> None "file"
[EOF]
"#); // in-repo: true, on-disk: false (4/4) Yay! We've observed all possible states!
// 3. Go back to respecting the executable bit
test_env.add_config(r#"working-copy.exec-bit-change = "respect""#);
work_dir.write_file("file", "update the file so respect notices the new state\n");
assert_file_executable(path, false);
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
M file
Working copy (@) : znkkpsqq 71681768 ignore | ignore
Parent commit (@-): rlvkpnrz 1792382a base | base
[EOF]
");
let output = work_dir.run_jj(["file", "chmod", "x", "file"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: znkkpsqq ef0a25b6 ignore | ignore
Parent commit (@-) : rlvkpnrz 1792382a base | base
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
assert_file_executable(path, true);
work_dir.run_jj(["new", "base"]).success();
set_file_executable(path, true);
let output = work_dir.run_jj(["debug", "local-working-copy"]);
insta::assert_snapshot!(output.normalize_stdout_with(redact_timestamp), @r#"
Current operation: OperationId("0cce4e44f0b47cc4404f74fe164536aa57f67b8981726ce6ec88c39d79e266a2586a79d51a065906b6d8b284b39fe0ab023547f65571d1b61a97916f7f7cf4d8")
Current tree: MergedTree { tree_ids: Resolved(TreeId("5201dbafb66dc1b28b029a262e1b206f6f93df1e")), labels: Unlabeled, .. }
Normal { exec_bit: ExecBit(true) } 5 <timestamp> None "file"
[EOF]
"#);
}
#[cfg(unix)]
#[test]
fn test_chmod_exec_bit_ignore() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let path = &work_dir.root().join("file");
test_env.add_config(r#"working-copy.exec-bit-change = "ignore""#);
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
assert_file_executable(path, false);
// 1. Reverting to "in-repo: true, on-disk: false" works.
create_commit_with_files(&work_dir, "repo-x-disk-n", &["base"], &[]);
work_dir.run_jj(["file", "chmod", "x", "file"]).success();
assert_file_executable(path, false);
// Commit, update the file, then reset the file.
work_dir.run_jj(["new"]).success();
work_dir.write_file(path, "something");
work_dir.run_jj(["abandon"]).success();
// The on-disk exec bit should remain false.
assert_file_executable(path, false);
// 2. Reverting to "in-repo: false, on-disk: true" works.
create_commit_with_files(&work_dir, "repo-n-disk-x", &["base"], &[]);
set_file_executable(path, true);
work_dir.run_jj(["file", "chmod", "n", "file"]).success();
assert_file_executable(path, true);
// Commit, update the file, then reset the file.
work_dir.run_jj(["new"]).success();
work_dir.write_file(path, "something");
work_dir.run_jj(["abandon"]).success();
// The on-disk exec bit should remain true.
assert_file_executable(path, true);
}
#[cfg(unix)]
#[test]
fn test_chmod_exec_bit_ignore_then_respect() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let path = &work_dir.root().join("file");
// Start while ignoring executable bits.
test_env.add_config(r#"working-copy.exec-bit-change = "ignore""#);
create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
// Set the in-repo executable bit to true.
let output = work_dir.run_jj(["file", "chmod", "x", "file"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: rlvkpnrz cb3f99cb base | base
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
assert_file_executable(path, false);
test_env.add_config(r#"working-copy.exec-bit-change = "respect""#);
work_dir.write_file("file", "update the file so respect notices the new state\n");
// This simultaneously snapshots and updates the executable bit.
let output = work_dir.run_jj(["file", "chmod", "x", "file"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: rlvkpnrz 96872a96 base | base
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
assert_file_executable(path, true);
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_completion.rs | cli/tests/test_completion.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::ffi::OsStr;
use clap_complete::Shell;
use itertools::Itertools as _;
use test_case::test_case;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
impl TestEnvironment {
/// Runs `jj` as if shell completion had been triggered for the argument of
/// the given index.
#[must_use = "either snapshot the output or assert the exit status with .success()"]
fn complete_at<I>(&self, shell: Shell, index: usize, args: I) -> CommandOutput
where
I: IntoIterator,
I::IntoIter: ExactSizeIterator,
I::Item: AsRef<OsStr>,
{
self.work_dir("").complete_at(shell, index, args)
}
/// Run `jj` as if fish shell completion had been triggered at the last item
/// in `args`.
#[must_use = "either snapshot the output or assert the exit status with .success()"]
fn complete_fish<I>(&self, args: I) -> CommandOutput
where
I: IntoIterator,
I::IntoIter: ExactSizeIterator,
I::Item: AsRef<OsStr>,
{
self.work_dir("").complete_fish(args)
}
}
impl TestWorkDir<'_> {
/// Runs `jj` as if shell completion had been triggered for the argument of
/// the given index.
#[must_use = "either snapshot the output or assert the exit status with .success()"]
fn complete_at<I>(&self, shell: Shell, index: usize, args: I) -> CommandOutput
where
I: IntoIterator,
I::IntoIter: ExactSizeIterator,
I::Item: AsRef<OsStr>,
{
let args = args.into_iter();
assert!(
index <= args.len(),
"index out of bounds: append empty string to complete after the last argument"
);
self.run_jj_with(|cmd| {
let cmd = cmd.env("COMPLETE", shell.to_string()).args(["--", "jj"]);
match shell {
// Bash passes the whole command line except for intermediate empty tokens but
// preserves trailing empty tokens:
// `jj log <CURSOR>` => ["--", "jj", "log", ""]
// with _CLAP_COMPLETE_INDEX=2
// `jj log <CURSOR> --no-graph` => ["--", "jj", "log", "--no-graph"]
// with _CLAP_COMPLETE_INDEX=2
// `jj log --no-graph<CURSOR>` => ["--", "jj", "log", "--no-graph"]
// with _CLAP_COMPLETE_INDEX=2
// (indistinguishable from the above)
// `jj log --no-graph <CURSOR>` => ["--", "jj", "log", "--no-graph", ""]
// with _CLAP_COMPLETE_INDEX=3
Shell::Bash => {
cmd.env("_CLAP_COMPLETE_INDEX", index.to_string())
.args(args.coalesce(|a, b| {
if a.as_ref().is_empty() {
Ok(b)
} else {
Err((a, b))
}
}))
}
// Zsh passes the whole command line except for empty tokens, including trailing
// empty tokens:
// `jj log <CURSOR>` => ["--", "jj", "log"]
// with _CLAP_COMPLETE_INDEX=2
// `jj log <CURSOR> --no-graph` => ["--", "jj", "log", "--no-graph"]
// with _CLAP_COMPLETE_INDEX=2
// `jj log --no-graph<CURSOR>` => ["--", "jj", "log", "--no-graph"]
// with _CLAP_COMPLETE_INDEX=2
// (indistinguishable from the above)
// `jj log --no-graph <CURSOR>` => ["--", "jj", "log", "--no-graph"]
// with _CLAP_COMPLETE_INDEX=3
Shell::Zsh => cmd
.env("_CLAP_COMPLETE_INDEX", index.to_string())
.args(args.filter(|a| !a.as_ref().is_empty())),
// Fish truncates the command line at the cursor; empty tokens are preserved:
// `jj log <CURSOR>` => ["--", "jj", "log", ""]
// `jj log <CURSOR> --no-graph` => ["--", "jj", "log", ""]
// `jj log --no-graph<CURSOR>` => ["--", "jj", "log", "--no-graph"]
// `jj log --no-graph <CURSOR>` => ["--", "jj", "log", "--no-graph", ""]
Shell::Fish => cmd.args(args.take(index)),
_ => todo!("{shell} completion behavior not implemented yet"),
}
})
}
/// Run `jj` as if fish shell completion had been triggered at the last item
/// in `args`.
#[must_use = "either snapshot the output or assert the exit status with .success()"]
fn complete_fish<I>(&self, args: I) -> CommandOutput
where
I: IntoIterator,
I::IntoIter: ExactSizeIterator,
I::Item: AsRef<OsStr>,
{
let args = args.into_iter();
self.complete_at(Shell::Fish, args.len(), args)
}
}
#[test]
fn test_bookmark_names() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
test_env
.run_jj_in(".", ["git", "init", "--colocate", "origin"])
.success();
let origin_dir = test_env.work_dir("origin");
test_env
.run_jj_in(".", ["git", "init", "--colocate", "upstream"])
.success();
let _upstream_dir = test_env.work_dir("upstream");
work_dir
.run_jj(["bookmark", "create", "-r@", "aaa-local"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "bbb-local"])
.success();
// add various remote branches
work_dir
.run_jj(["git", "remote", "add", "origin", "../origin"])
.success();
work_dir
.run_jj(["git", "remote", "add", "upstream", "../upstream"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "aaa-tracked"])
.success();
work_dir
.run_jj(["desc", "-r", "aaa-tracked", "-m", "x"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "bbb-tracked"])
.success();
work_dir
.run_jj(["desc", "-r", "bbb-tracked", "-m", "x"])
.success();
work_dir
.run_jj(["bookmark", "track", "--remote=origin", "*-tracked"])
.success();
work_dir
.run_jj(["bookmark", "track", "--remote=upstream", "aaa-tracked"])
.success();
work_dir
.run_jj(["git", "push", "--remote=origin", "--tracked"])
.success();
work_dir
.run_jj(["git", "push", "--remote=upstream", "--tracked"])
.success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "aaa-untracked"])
.success();
origin_dir
.run_jj(["desc", "-r", "aaa-untracked", "-m", "x"])
.success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "bbb-untracked"])
.success();
origin_dir
.run_jj(["desc", "-r", "bbb-untracked", "-m", "x"])
.success();
work_dir.run_jj(["git", "fetch", "--all-remotes"]).success();
insta::assert_snapshot!(work_dir.run_jj(["bookmark", "list", "--all"]), @r"
aaa-local: qpvuntsm fe38a82d (empty) x
aaa-tracked: qpvuntsm fe38a82d (empty) x
@origin: qpvuntsm fe38a82d (empty) x
@upstream: qpvuntsm fe38a82d (empty) x
aaa-untracked@origin: rlvkpnrz 434ae005 (empty) x
bbb-local: qpvuntsm fe38a82d (empty) x
bbb-tracked: qpvuntsm fe38a82d (empty) x
@origin: qpvuntsm fe38a82d (empty) x
bbb-untracked@origin: rlvkpnrz 434ae005 (empty) x
[EOF]
");
// Every shell hook is a little different, e.g. the zsh hooks add some
// additional environment variables. But this is irrelevant for the purpose
// of testing our own logic, so it's fine to test a single shell only.
let work_dir = test_env.work_dir("repo");
let output = work_dir.complete_fish(["bookmark", "rename", ""]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-tracked x
bbb-local x
bbb-tracked x
--repository Path to repository to operate on
--ignore-working-copy Don't snapshot the working copy, and don't update it
--ignore-immutable Allow rewriting immutable commits
--at-operation Operation to load the repo at
--debug Enable debug logging
--color When to colorize output
--quiet Silence non-primary command output
--no-pager Disable the pager
--config Additional configuration options (can be repeated)
--config-file Additional configuration files (can be repeated)
--help Print help (see more with '--help')
[EOF]
");
let output = work_dir.complete_fish(["bookmark", "rename", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-tracked x
[EOF]
");
let output = work_dir.complete_fish(["bookmark", "delete", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-tracked x
[EOF]
");
let output = work_dir.complete_fish(["bookmark", "forget", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-tracked x
aaa-untracked
[EOF]
");
let output = work_dir.complete_fish(["bookmark", "list", "--bookmark", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-tracked x
aaa-untracked
[EOF]
");
let output = work_dir.complete_fish(["bookmark", "move", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-tracked x
[EOF]
");
let output = work_dir.complete_fish(["bookmark", "set", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-tracked x
[EOF]
");
let output = work_dir.complete_fish(["bookmark", "track", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-untracked x
[EOF]
");
let output = work_dir.complete_fish(["bookmark", "untrack", "a"]);
insta::assert_snapshot!(output, @r"
aaa-tracked x
[EOF]
");
let output = work_dir.complete_fish(["git", "push", "-b", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-tracked x
[EOF]
");
let output = work_dir.complete_fish(["git", "fetch", "-b", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local x
aaa-tracked x
aaa-untracked
[EOF]
");
}
#[test]
fn test_tag_names() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-mcommit1"]).success();
work_dir
.run_jj(["tag", "set", "-r@-", "aaa-local"])
.success();
work_dir
.run_jj(["tag", "set", "-r@-", "bbb-local"])
.success();
let output = work_dir.complete_fish(["tag", "set", "a"]);
insta::assert_snapshot!(output, @r"
aaa-local commit1
[EOF]
");
let output = work_dir.complete_fish(["tag", "delete", "b"]);
insta::assert_snapshot!(output, @r"
bbb-local commit1
[EOF]
");
}
#[test]
fn test_global_arg_repository_is_respected() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["bookmark", "create", "-r@", "aaa"])
.success();
let output = test_env.complete_fish(["--repository", "repo", "bookmark", "rename", "a"]);
insta::assert_snapshot!(output, @r"
aaa (no description set)
[EOF]
");
}
#[test_case(Shell::Bash; "bash")]
#[test_case(Shell::Zsh; "zsh")]
#[test_case(Shell::Fish; "fish")]
fn test_aliases_are_resolved(shell: Shell) {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["bookmark", "create", "-r@", "aaa"])
.success();
// user config alias
test_env.add_config(r#"aliases.b = ["bookmark"]"#);
test_env.add_config(r#"aliases.rlog = ["log", "--reversed"]"#);
// repo config alias
work_dir
.run_jj(["config", "set", "--repo", "aliases.b2", "['bookmark']"])
.success();
let output = work_dir.complete_at(shell, 3, ["b", "rename", "a"]);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @"aaa[EOF]");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @"aaa:(no description set)[EOF]");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
aaa (no description set)
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
let output = work_dir.complete_at(shell, 3, ["b2", "rename", "a"]);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @"aaa[EOF]");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @"aaa:(no description set)[EOF]");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
aaa (no description set)
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
let output = work_dir.complete_at(shell, 2, ["rlog", "--rev"]);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @r"
--revisions
--reversed[EOF]
");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @r"
--revisions:Which revisions to show
--reversed:Show revisions in the opposite order (older revisions first)[EOF]
");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
--revisions Which revisions to show
--reversed Show revisions in the opposite order (older revisions first)
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
}
#[test]
fn test_completions_are_generated() {
let mut test_env = TestEnvironment::default();
test_env.add_env_var("COMPLETE", "fish");
let mut insta_settings = insta::Settings::clone_current();
insta_settings.add_filter(r"(--arguments) .*", "$1 .."); // omit path to jj binary
let _guard = insta_settings.bind_to_scope();
let output = test_env.run_jj_in(".", [""; 0]);
insta::assert_snapshot!(output, @r"
complete --keep-order --exclusive --command jj --arguments ..
[EOF]
");
let output = test_env.run_jj_in(".", ["--"]);
insta::assert_snapshot!(output, @r"
complete --keep-order --exclusive --command jj --arguments ..
[EOF]
");
}
#[test]
fn test_bad_complete_env() {
let mut test_env = TestEnvironment::default();
test_env.add_env_var("COMPLETE", "badshell");
let output = test_env.run_jj_in(".", [""; 0]);
insta::assert_snapshot!(output, @"
------- stderr -------
error: unknown shell `badshell`, expected one of `bash`, `elvish`, `fish`, `powershell`, `zsh`[EOF]
[exit status: 2]
");
// Empty value of COMPLETE is ignored as is the value of "0". This could
// change if `clap` changes the way it interprets an empty COMPLETE env var.
//
// In other words, jj runs normally instead of returning completions. We get
// an error because the default jj command needs to be run in a jj repo.
test_env.add_env_var("COMPLETE", "");
let output = test_env.run_jj_in(".", [""; 0]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Hint: Use `jj -h` for a list of available commands.
Run `jj config set --user ui.default-command log` to disable this message.
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
// Same thing (normal execution) happens for a sub-command and "0"
test_env.add_env_var("COMPLETE", "0");
let output = test_env.run_jj_in(".", ["config", "list", "user.name"]);
insta::assert_snapshot!(output, @r#"
user.name = "Test User"
[EOF]
"#);
}
#[test_case(Shell::Bash; "bash")]
#[test_case(Shell::Zsh; "zsh")]
#[test_case(Shell::Fish; "fish")]
fn test_default_command_is_resolved(shell: Shell) {
let test_env = TestEnvironment::default();
let output = test_env
.complete_at(shell, 1, ["--"])
.take_stdout_n_lines(2);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @r"
--revisions
--limit
[EOF]
");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @r"
--revisions:Which revisions to show
--limit:Limit number of revisions to show
[EOF]
");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
--revisions Which revisions to show
--limit Limit number of revisions to show
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
test_env.add_config("ui.default-command = ['abandon']");
let output = test_env
.complete_at(shell, 1, ["--"])
.take_stdout_n_lines(2);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @r"
--retain-bookmarks
--restore-descendants
[EOF]
");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @r"
--retain-bookmarks:Do not delete bookmarks pointing to the revisions to abandon
--restore-descendants:Do not modify the content of the children of the abandoned commits
[EOF]
");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
--retain-bookmarks Do not delete bookmarks pointing to the revisions to abandon
--restore-descendants Do not modify the content of the children of the abandoned commits
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
test_env.add_config("ui.default-command = ['bookmark', 'move']");
let output = test_env
.complete_at(shell, 1, ["--"])
.take_stdout_n_lines(2);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @r"
--from
--to
[EOF]
");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @r"
--from:Move bookmarks from the given revisions
--to:Move bookmarks to this revision
[EOF]
");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
--from Move bookmarks from the given revisions
--to Move bookmarks to this revision
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
}
#[test_case(Shell::Bash; "bash")]
#[test_case(Shell::Zsh; "zsh")]
#[test_case(Shell::Fish; "fish")]
fn test_command_completion(shell: Shell) {
let test_env = TestEnvironment::default();
// Command names should be suggested. If the default command were expanded,
// only "log" would be listed.
let output = test_env.complete_at(shell, 1, [""]).take_stdout_n_lines(2);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @r"
abandon
absorb
[EOF]
");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @r"
abandon:Abandon a revision
absorb:Move changes from a revision into the stack of mutable revisions
[EOF]
");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
abandon Abandon a revision
absorb Move changes from a revision into the stack of mutable revisions
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
let output = test_env
.complete_at(shell, 2, ["--no-pager", ""])
.take_stdout_n_lines(2);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @r"
abandon
absorb
[EOF]
");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @r"
abandon:Abandon a revision
absorb:Move changes from a revision into the stack of mutable revisions
[EOF]
");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
abandon Abandon a revision
absorb Move changes from a revision into the stack of mutable revisions
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
let output = test_env.complete_at(shell, 1, ["b"]);
match shell {
Shell::Zsh => {
insta::assert_snapshot!(output, @"bookmark:Manage bookmarks [default alias: b][EOF]");
}
Shell::Bash => {
insta::assert_snapshot!(output, @"bookmark[EOF]");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
bookmark Manage bookmarks [default alias: b]
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
let output = test_env.complete_at(shell, 1, ["aban", "-r", "@"]);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @"abandon[EOF]");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @"abandon:Abandon a revision[EOF]");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
abandon Abandon a revision
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
}
#[test]
fn test_remote_names() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init"]).success();
test_env
.run_jj_in(
".",
["git", "remote", "add", "origin", "git@git.local:user/repo"],
)
.success();
let output = test_env.complete_fish(["git", "remote", "remove", "o"]);
insta::assert_snapshot!(output, @r"
origin
[EOF]
");
let output = test_env.complete_fish(["git", "remote", "rename", "o"]);
insta::assert_snapshot!(output, @r"
origin
[EOF]
");
let output = test_env.complete_fish(["git", "remote", "set-url", "o"]);
insta::assert_snapshot!(output, @r"
origin
[EOF]
");
let output = test_env.complete_fish(["git", "push", "--remote", "o"]);
insta::assert_snapshot!(output, @r"
origin
[EOF]
");
let output = test_env.complete_fish(["git", "fetch", "--remote", "o"]);
insta::assert_snapshot!(output, @r"
origin
[EOF]
");
let output = test_env.complete_fish(["bookmark", "list", "--remote", "o"]);
insta::assert_snapshot!(output, @r"
origin
[EOF]
");
}
#[test_case(Shell::Bash; "bash")]
#[test_case(Shell::Zsh; "zsh")]
#[test_case(Shell::Fish; "fish")]
fn test_aliases_are_completed(shell: Shell) {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let repo_path = work_dir.root().to_str().unwrap();
// user config alias
test_env.add_config(r#"aliases.user-alias = ["bookmark"]"#);
// repo config alias
work_dir
.run_jj([
"config",
"set",
"--repo",
"aliases.repo-alias",
"['bookmark']",
])
.success();
let output = work_dir.complete_at(shell, 1, ["user-al"]);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @"user-alias[EOF]");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @"user-alias[EOF]");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
user-alias
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
// make sure --repository flag is respected
let output = test_env.complete_at(shell, 3, ["--repository", repo_path, "repo-al"]);
match shell {
Shell::Bash => {
insta::assert_snapshot!(output, @"repo-alias[EOF]");
}
Shell::Zsh => {
insta::assert_snapshot!(output, @"repo-alias[EOF]");
}
Shell::Fish => {
insta::assert_snapshot!(output, @r"
repo-alias
[EOF]
");
}
_ => unimplemented!("unexpected shell '{shell}'"),
}
// cannot load aliases from --config flag
let output = test_env.complete_at(
shell,
2,
["--config=aliases.cli-alias=['bookmark']", "cli-al"],
);
assert!(
output.status.success() && output.stdout.is_empty(),
"completion expected to come back empty, but got: {output}"
);
}
#[test]
fn test_revisions() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// create remote to test remote branches
test_env.run_jj_in(".", ["git", "init", "origin"]).success();
let origin_dir = test_env.work_dir("origin");
let origin_git_repo_path = origin_dir
.root()
.join(".jj")
.join("repo")
.join("store")
.join("git");
work_dir
.run_jj([
"git",
"remote",
"add",
"origin",
origin_git_repo_path.to_str().unwrap(),
])
.success();
origin_dir
.run_jj(["b", "c", "-r@", "remote_bookmark"])
.success();
origin_dir
.run_jj(["commit", "-m", "remote_commit"])
.success();
origin_dir.run_jj(["git", "export"]).success();
work_dir.run_jj(["git", "fetch"]).success();
work_dir
.run_jj(["b", "c", "-r@", "immutable_bookmark"])
.success();
work_dir.run_jj(["commit", "-m", "immutable"]).success();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "immutable_bookmark""#);
test_env.add_config(r#"revset-aliases."siblings" = "@-+ ~@""#);
test_env.add_config(
r#"revset-aliases."alias_with_newline" = '''
roots(
conflicts()
)
'''"#,
);
work_dir.write_file("file", "A");
work_dir.run_jj(["describe", "-m", "mutable 1"]).success();
work_dir.run_jj(["describe", "-m", "mutable 2"]).success();
// Create divergent change
work_dir
.run_jj(["b", "c", "-r=at_operation(@-, @)", "mutable_bookmark"])
.success();
work_dir.run_jj(["new", "immutable_bookmark"]).success();
work_dir.write_file("file", "B");
work_dir.run_jj(["describe", "-m", "mutable 3"]).success();
work_dir.run_jj(["new", "@", "mutable_bookmark"]).success();
work_dir
.run_jj(["b", "c", "-r@", "conflicted_bookmark"])
.success();
work_dir.run_jj(["describe", "-m", "conflicted"]).success();
work_dir.run_jj(["new", "mutable_bookmark"]).success();
work_dir
.run_jj(["describe", "-m", "working_copy"])
.success();
let work_dir = test_env.work_dir("repo");
// There are _a lot_ of commands and arguments accepting revisions.
// Let's not test all of them. Having at least one test per variation of
// completion function should be sufficient.
// complete all revisions
let output = work_dir.complete_fish(["diff", "--from", ""]);
insta::assert_snapshot!(output, @r"
conflicted_bookmark conflicted
immutable_bookmark immutable
mutable_bookmark mutable 1
x working_copy
k conflicted
w mutable 3
y/0 mutable 2
y/1 mutable 1
q immutable
r remote_commit
z (no description set)
remote_bookmark@origin remote_commit
alias_with_newline roots(
siblings @-+ ~@
[EOF]
");
// complete all revisions in a revset expression
let output = work_dir.complete_fish(["log", "-r", ".."]);
insta::assert_snapshot!(output, @r"
..conflicted_bookmark conflicted
..immutable_bookmark immutable
..mutable_bookmark mutable 1
..x working_copy
..k conflicted
..w mutable 3
..y/0 mutable 2
..y/1 mutable 1
..q immutable
..r remote_commit
..z (no description set)
..remote_bookmark@origin remote_commit
..alias_with_newline roots(
..siblings @-+ ~@
[EOF]
");
// complete only mutable revisions
let output = work_dir.complete_fish(["squash", "--into", ""]);
insta::assert_snapshot!(output, @r"
conflicted_bookmark conflicted
mutable_bookmark mutable 1
x working_copy
k conflicted
w mutable 3
y/0 mutable 2
y/1 mutable 1
r remote_commit
alias_with_newline roots(
siblings @-+ ~@
[EOF]
");
// complete only mutable revisions in a revset expression
let output = work_dir.complete_fish(["abandon", "y::"]);
insta::assert_snapshot!(output, @r"
y::conflicted_bookmark conflicted
y::mutable_bookmark mutable 1
y::x working_copy
y::k conflicted
y::w mutable 3
y::y/0 mutable 2
y::y/1 mutable 1
y::r remote_commit
y::alias_with_newline roots(
y::siblings @-+ ~@
[EOF]
");
// complete remote bookmarks in a revset expression
let output = work_dir.complete_fish(["log", "-r", "remote_bookmark@"]);
insta::assert_snapshot!(output, @r"
remote_bookmark@origin remote_commit
[EOF]
");
// complete conflicted revisions in a revset expression
let output = work_dir.complete_fish(["resolve", "-r", ""]);
insta::assert_snapshot!(output, @r"
conflicted_bookmark conflicted
k conflicted
alias_with_newline roots(
siblings @-+ ~@
[EOF]
");
// complete args of the default command
test_env.add_config("ui.default-command = 'log'");
let output = work_dir.complete_fish(["-r", ""]);
insta::assert_snapshot!(output, @r"
conflicted_bookmark conflicted
immutable_bookmark immutable
mutable_bookmark mutable 1
x working_copy
k conflicted
w mutable 3
y/0 mutable 2
y/1 mutable 1
q immutable
r remote_commit
z (no description set)
remote_bookmark@origin remote_commit
alias_with_newline roots(
siblings @-+ ~@
[EOF]
");
// Begin testing `jj git push --named`
// 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"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.complete_fish(["git", "push", "--named", "a="]);
insta::assert_snapshot!(output, @r"
a=conflicted_bookmark conflicted
a=immutable_bookmark immutable
a=mutable_bookmark mutable 1
a=x working_copy
a=k conflicted
a=w mutable 3
a=y/0 mutable 2
a=y/1 mutable 1
a=q immutable
a=r remote_commit
a=z (no description set)
a=remote_bookmark@origin remote_commit
a=alias_with_newline roots(
a=siblings @-+ ~@
[EOF]
");
let output = work_dir.complete_fish(["git", "push", "--named", "a=a"]);
insta::assert_snapshot!(output, @r"
a=alias_with_newline roots(
[EOF]
");
}
#[test]
fn test_operations() {
let test_env = TestEnvironment::default();
// suppress warnings on stderr of completions for invalid args
test_env.add_config("ui.default-command = 'log'");
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_fix_command.rs | cli/tests/test_fix_command.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt as _;
use std::path::PathBuf;
use indoc::formatdoc;
use indoc::indoc;
use jj_lib::file_util::symlink_file;
use crate::common::TestEnvironment;
use crate::common::to_toml_value;
fn set_up_fake_formatter(test_env: &mut TestEnvironment, args: &[&str]) {
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
test_env.add_config(formatdoc! {"
[fix.tools.fake-formatter]
command = {command}
patterns = ['all()']
",
command = toml_edit::Value::from_iter(
[formatter_path.to_str().unwrap()]
.iter()
.chain(args)
.copied()
)
});
test_env.add_paths_to_normalize(formatter_path, "$FAKE_FORMATTER_PATH");
}
#[test]
fn test_config_no_tools() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "content\n");
let output = work_dir.run_jj(["fix"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: No `fix.tools` are configured
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["file", "show", "file", "-r", "@"]);
insta::assert_snapshot!(output, @r"
content
[EOF]
");
}
#[test]
fn test_config_nonexistent_tool() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
test_env.add_config(
r###"
[fix.tools.my-tool]
command = ["nonexistent-fix-tool-binary"]
patterns = ["glob:**"]
"###,
);
work_dir.write_file("file", "content\n");
let output = work_dir.run_jj(["fix"]);
// We inform the user about the non-existent tool
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Failed to start `nonexistent-fix-tool-binary`
Fixed 0 commits of 1 checked.
Nothing changed.
[EOF]
");
}
#[test]
fn test_config_multiple_tools() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
let formatter = to_toml_value(formatter_path.to_str().unwrap());
test_env.add_config(format!(
r###"
[fix.tools.tool-1]
command = [{formatter}, "--uppercase"]
patterns = ["foo"]
[fix.tools.tool-2]
command = [{formatter}, "--lowercase"]
patterns = ["bar"]
"###,
));
work_dir.write_file("foo", "Foo\n");
work_dir.write_file("bar", "Bar\n");
work_dir.write_file("baz", "Baz\n");
work_dir.run_jj(["fix"]).success();
let output = work_dir.run_jj(["file", "show", "foo", "-r", "@"]);
insta::assert_snapshot!(output, @r"
FOO
[EOF]
");
let output = work_dir.run_jj(["file", "show", "bar", "-r", "@"]);
insta::assert_snapshot!(output, @r"
bar
[EOF]
");
let output = work_dir.run_jj(["file", "show", "baz", "-r", "@"]);
insta::assert_snapshot!(output, @r"
Baz
[EOF]
");
}
#[test]
fn test_config_multiple_tools_with_same_name() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
let formatter = to_toml_value(formatter_path.to_str().unwrap());
// Multiple definitions with the same `name` are not allowed, because it is
// likely to be a mistake, and mistakes are risky when they rewrite files.
test_env.add_config(format!(
r###"
[fix.tools.my-tool]
command = [{formatter}, "--uppercase"]
patterns = ["foo"]
[fix.tools.my-tool]
command = [{formatter}, "--lowercase"]
patterns = ["bar"]
"###,
));
work_dir.write_file("foo", "Foo\n");
work_dir.write_file("bar", "Bar\n");
let output = work_dir.run_jj(["fix"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Configuration cannot be parsed as TOML document
Caused by: TOML parse error at line 6, column 20
|
6 | [fix.tools.my-tool]
| ^^^^^^^
duplicate key
Hint: Check the config file: $TEST_ENV/config/config0002.toml
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
test_env.set_config_path("/dev/null");
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["file", "show", "foo", "-r", "@"]);
insta::assert_snapshot!(output, @r"
Foo
[EOF]
");
let output = work_dir.run_jj(["file", "show", "bar", "-r", "@"]);
insta::assert_snapshot!(output, @r"
Bar
[EOF]
");
}
#[test]
fn test_config_disabled_tools() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
let formatter = to_toml_value(formatter_path.to_str().unwrap());
test_env.add_config(format!(
r###"
[fix.tools.tool-1]
# default is enabled
command = [{formatter}, "--uppercase"]
patterns = ["foo"]
[fix.tools.tool-2]
enabled = true
command = [{formatter}, "--lowercase"]
patterns = ["bar"]
[fix.tools.tool-3]
enabled = false
command = [{formatter}, "--lowercase"]
patterns = ["baz"]
"###
));
work_dir.write_file("foo", "Foo\n");
work_dir.write_file("bar", "Bar\n");
work_dir.write_file("baz", "Baz\n");
work_dir.run_jj(["fix"]).success();
let output = work_dir.run_jj(["file", "show", "foo", "-r", "@"]);
insta::assert_snapshot!(output, @r"
FOO
[EOF]
");
let output = work_dir.run_jj(["file", "show", "bar", "-r", "@"]);
insta::assert_snapshot!(output, @r"
bar
[EOF]
");
let output = work_dir.run_jj(["file", "show", "baz", "-r", "@"]);
insta::assert_snapshot!(output, @r"
Baz
[EOF]
");
}
#[test]
fn test_config_disabled_tools_warning_when_all_tools_are_disabled() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
let formatter = to_toml_value(formatter_path.to_str().unwrap());
test_env.add_config(format!(
r###"
[fix.tools.tool-2]
enabled = false
command = [{formatter}, "--lowercase"]
patterns = ["bar"]
"###
));
work_dir.write_file("bar", "Bar\n");
let output = work_dir.run_jj(["fix"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: At least one entry of `fix.tools` must be enabled.
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_config_tables_overlapping_patterns() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
let formatter = to_toml_value(formatter_path.to_str().unwrap());
test_env.add_config(format!(
r###"
[fix.tools.tool-1]
command = [{formatter}, "--append", "tool-1"]
patterns = ["foo", "bar"]
[fix.tools.tool-2]
command = [{formatter}, "--append", "tool-2"]
patterns = ["bar", "baz"]
"###,
));
work_dir.write_file("foo", "foo\n");
work_dir.write_file("bar", "bar\n");
work_dir.write_file("baz", "baz\n");
work_dir.run_jj(["fix"]).success();
let output = work_dir.run_jj(["file", "show", "foo", "-r", "@"]);
insta::assert_snapshot!(output, @r"
foo
tool-1[EOF]
");
let output = work_dir.run_jj(["file", "show", "bar", "-r", "@"]);
insta::assert_snapshot!(output, @r"
bar
tool-1tool-2[EOF]
");
let output = work_dir.run_jj(["file", "show", "baz", "-r", "@"]);
insta::assert_snapshot!(output, @r"
baz
tool-2[EOF]
");
}
#[test]
fn test_config_tables_all_commands_missing() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
test_env.add_config(
r###"
[fix.tools.my-tool-missing-command-1]
patterns = ["foo"]
[fix.tools.my-tool-missing-command-2]
patterns = ['glob:"ba*"']
"###,
);
work_dir.write_file("foo", "foo\n");
let output = work_dir.run_jj(["fix"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
------- stderr -------
Config error: Invalid type or value for fix.tools.my-tool-missing-command-1
Caused by: missing field `command`
Hint: Check the config file: $TEST_ENV/config/config0002.toml
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["file", "show", "foo", "-r", "@"]);
insta::assert_snapshot!(output, @r"
foo
[EOF]
");
}
#[test]
fn test_config_tables_some_commands_missing() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
let formatter = to_toml_value(formatter_path.to_str().unwrap());
test_env.add_config(format!(
r###"
[fix.tools.tool-1]
command = [{formatter}, "--uppercase"]
patterns = ["foo"]
[fix.tools.my-tool-missing-command]
patterns = ['bar']
"###,
));
work_dir.write_file("foo", "foo\n");
let output = work_dir.run_jj(["fix"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
------- stderr -------
Config error: Invalid type or value for fix.tools.my-tool-missing-command
Caused by: missing field `command`
Hint: Check the config file: $TEST_ENV/config/config0002.toml
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["file", "show", "foo", "-r", "@"]);
insta::assert_snapshot!(output, @r"
foo
[EOF]
");
}
#[test]
fn test_config_tables_empty_patterns_list() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
let formatter = to_toml_value(formatter_path.to_str().unwrap());
test_env.add_config(format!(
r###"
[fix.tools.my-tool-empty-patterns]
command = [{formatter}, "--uppercase"]
patterns = []
"###,
));
work_dir.write_file("foo", "foo\n");
let output = work_dir.run_jj(["fix"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 0 commits of 1 checked.
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["file", "show", "foo", "-r", "@"]);
insta::assert_snapshot!(output, @r"
foo
[EOF]
");
}
#[test]
fn test_config_filesets() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
let formatter = to_toml_value(formatter_path.to_str().unwrap());
test_env.add_config(format!(
r###"
[fix.tools.my-tool-match-one]
command = [{formatter}, "--uppercase"]
patterns = ['glob:"a*"']
[fix.tools.my-tool-match-two]
command = [{formatter}, "--reverse"]
patterns = ['glob:"b*"']
[fix.tools.my-tool-match-none]
command = [{formatter}, "--append", "SHOULD NOT APPEAR"]
patterns = ['glob:"this-doesnt-match-anything-*"']
"###,
));
work_dir.write_file("a1", "a1\n");
work_dir.write_file("b1", "b1\n");
work_dir.write_file("b2", "b2\n");
work_dir.run_jj(["fix"]).success();
let output = work_dir.run_jj(["file", "show", "a1", "-r", "@"]);
insta::assert_snapshot!(output, @r"
A1
[EOF]
");
let output = work_dir.run_jj(["file", "show", "b1", "-r", "@"]);
insta::assert_snapshot!(output, @r"
1b[EOF]
");
let output = work_dir.run_jj(["file", "show", "b2", "-r", "@"]);
insta::assert_snapshot!(output, @r"
2b[EOF]
");
}
#[test]
fn test_relative_paths() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
assert!(formatter_path.is_file());
let formatter = to_toml_value(formatter_path.to_str().unwrap());
test_env.add_config(format!(
r###"
[fix.tools.tool]
command = [{formatter}, "--stdout", "Fixed!"]
patterns = ['glob:"foo*"']
"###,
));
let sub_dir = work_dir.create_dir("dir");
work_dir.write_file("foo1", "unfixed\n");
work_dir.write_file("foo2", "unfixed\n");
work_dir.write_file("dir/foo3", "unfixed\n");
// Positional arguments are cwd-relative, but the configured patterns are
// repo-relative, so this command fixes the empty intersection of those
// filesets.
sub_dir.run_jj(["fix", "foo3"]).success();
let output = work_dir.run_jj(["file", "show", "foo1", "-r", "@"]);
insta::assert_snapshot!(output, @r"
unfixed
[EOF]
");
let output = work_dir.run_jj(["file", "show", "foo2", "-r", "@"]);
insta::assert_snapshot!(output, @r"
unfixed
[EOF]
");
let output = work_dir.run_jj(["file", "show", "dir/foo3", "-r", "@"]);
insta::assert_snapshot!(output, @r"
unfixed
[EOF]
");
// Positional arguments can specify a subset of the configured fileset.
sub_dir.run_jj(["fix", "../foo1"]).success();
let output = work_dir.run_jj(["file", "show", "foo1", "-r", "@"]);
insta::assert_snapshot!(output, @"Fixed![EOF]");
let output = work_dir.run_jj(["file", "show", "foo2", "-r", "@"]);
insta::assert_snapshot!(output, @r"
unfixed
[EOF]
");
let output = work_dir.run_jj(["file", "show", "dir/foo3", "-r", "@"]);
insta::assert_snapshot!(output, @r"
unfixed
[EOF]
");
// 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]");
let output = work_dir.run_jj(["file", "show", "foo2", "-r", "@"]);
insta::assert_snapshot!(output, @"Fixed![EOF]");
let output = work_dir.run_jj(["file", "show", "dir/foo3", "-r", "@"]);
insta::assert_snapshot!(output, @r"
unfixed
[EOF]
");
// The output filtered to a non-existent file should display a warning.
let output = work_dir.run_jj(["fix", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
Fixed 0 commits of 1 checked.
Nothing changed.
[EOF]
");
}
#[test]
fn test_relative_tool_path_from_subdirectory() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Copy the fake-formatter into the workspace as a relative tool
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
let formatter_name = formatter_path.file_name().unwrap().to_str().unwrap();
let tool_dir = work_dir.create_dir("tools");
let workspace_formatter_path = tool_dir.root().join(formatter_name);
std::fs::copy(formatter_path, &workspace_formatter_path).unwrap();
work_dir.write_file(".gitignore", "tools/\n");
let formatter_relative_path = PathBuf::from_iter(["$root", "tools", formatter_name]);
test_env.add_config(format!(
r###"
[fix.tools.a]
command = [{path}, "--uppercase"]
patterns = ['glob:"**/*.txt"']
"###,
path = to_toml_value(formatter_relative_path.to_str().unwrap())
));
// Create a test file and subdirectory
work_dir.write_file("test.txt", "hello world\n");
let sub_dir = work_dir.create_dir("subdir");
work_dir.write_file("subdir/nested.txt", "nested content\n");
work_dir.run_jj(["debug", "snapshot"]).success();
let setup_opid = work_dir.current_operation_id();
// Run fix from workspace root
let output = work_dir.run_jj(["fix"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 1 commits of 1 checked.
Working copy (@) now at: qpvuntsm 57a27b36 (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 2 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["file", "show", "test.txt", "-r", "@"]);
insta::assert_snapshot!(output, @r"
HELLO WORLD
[EOF]
");
let output = work_dir.run_jj(["file", "show", "subdir/nested.txt", "-r", "@"]);
insta::assert_snapshot!(output, @r"
NESTED CONTENT
[EOF]
");
// Reset so the fix tools should have an effect again
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Run fix from the subdirectory
let output = sub_dir.run_jj(["fix"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 1 commits of 1 checked.
Working copy (@) now at: qpvuntsm 05404d5b (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 2 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["file", "show", "test.txt", "-r", "@"]);
insta::assert_snapshot!(output, @r"
HELLO WORLD
[EOF]
");
let output = work_dir.run_jj(["file", "show", "subdir/nested.txt", "-r", "@"]);
insta::assert_snapshot!(output, @r"
NESTED CONTENT
[EOF]
");
}
#[test]
fn test_fix_empty_commit() {
let mut test_env = TestEnvironment::default();
set_up_fake_formatter(&mut test_env, &["--uppercase"]);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["fix", "-s", "@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 0 commits of 1 checked.
Nothing changed.
[EOF]
");
}
#[test]
fn test_fix_leaf_commit() {
let mut test_env = TestEnvironment::default();
set_up_fake_formatter(&mut test_env, &["--uppercase"]);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "unaffected");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "affected");
let output = work_dir.run_jj(["fix", "-s", "@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 1 commits of 1 checked.
Working copy (@) now at: rlvkpnrz f5c11961 (no description set)
Parent commit (@-) : qpvuntsm b37955c0 (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file", "-r", "@-"]);
insta::assert_snapshot!(output, @"unaffected[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "@"]);
insta::assert_snapshot!(output, @"AFFECTED[EOF]");
}
#[test]
fn test_fix_parent_commit() {
let mut test_env = TestEnvironment::default();
set_up_fake_formatter(&mut test_env, &["--uppercase"]);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Using one file name for all commits adds coverage of some possible bugs.
work_dir.write_file("file", "parent");
work_dir
.run_jj(["bookmark", "create", "-r@", "parent"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "child1");
work_dir
.run_jj(["bookmark", "create", "-r@", "child1"])
.success();
work_dir.run_jj(["new", "-r", "parent"]).success();
work_dir.write_file("file", "child2");
work_dir
.run_jj(["bookmark", "create", "-r@", "child2"])
.success();
let output = work_dir.run_jj(["fix", "-s", "parent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 3 commits of 3 checked.
Working copy (@) now at: mzvwutvl e7ba6d31 child2 | (no description set)
Parent commit (@-) : qpvuntsm 49f1ddd5 parent | (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file", "-r", "parent"]);
insta::assert_snapshot!(output, @"PARENT[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "child1"]);
insta::assert_snapshot!(output, @"CHILD1[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "child2"]);
insta::assert_snapshot!(output, @"CHILD2[EOF]");
}
#[test]
fn test_fix_sibling_commit() {
let mut test_env = TestEnvironment::default();
set_up_fake_formatter(&mut test_env, &["--uppercase"]);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "parent");
work_dir
.run_jj(["bookmark", "create", "-r@", "parent"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "child1");
work_dir
.run_jj(["bookmark", "create", "-r@", "child1"])
.success();
work_dir.run_jj(["new", "-r", "parent"]).success();
work_dir.write_file("file", "child2");
work_dir
.run_jj(["bookmark", "create", "-r@", "child2"])
.success();
let output = work_dir.run_jj(["fix", "-s", "child1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 1 commits of 1 checked.
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file", "-r", "parent"]);
insta::assert_snapshot!(output, @"parent[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "child1"]);
insta::assert_snapshot!(output, @"CHILD1[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "child2"]);
insta::assert_snapshot!(output, @"child2[EOF]");
}
#[test]
fn test_fix_descendant_commits() {
let mut test_env = TestEnvironment::default();
set_up_fake_formatter(&mut test_env, &["--uppercase"]);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("parent", "parent");
work_dir
.run_jj(["bookmark", "create", "-r@", "parent"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("child1", "child1");
work_dir
.run_jj(["bookmark", "create", "-r@", "child1"])
.success();
work_dir.run_jj(["new", "-r", "parent"]).success();
work_dir.write_file("child2", "child2");
work_dir
.run_jj(["bookmark", "create", "-r@", "child2"])
.success();
let output = work_dir.run_jj(["fix", "-s", "parent", "child1", "child2", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
Fixed 2 commits of 3 checked.
Working copy (@) now at: mzvwutvl afe0ade0 child2 | (no description set)
Parent commit (@-) : qpvuntsm c9cb6288 parent | (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["file", "show", "parent", "-r", "parent"]);
insta::assert_snapshot!(output, @"parent[EOF]");
let output = work_dir.run_jj(["file", "show", "child1", "-r", "child1"]);
insta::assert_snapshot!(output, @"CHILD1[EOF]");
let output = work_dir.run_jj(["file", "show", "child2", "-r", "child2"]);
insta::assert_snapshot!(output, @"CHILD2[EOF]");
}
#[test]
fn test_default_revset() {
let mut test_env = TestEnvironment::default();
set_up_fake_formatter(&mut test_env, &["--uppercase"]);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "trunk1");
work_dir
.run_jj(["bookmark", "create", "-r@", "trunk1"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "trunk2");
work_dir
.run_jj(["bookmark", "create", "-r@", "trunk2"])
.success();
work_dir.run_jj(["new", "trunk1"]).success();
work_dir.write_file("file", "foo");
work_dir
.run_jj(["bookmark", "create", "-r@", "foo"])
.success();
work_dir.run_jj(["new", "trunk1"]).success();
work_dir.write_file("file", "bar1");
work_dir
.run_jj(["bookmark", "create", "-r@", "bar1"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "bar2");
work_dir
.run_jj(["bookmark", "create", "-r@", "bar2"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "bar3");
work_dir
.run_jj(["bookmark", "create", "-r@", "bar3"])
.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).
test_env.add_config(r#"revset-aliases."immutable_heads()" = "trunk2""#);
let output = work_dir.run_jj(["fix"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 3 commits of 3 checked.
Working copy (@) now at: yostqsxw 932b950d bar2 | (no description set)
Parent commit (@-) : yqosqzyt 8a37ed67 bar1 | (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file", "-r", "trunk1"]);
insta::assert_snapshot!(output, @"trunk1[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "trunk2"]);
insta::assert_snapshot!(output, @"trunk2[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "foo"]);
insta::assert_snapshot!(output, @"foo[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "bar1"]);
insta::assert_snapshot!(output, @"BAR1[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "bar2"]);
insta::assert_snapshot!(output, @"BAR2[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "bar3"]);
insta::assert_snapshot!(output, @"BAR3[EOF]");
}
#[test]
fn test_custom_default_revset() {
let mut test_env = TestEnvironment::default();
set_up_fake_formatter(&mut test_env, &["--uppercase"]);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "foo");
work_dir
.run_jj(["bookmark", "create", "-r@", "foo"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "bar");
work_dir
.run_jj(["bookmark", "create", "-r@", "bar"])
.success();
// Check out a different commit so that the schema default `reachable(@,
// mutable())` would behave differently from our customized default.
work_dir.run_jj(["new", "-r", "foo"]).success();
test_env.add_config(r#"revsets.fix = "bar""#);
let output = work_dir.run_jj(["fix"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 1 commits of 1 checked.
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file", "-r", "foo"]);
insta::assert_snapshot!(output, @"foo[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "bar"]);
insta::assert_snapshot!(output, @"BAR[EOF]");
}
#[test]
fn test_fix_immutable_commit() {
let mut test_env = TestEnvironment::default();
set_up_fake_formatter(&mut test_env, &["--uppercase"]);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "immutable");
work_dir
.run_jj(["bookmark", "create", "-r@", "immutable"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "mutable");
work_dir
.run_jj(["bookmark", "create", "-r@", "mutable"])
.success();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "immutable""#);
let output = work_dir.run_jj(["fix", "-s", "immutable"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit a86b2eccaaab is immutable
Hint: Could not modify commit: qpvuntsm a86b2ecc immutable | (no description set)
Hint: Immutable commits are used to protect shared history.
Hint: For more information, see:
- https://docs.jj-vcs.dev/latest/config/#set-of-immutable-commits
- `jj help -k config`, "Set of immutable commits"
Hint: This operation would rewrite 1 immutable commits.
[EOF]
[exit status: 1]
"#);
let output = work_dir.run_jj(["file", "show", "file", "-r", "immutable"]);
insta::assert_snapshot!(output, @"immutable[EOF]");
let output = work_dir.run_jj(["file", "show", "file", "-r", "mutable"]);
insta::assert_snapshot!(output, @"mutable[EOF]");
}
#[test]
fn test_fix_empty_file() {
let mut test_env = TestEnvironment::default();
set_up_fake_formatter(&mut test_env, &["--uppercase"]);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "");
let output = work_dir.run_jj(["fix", "-s", "@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Fixed 0 commits of 1 checked.
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file", "-r", "@"]);
insta::assert_snapshot!(output, @"");
}
#[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_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.
let mut large_contents = b"A".repeat(0x800_000);
large_contents.push(b'\n');
work_dir.write_file("file", &large_contents);
work_dir
.run_jj([
"config",
"set",
"--repo",
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_abandon_command.rs | cli/tests/test_abandon_command.rs | // Copyright 2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit;
#[test]
fn test_basics() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &[]);
create_commit(&work_dir, "d", &["c"]);
create_commit(&work_dir, "e", &["a", "d"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [znk] e
โโโฎ
โ โ [vru] d
โ โ [roy] c
โ โ โ [zsu] b
โโโโโฏ
โ โ [rlv] a
โโโฏ
โ [zzz]
[EOF]
");
let setup_opid = work_dir.current_operation_id();
let output = work_dir.run_jj(["abandon", "--retain-bookmarks", "d"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
vruxwmqv 636920e4 d | d
Rebased 1 descendant commits onto parents of abandoned commits
Working copy (@) now at: znkkpsqq 38e96a1f e | e
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Parent commit (@-) : royxmykx c12952d9 c d | c
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [znk] e
โโโฎ
โ โ [roy] c d
โ โ โ [zsu] b
โโโโโฏ
โ โ [rlv] a
โโโฏ
โ [zzz]
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["abandon", "--retain-bookmarks"]); // abandons `e`
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
znkkpsqq 03e0d4bf e | e
Working copy (@) now at: nkmrtpmo 179731fc (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a e?? | a
Parent commit (@-) : vruxwmqv 636920e4 d e?? | d
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [nkm]
โโโฎ
โ โ [vru] d e??
โ โ [roy] c
โ โ โ [zsu] b
โโโโโฏ
โ โ [rlv] a e??
โโโฏ
โ [zzz]
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["abandon", "descendants(d)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 2 commits:
znkkpsqq 03e0d4bf e | e
vruxwmqv 636920e4 d | d
Deleted bookmarks: d, e
Working copy (@) now at: xtnwkqum 1c70f4d2 (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Parent commit (@-) : royxmykx c12952d9 c | c
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [xtn]
โโโฎ
โ โ [roy] c
โ โ โ [zsu] b
โโโโโฏ
โ โ [rlv] a
โโโฏ
โ [zzz]
[EOF]
");
// Test abandoning the same commit twice directly
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["abandon", "-rb", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
zsuskuln 123b4d91 b | b
Deleted bookmarks: b
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [znk] e
โโโฎ
โ โ [vru] d
โ โ [roy] c
โ โ [rlv] a
โโโฏ
โ [zzz]
[EOF]
");
// Test abandoning the same commit twice indirectly
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["abandon", "d::", "e"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 2 commits:
znkkpsqq 03e0d4bf e | e
vruxwmqv 636920e4 d | d
Deleted bookmarks: d, e
Working copy (@) now at: xlzxqlsl 55d5c4c2 (empty) (no description set)
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Parent commit (@-) : royxmykx c12952d9 c | c
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [xlz]
โโโฎ
โ โ [roy] c
โ โ โ [zsu] b
โโโโโฏ
โ โ [rlv] a
โโโฏ
โ [zzz]
[EOF]
");
let output = work_dir.run_jj(["abandon", "none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No revisions to abandon.
[EOF]
");
}
#[test]
fn test_abandon_many() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
for i in 0..10 {
work_dir.run_jj(["new", &format!("-mcommit{i}")]).success();
}
// The list of commits should be elided.
let output = work_dir.run_jj(["abandon", ".."]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 11 commits:
kpqxywon 6faec5d1 (empty) commit9
znkkpsqq 80f67a53 (empty) commit8
yostqsxw 8bd72fcc (empty) commit7
vruxwmqv 06c46771 (empty) commit6
yqosqzyt 168813e3 (empty) commit5
royxmykx bd8c3571 (empty) commit4
mzvwutvl 57958fa0 (empty) commit3
zsuskuln 59515644 (empty) commit2
kkmpptxz a969596d (empty) commit1
rlvkpnrz 02fe38c9 (empty) commit0
...
Working copy (@) now at: kmkuslsw a36a913b (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
}
// This behavior illustrates https://github.com/jj-vcs/jj/issues/2600.
// See also the corresponding test in `test_rebase_command`
#[test]
fn test_bug_2600() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
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.
create_commit(&work_dir, "nottherootcommit", &[]);
create_commit(&work_dir, "base", &["nottherootcommit"]);
create_commit(&work_dir, "a", &["base"]);
create_commit(&work_dir, "b", &["base", "a"]);
create_commit(&work_dir, "c", &["b"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [znk] c
โ [vru] b
โโโฎ
โ โ [roy] a
โโโฏ
โ [zsu] base
โ [rlv] nottherootcommit
โ [zzz]
[EOF]
");
let setup_opid = work_dir.current_operation_id();
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["abandon", "base"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
zsuskuln 67c2f714 base | base
Deleted bookmarks: base
Rebased 3 descendant commits onto parents of abandoned commits
Working copy (@) now at: znkkpsqq c1223866 c | c
Parent commit (@-) : vruxwmqv 1dfaa834 b | b
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.
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [znk] c
โ [vru] b
โโโฎ
โ โ [roy] a
โโโฏ
โ [rlv] nottherootcommit
โ [zzz]
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["abandon", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
royxmykx 183dbbca a | a
Deleted bookmarks: a
Rebased 2 descendant commits onto parents of abandoned commits
Working copy (@) now at: znkkpsqq f863da3f c | c
Parent commit (@-) : vruxwmqv d7aed853 b | b
Added 0 files, modified 0 files, removed 1 files
[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".
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [znk] c
โ [vru] b
โ [zsu] base
โ [rlv] nottherootcommit
โ [zzz]
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["abandon", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
vruxwmqv cedee197 b | b
Deleted bookmarks: b
Rebased 1 descendant commits onto parents of abandoned commits
Working copy (@) now at: znkkpsqq 4dc308fb c | c
Parent commit (@-) : zsuskuln 67c2f714 base | base
Parent commit (@-) : royxmykx 183dbbca a | a
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
// Commit "c" should inherit the parents from the abndoned commit "b".
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [znk] c
โโโฎ
โ โ [roy] a
โโโฏ
โ [zsu] base
โ [rlv] nottherootcommit
โ [zzz]
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// ========= Reminder of the setup ===========
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [znk] c
โ [vru] b
โโโฎ
โ โ [roy] a
โโโฏ
โ [zsu] base
โ [rlv] nottherootcommit
โ [zzz]
[EOF]
");
let output = work_dir.run_jj(["abandon", "--retain-bookmarks", "a", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 2 commits:
vruxwmqv cedee197 b | b
royxmykx 183dbbca a | a
Rebased 1 descendant commits onto parents of abandoned commits
Working copy (@) now at: znkkpsqq b350f44b c | c
Parent commit (@-) : zsuskuln 67c2f714 a b base | base
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.
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [znk] c
โ [zsu] a b base
โ [rlv] nottherootcommit
โ [zzz]
[EOF]
");
let output = work_dir.run_jj(["bookmark", "list", "b"]);
insta::assert_snapshot!(output, @r"
b: zsuskuln 67c2f714 base
[EOF]
");
}
#[test]
fn test_bug_2600_rootcommit_special_case() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Set up like `test_bug_2600`, but without the `nottherootcommit` commit.
create_commit(&work_dir, "base", &[]);
create_commit(&work_dir, "a", &["base"]);
create_commit(&work_dir, "b", &["base", "a"]);
create_commit(&work_dir, "c", &["b"]);
// Setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ [vru] c
โ [roy] b
โโโฎ
โ โ [zsu] a
โโโฏ
โ [rlv] base
โ [zzz]
[EOF]
");
// Now, the test
let output = work_dir.run_jj(["abandon", "base"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The Git backend does not support creating merge commits with the root commit as one of the parents.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_double_abandon() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
create_commit(&work_dir, "a", &[]);
// Test the setup
insta::assert_snapshot!(work_dir.run_jj(["log", "--no-graph", "-r", "a"]), @r"
rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a 7d980be7
a
[EOF]
");
let commit_id = work_dir
.run_jj(["log", "--no-graph", "--color=never", "-T=commit_id", "-r=a"])
.success()
.stdout
.into_raw();
let output = work_dir.run_jj(["abandon", &commit_id]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
rlvkpnrz 7d980be7 a | a
Deleted bookmarks: a
Working copy (@) now at: royxmykx 0cff017c (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
let output = work_dir.run_jj(["abandon", &commit_id]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Skipping 1 revisions that are already hidden.
No revisions to abandon.
[EOF]
");
}
#[test]
fn test_abandon_restore_descendants() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "foo\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "bar\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "baz\n");
// Remove the commit containing "bar"
let output = work_dir.run_jj(["abandon", "-r@-", "--restore-descendants"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
rlvkpnrz b23f92c3 (no description set)
Rebased 1 descendant commits (while preserving their content) onto parents of abandoned commits
Working copy (@) now at: kkmpptxz 2b575035 (no description set)
Parent commit (@-) : qpvuntsm d0c049cd (no description set)
[EOF]
");
let output = work_dir.run_jj(["diff", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file b/file
index 257cc5642c..76018072e0 100644
--- a/file
+++ b/file
@@ -1,1 +1,1 @@
-foo
+baz
[EOF]
");
}
#[test]
fn test_abandon_tracking_bookmarks() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "remote"]).success();
let remote_dir = test_env.work_dir("remote");
remote_dir
.run_jj(["bookmark", "set", "-r@", "foo"])
.success();
remote_dir.run_jj(["git", "export"]).success();
// Create colocated Git repo which may have @git tracking bookmarks
test_env
.run_jj_in(
".",
[
"git",
"clone",
"--colocate",
"--config=remotes.origin.auto-track-bookmarks='*'",
"remote/.jj/repo/store/git",
"local",
],
)
.success();
let local_dir = test_env.work_dir("local");
local_dir
.run_jj(["bookmark", "set", "-r@", "bar"])
.success();
insta::assert_snapshot!(get_log_output(&local_dir), @r"
@ [zsu] bar
โ โ [qpv] foo
โโโฏ
โ [zzz]
[EOF]
");
let output = local_dir.run_jj(["abandon", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
qpvuntsm e8849ae1 foo | (empty) (no description set)
Deleted bookmarks: foo
Hint: Deleted bookmarks can be pushed by name or all at once with `jj git push --deleted`.
[EOF]
");
let output = local_dir.run_jj(["abandon", "bar"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Abandoned 1 commits:
zsuskuln c2934cfb bar | (empty) (no description set)
Deleted bookmarks: bar
Working copy (@) now at: vruxwmqv b64f323d (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"separate(" ", "[" ++ change_id.short(3) ++ "]", bookmarks)"#;
work_dir.run_jj(["log", "-T", template])
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_diffedit_command.rs | cli/tests/test_diffedit_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use bstr::ByteSlice as _;
use indoc::indoc;
use crate::common::TestEnvironment;
#[test]
fn test_diffedit() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "a\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file2", "a\n");
work_dir.write_file("file3", "a\n");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.write_file("file2", "b\n");
work_dir.run_jj(["debug", "snapshot"]).success();
let setup_opid = work_dir.current_operation_id();
// Test the setup; nothing happens if we make no changes
std::fs::write(
&edit_script,
[
"files-before file1 file2",
"files-after JJ-INSTRUCTIONS file2",
"dump JJ-INSTRUCTIONS instrs",
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["diffedit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("instrs")).unwrap(), @r"
You are editing changes in: kkmpptxz e4245972 (no description set)
The diff initially shows the commit's changes.
Adjust the right side until it shows the contents you want. If you
don't make any changes, then the operation will be aborted.
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
[EOF]
");
// Try again with ui.diff-instructions=false
std::fs::write(&edit_script, "files-before file1 file2\0files-after file2").unwrap();
let output = work_dir.run_jj(["diffedit", "--config=ui.diff-instructions=false"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
[EOF]
");
// Try again with --tool=<name>
std::fs::write(
&edit_script,
"files-before file1 file2\0files-after JJ-INSTRUCTIONS file2",
)
.unwrap();
let output = work_dir.run_jj([
"diffedit",
"--config=ui.diff-editor='false'",
"--tool=fake-diff-editor",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
[EOF]
");
// Nothing happens if the diff-editor exits with an error
std::fs::write(&edit_script, "rm file2\0fail").unwrap();
let output = work_dir.run_jj(["diffedit"]);
insta::assert_snapshot!(output.normalize_stderr_exit_status(), @r"
------- stderr -------
Error: Failed to edit diff
Caused by: Tool exited with exit status: 1 (run with --debug to see the exact invocation)
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
[EOF]
");
// Can edit changes to individual files
std::fs::write(&edit_script, "reset file2").unwrap();
let output = work_dir.run_jj(["diffedit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 40ad4f80 (no description set)
Parent commit (@-) : rlvkpnrz 7e268da3 (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
[EOF]
");
// Changes to a commit are propagated to descendants
work_dir.run_jj(["op", "restore", &setup_opid]).success();
std::fs::write(&edit_script, "write file3\nmodified\n").unwrap();
let output = work_dir.run_jj(["diffedit", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: kkmpptxz 9f0ebae1 (no description set)
Parent commit (@-) : rlvkpnrz 72bcd8e9 (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let contents = work_dir.read_file("file3");
insta::assert_snapshot!(contents, @"modified");
// Test diffedit --from @--
work_dir.run_jj(["op", "restore", &setup_opid]).success();
std::fs::write(
&edit_script,
"files-before file1\0files-after JJ-INSTRUCTIONS file2 file3\0reset file2",
)
.unwrap();
let output = work_dir.run_jj(["diffedit", "--from", "@--"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 215fca5f (no description set)
Parent commit (@-) : rlvkpnrz 7e268da3 (no description set)
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
D file2
[EOF]
");
// Test with path restriction
work_dir.run_jj(["op", "restore", &setup_opid]).success();
work_dir.write_file("file3", "a\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "modified\n");
work_dir.write_file("file2", "modified\n");
work_dir.write_file("file3", "modified\n");
// Edit only file2 with path argument
std::fs::write(
&edit_script,
"files-before file2\0files-after JJ-INSTRUCTIONS file2\0reset file2",
)
.unwrap();
let output = work_dir.run_jj(["diffedit", "file2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: tlkvzzqu 06bdff15 (no description set)
Parent commit (@-) : kkmpptxz e4245972 (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
C {file3 => file1}
M file3
[EOF]
");
// Test reverse-order diffedit --to @-
work_dir.run_jj(["op", "restore", &setup_opid]).success();
std::fs::write(
&edit_script,
[
"files-before file2",
"files-after JJ-INSTRUCTIONS file1 file2",
"reset file2",
"dump JJ-INSTRUCTIONS instrs",
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["diffedit", "--to", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: kkmpptxz 9a4e9bcc (no description set)
Parent commit (@-) : rlvkpnrz fb5c77f4 (no description set)
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("instrs")).unwrap(), @r"
You are editing changes in: rlvkpnrz 7e268da3 (no description set)
The diff initially shows the commit's changes relative to:
kkmpptxz e4245972 (no description set)
Adjust the right side until it shows the contents you want. If you
don't make any changes, then the operation will be aborted.
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
[EOF]
");
}
#[test]
fn test_diffedit_new_file() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "a\n");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.write_file("file2", "b\n");
work_dir.run_jj(["debug", "snapshot"]).success();
let setup_opid = work_dir.current_operation_id();
// Test the setup; nothing happens if we make no changes
std::fs::write(
&edit_script,
"files-before file1\0files-after JJ-INSTRUCTIONS file2",
)
.unwrap();
let output = work_dir.run_jj(["diffedit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
A file2
[EOF]
");
// Creating `file1` on the right side is noticed by `jj diffedit`
std::fs::write(&edit_script, "write file1\nmodified\n").unwrap();
let output = work_dir.run_jj(["diffedit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: rlvkpnrz c26dcad1 (no description set)
Parent commit (@-) : qpvuntsm eb7b8a1f (no description set)
Added 1 files, modified 0 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
M file1
A file2
[EOF]
");
// Creating a file that wasn't on either side is ignored by diffedit.
// TODO(ilyagr) We should decide whether we like this behavior.
//
// On one hand, it is unexpected and potentially a minor BUG. On the other
// hand, this prevents `jj` from loading any backup files the merge tool
// generates.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
std::fs::write(&edit_script, "write new_file\nnew file\n").unwrap();
let output = work_dir.run_jj(["diffedit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
A file2
[EOF]
");
}
#[test]
fn test_diffedit_existing_instructions() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// A diff containing an existing JJ-INSTRUCTIONS file themselves.
work_dir.write_file("JJ-INSTRUCTIONS", "instruct");
std::fs::write(&edit_script, "write JJ-INSTRUCTIONS\nmodified\n").unwrap();
let output = work_dir.run_jj(["diffedit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm e914aaad (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
// Test that we didn't delete or overwrite the "JJ-INSTRUCTIONS" file.
let content = work_dir.read_file("JJ-INSTRUCTIONS");
insta::assert_snapshot!(content, @"modified");
}
#[test]
fn test_diffedit_external_tool_conflict_marker_style() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let file_path = "file";
// Create a conflict
work_dir.write_file(
file_path,
indoc! {"
line 1
line 2
line 3
line 4
line 5
"},
);
work_dir.run_jj(["commit", "-m", "base"]).success();
work_dir.write_file(
file_path,
indoc! {"
line 1
line 2.1
line 2.2
line 3
line 4.1
line 5
"},
);
work_dir.run_jj(["describe", "-m", "side-a"]).success();
work_dir
.run_jj(["new", "subject(base)", "-m", "side-b"])
.success();
work_dir.write_file(
file_path,
indoc! {"
line 1
line 2.3
line 3
line 4.2
line 4.3
line 5
"},
);
// Resolve one of the conflicts in the working copy
work_dir
.run_jj(["new", "subject(side-a)", "subject(side-b)"])
.success();
work_dir.write_file(
file_path,
indoc! {"
line 1
line 2.1
line 2.2
line 2.3
line 3
<<<<<<<
%%%%%%%
-line 4
+line 4.1
+++++++
line 4.2
line 4.3
>>>>>>>
line 5
"},
);
// 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
std::fs::write(
&edit_script,
[
"files-before file",
"files-after JJ-INSTRUCTIONS file",
"dump file after-file",
"reset file",
"dump file before-file",
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["diffedit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: mzvwutvl 2fc7c1ba (conflict) (empty) (no description set)
Parent commit (@-) : rlvkpnrz 74e448a1 side-a
Parent commit (@-) : zsuskuln 6982bce7 side-b
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict
Existing conflicts were resolved or abandoned from 1 commits.
[EOF]
");
// Conflicts should render using "snapshot" format in diff editor
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("before-file")).unwrap(), @r#"
line 1
<<<<<<< conflict 1 of 2
+++++++ rlvkpnrz 74e448a1 "side-a"
line 2.1
line 2.2
------- qpvuntsm 9bd2e004 "base"
line 2
+++++++ zsuskuln 6982bce7 "side-b"
line 2.3
>>>>>>> conflict 1 of 2 ends
line 3
<<<<<<< conflict 2 of 2
+++++++ rlvkpnrz 74e448a1 "side-a"
line 4.1
------- qpvuntsm 9bd2e004 "base"
line 4
+++++++ zsuskuln 6982bce7 "side-b"
line 4.2
line 4.3
>>>>>>> conflict 2 of 2 ends
line 5
"#);
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("after-file")).unwrap(), @r#"
line 1
line 2.1
line 2.2
line 2.3
line 3
<<<<<<< conflict 1 of 1
+++++++ rlvkpnrz 74e448a1 "side-a"
line 4.1
------- qpvuntsm 9bd2e004 "base"
line 4
+++++++ zsuskuln 6982bce7 "side-b"
line 4.2
line 4.3
>>>>>>> conflict 1 of 1 ends
line 5
"#);
// Conflicts should be materialized using "diff" format in working copy
insta::assert_snapshot!(work_dir.read_file(file_path), @r#"
line 1
<<<<<<< conflict 1 of 2
+++++++ rlvkpnrz 74e448a1 "side-a"
line 2.1
line 2.2
%%%%%%% diff from: qpvuntsm 9bd2e004 "base"
\\\\\\\ to: zsuskuln 6982bce7 "side-b"
-line 2
+line 2.3
>>>>>>> conflict 1 of 2 ends
line 3
<<<<<<< conflict 2 of 2
%%%%%%% diff from: qpvuntsm 9bd2e004 "base"
\\\\\\\ to: rlvkpnrz 74e448a1 "side-a"
-line 4
+line 4.1
+++++++ zsuskuln 6982bce7 "side-b"
line 4.2
line 4.3
>>>>>>> conflict 2 of 2 ends
line 5
"#);
// File should be conflicted with no changes
let output = work_dir.run_jj(["st"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : mzvwutvl 2fc7c1ba (conflict) (empty) (no description set)
Parent commit (@-): rlvkpnrz 74e448a1 side-a
Parent commit (@-): zsuskuln 6982bce7 side-b
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict
[EOF]
");
}
#[test]
fn test_diffedit_3pane() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "a\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file2", "a\n");
work_dir.write_file("file3", "a\n");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.write_file("file2", "b\n");
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.
let config_with_right_as_after =
"merge-tools.fake-diff-editor.edit-args=['$left', '$right', '--ignore=$output']";
let config_with_output_as_after =
"merge-tools.fake-diff-editor.edit-args=['$left', '$output', '--ignore=$right']";
std::fs::write(&edit_script, "").unwrap();
// Nothing happens if we make no changes
std::fs::write(
&edit_script,
"files-before file1 file2\0files-after JJ-INSTRUCTIONS file2",
)
.unwrap();
let output = work_dir.run_jj(["diffedit", "--config", config_with_output_as_after]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
[EOF]
");
// 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, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
[EOF]
");
// Can edit changes to individual files
std::fs::write(&edit_script, "reset file2").unwrap();
let output = work_dir.run_jj(["diffedit", "--config", config_with_output_as_after]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 239413bd (no description set)
Parent commit (@-) : rlvkpnrz 7e268da3 (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
[EOF]
");
// Can write something new to `file1`
work_dir.run_jj(["op", "restore", &setup_opid]).success();
std::fs::write(&edit_script, "write file1\nnew content").unwrap();
let output = work_dir.run_jj(["diffedit", "--config", config_with_output_as_after]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 95873a91 (no description set)
Parent commit (@-) : rlvkpnrz 7e268da3 (no description set)
Added 1 files, modified 0 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
M file1
M file2
[EOF]
");
// But nothing happens if we modify the right side
work_dir.run_jj(["op", "restore", &setup_opid]).success();
std::fs::write(&edit_script, "write file1\nnew content").unwrap();
let output = work_dir.run_jj(["diffedit", "--config", config_with_right_as_after]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
[EOF]
");
// TODO: test with edit_script of "reset file2". This fails on right side
// since the file is readonly.
}
#[test]
fn test_diffedit_merge() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "a\n");
work_dir.write_file("file2", "a\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "b"])
.success();
work_dir.write_file("file1", "b\n");
work_dir.write_file("file2", "b\n");
work_dir.run_jj(["new", "@-"]).success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "c\n");
work_dir.write_file("file2", "c\n");
work_dir.run_jj(["new", "@", "b", "-m", "merge"]).success();
// Resolve the conflict in file1, but leave the conflict in file2
work_dir.write_file("file1", "d\n");
work_dir.write_file("file3", "d\n");
work_dir.run_jj(["new"]).success();
// Test the setup
let output = work_dir.run_jj(["diff", "-r", "@-", "-s"]);
insta::assert_snapshot!(output, @r"
M file1
A file3
[EOF]
");
// 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",
)
.unwrap();
let output = work_dir.run_jj(["diffedit", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: yqosqzyt df15f76d (conflict) (empty) (no description set)
Parent commit (@-) : royxmykx 44a9042a (conflict) merge
Added 0 files, modified 0 files, removed 1 files
Warning: There are unresolved conflicts at these paths:
file2 2-sided conflict
[EOF]
");
let output = work_dir.run_jj(["diff", "-s", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
D file1
A file3
[EOF]
");
assert!(!work_dir.root().join("file1").exists());
let output = work_dir.run_jj(["file", "show", "file2"]);
insta::assert_snapshot!(output, @r"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: qpvuntsm fc6f5e82
\\\\\\\ to: mzvwutvl e3b18dc7
-a
+c
+++++++ rlvkpnrz 7027fb26
b
>>>>>>> conflict 1 of 1 ends
[EOF]
");
}
#[test]
fn test_diffedit_old_restore_interactive_tests() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "a\n");
work_dir.write_file("file2", "a\n");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.write_file("file2", "b\n");
work_dir.write_file("file3", "b\n");
work_dir.run_jj(["debug", "snapshot"]).success();
let setup_opid = work_dir.current_operation_id();
// Nothing happens if we make no changes
let output = work_dir.run_jj(["diffedit", "--from", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
C {file2 => file3}
[EOF]
");
// Nothing happens if the diff-editor exits with an error
std::fs::write(&edit_script, "rm file2\0fail").unwrap();
let output = work_dir.run_jj(["diffedit", "--from", "@-"]);
insta::assert_snapshot!(output.normalize_stderr_exit_status(), @r"
------- stderr -------
Error: Failed to edit diff
Caused by: Tool exited with exit status: 1 (run with --debug to see the exact invocation)
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
C {file2 => file3}
[EOF]
");
// Can restore changes to individual files
std::fs::write(&edit_script, "reset file2\0reset file3").unwrap();
let output = work_dir.run_jj(["diffedit", "--from", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: rlvkpnrz 83b62f75 (no description set)
Parent commit (@-) : qpvuntsm fc6f5e82 (no description set)
Added 0 files, modified 1 files, removed 1 files
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file1
[EOF]
");
// Can make unrelated edits
work_dir.run_jj(["op", "restore", &setup_opid]).success();
std::fs::write(&edit_script, "write file3\nunrelated\n").unwrap();
let output = work_dir.run_jj(["diffedit", "--from", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: rlvkpnrz 8119c685 (no description set)
Parent commit (@-) : qpvuntsm fc6f5e82 (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["diff", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file1 b/file1
deleted file mode 100644
index 7898192261..0000000000
--- a/file1
+++ /dev/null
@@ -1,1 +0,0 @@
-a
diff --git a/file2 b/file2
index 7898192261..6178079822 100644
--- a/file2
+++ b/file2
@@ -1,1 +1,1 @@
-a
+b
diff --git a/file3 b/file3
new file mode 100644
index 0000000000..c21c9352f7
--- /dev/null
+++ b/file3
@@ -0,0 +1,1 @@
+unrelated
[EOF]
");
}
#[test]
fn test_diffedit_restore_descendants() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "println!(\"foo\")\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "println!(\"bar\")\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "println!(\"baz\");\n");
// Add a ";" after the line with "bar". There should be no conflict.
std::fs::write(edit_script, "write file\nprintln!(\"bar\");\n").unwrap();
let output = work_dir.run_jj(["diffedit", "-r", "@-", "--restore-descendants"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits (while preserving their content)
Working copy (@) now at: kkmpptxz a35ef1a5 (no description set)
Parent commit (@-) : rlvkpnrz 2e949a84 (no description set)
[EOF]
");
let output = work_dir.run_jj(["diff", "--git"]);
insta::assert_snapshot!(output, @r#"
diff --git a/file b/file
index 1a598a8fc9..7b6a85ab5a 100644
--- a/file
+++ b/file
@@ -1,1 +1,1 @@
-println!("bar");
+println!("baz");
[EOF]
"#);
}
#[test]
fn test_diffedit_external_tool_eol_conversion() {
// 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();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let file_path = "file";
// Use the none eol-conversion setting to check in as is.
let eol_conversion_none_config = "working-copy.eol-conversion='none'";
work_dir.write_file(file_path, "\n");
work_dir
.run_jj(["commit", "--config", eol_conversion_none_config, "-m", "1"])
.success();
work_dir.write_file(file_path, "\n\n");
work_dir
.run_jj(["commit", "--config", eol_conversion_none_config, "-m", "2"])
.success();
std::fs::write(
&edit_script,
[
"dump file after-file",
"reset file",
"dump file before-file",
]
.join("\0"),
)
.unwrap();
let test_eol_conversion_config = "working-copy.eol-conversion='input-output'";
work_dir
.run_jj([
"diffedit",
"-r",
"@-",
"--config",
test_eol_conversion_config,
])
.success();
let before_file_contents = std::fs::read(test_env.env_root().join("before-file")).unwrap();
let before_file_lines = before_file_contents
.lines_with_terminator()
.collect::<Vec<_>>();
let after_file_contents = std::fs::read(test_env.env_root().join("after-file")).unwrap();
let after_file_lines = after_file_contents
.lines_with_terminator()
.collect::<Vec<_>>();
assert_eq!(before_file_lines[0], after_file_lines[0]);
fn get_eol(line: &[u8]) -> &'static str {
if line.ends_with(b"\r\n") {
"\r\n"
} else if line.ends_with(b"\n") {
"\n"
} else {
""
}
}
let first_eol = get_eol(after_file_lines[0]);
let second_eol = get_eol(after_file_lines[1]);
assert_eq!(first_eol, second_eol);
assert_eq!(
first_eol, "\n",
"The EOL the external diff editor receives must be LF to align with the builtin diff \
editor."
);
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.
work_dir.write_file(file_path, "\n\n");
work_dir
.run_jj(["squash", "--config", eol_conversion_none_config, "-m", "2"])
.success();
std::fs::write(&edit_script, format!("write file\n{eol}{eol}{eol}")).unwrap();
work_dir
.run_jj([
"diffedit",
"-r",
"@-",
"--config",
test_eol_conversion_config,
])
.success();
work_dir
.run_jj(["new", "root()", "--config", eol_conversion_none_config])
.success();
work_dir
.run_jj(["new", "subject(2)", "--config", eol_conversion_none_config])
.success();
let file_content = work_dir.read_file(file_path);
assert_eq!(file_content, b"\n\n\n");
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_templater.rs | cli/tests/test_templater.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_templater_parse_error() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let render = |template| get_template_output(&work_dir, "@-", template);
// Typo
test_env.add_config(
r###"
[template-aliases]
'conflicting' = ''
'shorted()' = ''
'socat(x)' = 'x'
'format_id(id)' = 'id.sort()'
"###,
);
insta::assert_snapshot!(render(r#"conflicts"#), @r"
------- stderr -------
Error: Failed to parse template: Keyword `conflicts` doesn't exist
Caused by: --> 1:1
|
1 | conflicts
| ^-------^
|
= Keyword `conflicts` doesn't exist
Hint: Did you mean `conflict`, `conflicted_files`, `conflicting`?
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(render(r#"commit_id.shorter()"#), @r"
------- stderr -------
Error: Failed to parse template: Method `shorter` doesn't exist for type `CommitId`
Caused by: --> 1:11
|
1 | commit_id.shorter()
| ^-----^
|
= Method `shorter` doesn't exist for type `CommitId`
Hint: Did you mean `short`, `shortest`?
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(render(r#"oncat()"#), @r"
------- stderr -------
Error: Failed to parse template: Function `oncat` doesn't exist
Caused by: --> 1:1
|
1 | oncat()
| ^---^
|
= Function `oncat` doesn't exist
Hint: Did you mean `concat`, `socat`?
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(render(r#""".lines().map(|s| se)"#), @r#"
------- stderr -------
Error: Failed to parse template: Keyword `se` doesn't exist
Caused by: --> 1:20
|
1 | "".lines().map(|s| se)
| ^^
|
= Keyword `se` doesn't exist
Hint: Did you mean `s`, `self`?
[EOF]
[exit status: 1]
"#);
insta::assert_snapshot!(render(r#"format_id(commit_id)"#), @r"
------- stderr -------
Error: Failed to parse template: In alias `format_id(id)`
Caused by:
1: --> 1:1
|
1 | format_id(commit_id)
| ^------------------^
|
= In alias `format_id(id)`
2: --> 1:4
|
1 | id.sort()
| ^--^
|
= Method `sort` doesn't exist for type `CommitId`
Hint: Did you mean `short`, `shortest`?
[EOF]
[exit status: 1]
");
// "at least N arguments"
insta::assert_snapshot!(render("separate()"), @r"
------- stderr -------
Error: Failed to parse template: Function `separate`: Expected at least 1 arguments
Caused by: --> 1:10
|
1 | separate()
| ^
|
= Function `separate`: Expected at least 1 arguments
[EOF]
[exit status: 1]
");
// -Tbuiltin shows the predefined builtin_* aliases. This isn't 100%
// guaranteed, but is nice.
insta::assert_snapshot!(render(r#"builtin"#), @r"
------- stderr -------
Error: Failed to parse template: Keyword `builtin` doesn't exist
Caused by: --> 1:1
|
1 | builtin
| ^-----^
|
= Keyword `builtin` doesn't exist
Hint: Did you mean `builtin_config_list`, `builtin_config_list_detailed`, `builtin_draft_commit_description`, `builtin_evolog_compact`, `builtin_log_comfortable`, `builtin_log_compact`, `builtin_log_compact_full_description`, `builtin_log_detailed`, `builtin_log_node`, `builtin_log_node_ascii`, `builtin_log_oneline`, `builtin_log_redacted`, `builtin_op_log_comfortable`, `builtin_op_log_compact`, `builtin_op_log_node`, `builtin_op_log_node_ascii`, `builtin_op_log_oneline`, `builtin_op_log_redacted`?
[EOF]
[exit status: 1]
");
}
#[test]
fn test_templater_upper_lower() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let render = |template| get_colored_template_output(&work_dir, "@-", template);
insta::assert_snapshot!(
render(r#"change_id.shortest(4).upper() ++ change_id.shortest(4).upper().lower()"#),
@"[1m[38;5;5mZ[0m[38;5;8mZZZ[1m[38;5;5mz[0m[38;5;8mzzz[39m[EOF]");
insta::assert_snapshot!(
render(r#""Hello".upper() ++ "Hello".lower()"#), @"HELLOhello[EOF]");
}
#[test]
fn test_templater_alias() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let render = |template| get_template_output(&work_dir, "@-", template);
test_env.add_config(
r###"
[template-aliases]
'my_commit_id' = 'commit_id.short()'
'syntax_error' = 'foo.'
'name_error' = 'unknown_id'
'recurse' = 'recurse1'
'recurse1' = 'recurse2()'
'recurse2()' = 'recurse'
'identity(x)' = 'x'
'coalesce2(x, y)' = 'if(x, x, y)'
'format_commit_summary_with_refs(x, y)' = 'x.commit_id()'
'builtin_log_node' = '"#"'
'builtin_op_log_node' = '"#"'
'builtin_log_node_ascii' = '"#"'
'builtin_op_log_node_ascii' = '"#"'
"###,
);
insta::assert_snapshot!(render("my_commit_id"), @"000000000000[EOF]");
insta::assert_snapshot!(render("identity(my_commit_id)"), @"000000000000[EOF]");
insta::assert_snapshot!(render("commit_id ++ syntax_error"), @r"
------- stderr -------
Error: Failed to parse template: In alias `syntax_error`
Caused by:
1: --> 1:14
|
1 | commit_id ++ syntax_error
| ^----------^
|
= In alias `syntax_error`
2: --> 1:5
|
1 | foo.
| ^---
|
= expected <identifier>
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(render("commit_id ++ name_error"), @r"
------- stderr -------
Error: Failed to parse template: In alias `name_error`
Caused by:
1: --> 1:14
|
1 | commit_id ++ name_error
| ^--------^
|
= In alias `name_error`
2: --> 1:1
|
1 | unknown_id
| ^--------^
|
= Keyword `unknown_id` doesn't exist
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(render(r#"identity(identity(commit_id.short("")))"#), @r#"
------- stderr -------
Error: Failed to parse template: In alias `identity(x)`
Caused by:
1: --> 1:1
|
1 | identity(identity(commit_id.short("")))
| ^-------------------------------------^
|
= In alias `identity(x)`
2: --> 1:1
|
1 | x
| ^
|
= In function parameter `x`
3: --> 1:10
|
1 | identity(identity(commit_id.short("")))
| ^---------------------------^
|
= In alias `identity(x)`
4: --> 1:1
|
1 | x
| ^
|
= In function parameter `x`
5: --> 1:35
|
1 | identity(identity(commit_id.short("")))
| ^^
|
= Expected expression of type `Integer`, but actual type is `String`
[EOF]
[exit status: 1]
"#);
insta::assert_snapshot!(render("commit_id ++ recurse"), @r"
------- stderr -------
Error: Failed to parse template: In alias `recurse`
Caused by:
1: --> 1:14
|
1 | commit_id ++ recurse
| ^-----^
|
= In alias `recurse`
2: --> 1:1
|
1 | recurse1
| ^------^
|
= In alias `recurse1`
3: --> 1:1
|
1 | recurse2()
| ^--------^
|
= In alias `recurse2()`
4: --> 1:1
|
1 | recurse
| ^-----^
|
= Alias `recurse` expanded recursively
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(render("identity()"), @r"
------- stderr -------
Error: Failed to parse template: Function `identity`: Expected 1 arguments
Caused by: --> 1:10
|
1 | identity()
| ^
|
= Function `identity`: Expected 1 arguments
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(render("identity(commit_id, commit_id)"), @r"
------- stderr -------
Error: Failed to parse template: Function `identity`: Expected 1 arguments
Caused by: --> 1:10
|
1 | identity(commit_id, commit_id)
| ^------------------^
|
= Function `identity`: Expected 1 arguments
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(render(r#"coalesce2(label("x", "not boolean"), "")"#), @r#"
------- stderr -------
Error: Failed to parse template: In alias `coalesce2(x, y)`
Caused by:
1: --> 1:1
|
1 | coalesce2(label("x", "not boolean"), "")
| ^--------------------------------------^
|
= In alias `coalesce2(x, y)`
2: --> 1:4
|
1 | if(x, x, y)
| ^
|
= In function parameter `x`
3: --> 1:11
|
1 | coalesce2(label("x", "not boolean"), "")
| ^-----------------------^
|
= Expected expression of type `Boolean`, but actual type is `Template`
[EOF]
[exit status: 1]
"#);
insta::assert_snapshot!(render("(-my_commit_id)"), @r"
------- stderr -------
Error: Failed to parse template: In alias `my_commit_id`
Caused by:
1: --> 1:3
|
1 | (-my_commit_id)
| ^----------^
|
= In alias `my_commit_id`
2: --> 1:1
|
1 | commit_id.short()
| ^---------------^
|
= Expected expression of type `Integer`, but actual type is `String`
[EOF]
[exit status: 1]
");
}
#[test]
fn test_templater_alias_override() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
test_env.add_config(
r#"
[template-aliases]
'f(x)' = '"user"'
"#,
);
// 'f(x)' should be overridden by --config 'f(a)'. If aliases were sorted
// purely by name, 'f(a)' would come first.
let output = work_dir.run_jj([
"log",
"--no-graph",
"-r@",
"-T",
r#"f(_)"#,
r#"--config=template-aliases.'f(a)'='"arg"'"#,
]);
insta::assert_snapshot!(output, @"arg[EOF]");
}
#[test]
fn test_templater_bad_alias_decl() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
test_env.add_config(
r###"
[template-aliases]
'badfn(a, a)' = 'a'
'my_commit_id' = 'commit_id.short()'
"###,
);
// Invalid declaration should be warned and ignored.
let output = work_dir.run_jj(["log", "--no-graph", "-r@-", "-Tmy_commit_id"]);
insta::assert_snapshot!(output, @r"
000000000000[EOF]
------- stderr -------
Warning: Failed to load `template-aliases.badfn(a, a)`: --> 1:7
|
1 | badfn(a, a)
| ^--^
|
= Redefinition of function parameter
[EOF]
");
}
#[test]
fn test_templater_config_function() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let render = |template| get_template_output(&work_dir, "@-", template);
insta::assert_snapshot!(
render("config('user.name')"),
@r#""Test User"[EOF]"#);
insta::assert_snapshot!(
render("config('user')"),
@r#"{ email = "test.user@example.com", name = "Test User" }[EOF]"#);
insta::assert_snapshot!(render("config('invalid name')"), @r"
------- stderr -------
Error: Failed to parse template: Failed to parse config name
Caused by:
1: --> 1:8
|
1 | config('invalid name')
| ^------------^
|
= Failed to parse config name
2: TOML parse error at line 1, column 9
|
1 | invalid name
| ^
unexpected content, expected nothing
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(render("config('unknown')"), @r"
------- stderr -------
Error: Failed to parse template: Failed to get config value
Caused by:
1: --> 1:1
|
1 | config('unknown')
| ^----^
|
= Failed to get config value
2: Value not found for unknown
[EOF]
[exit status: 1]
");
}
#[must_use]
fn get_template_output(work_dir: &TestWorkDir, rev: &str, template: &str) -> CommandOutput {
work_dir.run_jj(["log", "--no-graph", "-r", rev, "-T", template])
}
#[must_use]
fn get_colored_template_output(work_dir: &TestWorkDir, rev: &str, template: &str) -> CommandOutput {
work_dir.run_jj([
"log",
"--color=always",
"--no-graph",
"-r",
rev,
"-T",
template,
])
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_global_opts.rs | cli/tests/test_global_opts.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::ffi::OsString;
use indoc::indoc;
use itertools::Itertools as _;
use regex::Regex;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_non_utf8_arg() {
let test_env = TestEnvironment::default();
#[cfg(unix)]
let invalid_utf = {
use std::os::unix::ffi::OsStringExt as _;
OsString::from_vec(vec![0x66, 0x6f, 0x80, 0x6f])
};
#[cfg(windows)]
let invalid_utf = {
use std::os::windows::prelude::*;
OsString::from_wide(&[0x0066, 0x006f, 0xD800, 0x006f])
};
let output = test_env.run_jj_in(".", [&invalid_utf]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Non-UTF-8 argument
[EOF]
[exit status: 2]
");
}
#[test]
fn test_version() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["--version"]).success();
let stdout = output.stdout.into_raw();
let sanitized = stdout.replace(|c: char| c.is_ascii_hexdigit(), "?");
let expected = [
"jj ?.??.?\n",
"jj ?.??.?-????????????????????????????????????????\n",
// This test could be made to succeed when `jj` is compiled at a merge commit by adding a
// few entries like "jj ?.??.?-????????????????????????????????????????-?????????????????
// ???????????????????????\n" here. However, it might be best to keep it failing, so that
// we avoid releasing `jj` with such `--version` output.
];
assert!(
expected.contains(&sanitized.as_str()),
"`jj version` output: {stdout:?}.\nSanitized: {sanitized:?}\nExpected one of: {expected:?}"
);
}
#[test]
fn test_no_subcommand() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Outside of a repo.
let output = test_env.run_jj_in(".", [""; 0]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Hint: Use `jj -h` for a list of available commands.
Run `jj config set --user ui.default-command log` to disable this message.
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
test_env.add_config(r#"ui.default-command="log""#);
let output = test_env.run_jj_in(".", [""; 0]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
let output = test_env.run_jj_in(".", ["--help"]).success();
insta::assert_snapshot!(
output.stdout.normalized().lines().next().unwrap(),
@"Jujutsu (An experimental VCS)");
insta::assert_snapshot!(output.stderr, @"");
let output = test_env.run_jj_in(".", ["-R", "repo"]).success();
assert_eq!(output, work_dir.run_jj(["log"]));
// Inside of a repo.
let output = work_dir.run_jj([""; 0]).success();
assert_eq!(output, work_dir.run_jj(["log"]));
// Command argument that looks like a command name.
work_dir
.run_jj(["bookmark", "create", "-r@", "help"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "log"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "show"])
.success();
// TODO: test_env.run_jj(["-r", "help"]).success()
insta::assert_snapshot!(work_dir.run_jj(["-r", "log"]), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:07 help log show e8849ae1
โ (empty) (no description set)
~
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["-r", "show"]), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:07 help log show e8849ae1
โ (empty) (no description set)
~
[EOF]
");
// Multiple default command strings work.
test_env.add_config(r#"ui.default-command=["commit", "-m", "foo"]"#);
work_dir.run_jj(["new"]).success();
work_dir.write_file("file.txt", "file");
let output = work_dir.run_jj([""; 0]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kxryzmor 8db1ba9a (empty) (no description set)
Parent commit (@-) : lylxulpl 19f3adb2 foo
[EOF]
");
}
#[test]
fn test_ignore_working_copy() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "initial");
let output = work_dir.run_jj(["log", "-T", "commit_id"]);
insta::assert_snapshot!(output, @r"
@ 82a10a4d9ef783fd68b661f40ce10dd80d599d9e
โ 0000000000000000000000000000000000000000
[EOF]
");
// Modify the file. With --ignore-working-copy, we still get the same commit
// ID.
work_dir.write_file("file", "modified");
let output_again = work_dir.run_jj(["log", "-T", "commit_id", "--ignore-working-copy"]);
assert_eq!(output_again, output);
// But without --ignore-working-copy, we get a new commit ID.
let output = work_dir.run_jj(["log", "-T", "commit_id"]);
insta::assert_snapshot!(output, @r"
@ 00fc09f48ccf5c8b025a0f93b0ec3b0e4294a598
โ 0000000000000000000000000000000000000000
[EOF]
");
}
#[test]
fn test_repo_arg_with_git_init() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["git", "init", "-R=.", "repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_repo_arg_with_git_clone() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["git", "clone", "-R=.", "remote"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_resolve_workspace_directory() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let sub_dir = work_dir.create_dir_all("dir/subdir");
// Ancestor of cwd
let output = sub_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : qpvuntsm e8849ae1 (empty) (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// Explicit subdirectory path
let output = sub_dir.run_jj(["status", "-R", "."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
// Valid explicit path
let output = sub_dir.run_jj(["status", "-R", "../.."]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : qpvuntsm e8849ae1 (empty) (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// "../../..".ancestors() contains "../..", but it should never be looked up.
let output = sub_dir.run_jj(["status", "-R", "../../.."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "../../.."
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_no_workspace_directory() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
work_dir.create_dir_all("");
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
let output = test_env.run_jj_in(".", ["status", "-R", "repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "repo"
[EOF]
[exit status: 1]
"#);
work_dir.create_dir_all(".git");
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "."
Hint: It looks like this is a git repo. You can create a jj repo backed by it by running this:
jj git init
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_bad_path() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let sub_dir = work_dir.create_dir_all("dir");
// cwd == workspace_root
let output = work_dir.run_jj(["file", "show", "../out"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Error: Failed to parse fileset: Invalid file pattern
Caused by:
1: --> 1:1
|
1 | ../out
| ^----^
|
= Invalid file pattern
2: Path "../out" is not in the repo "."
3: Invalid component ".." in repo-relative path "../out"
[EOF]
[exit status: 1]
"#);
// cwd != workspace_root, can't be parsed as repo-relative path
let output = sub_dir.run_jj(["file", "show", "../.."]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Error: Failed to parse fileset: Invalid file pattern
Caused by:
1: --> 1:1
|
1 | ../..
| ^---^
|
= Invalid file pattern
2: Path "../.." is not in the repo "../"
3: Invalid component ".." in repo-relative path "../"
[EOF]
[exit status: 1]
"#);
// cwd != workspace_root, can be parsed as repo-relative path
let output = test_env.run_jj_in(".", ["file", "show", "-Rrepo", "out"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Error: Failed to parse fileset: Invalid file pattern
Caused by:
1: --> 1:1
|
1 | out
| ^-^
|
= Invalid file pattern
2: Path "out" is not in the repo "repo"
3: Invalid component ".." in repo-relative path "../out"
Hint: Consider using root:"out" to specify repo-relative path
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_invalid_filesets_looking_like_filepaths() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["file", "show", "abc~"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse fileset: Syntax error
Caused by: --> 1:5
|
1 | abc~
| ^---
|
= expected `~` or <primary>
Hint: See https://docs.jj-vcs.dev/latest/filesets/ or use `jj help -k filesets` for filesets syntax and how to match file paths.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_broken_repo_structure() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let store_path = work_dir.root().join(".jj").join("repo").join("store");
let store_type_path = store_path.join("type");
// Test the error message when the git repository can't be located.
work_dir.remove_file(store_path.join("git_target"));
let output = work_dir.run_jj(["log"]);
insta::assert_snapshot!(output.strip_stderr_last_line(), @r"
------- stderr -------
Internal error: The repository appears broken or inaccessible
Caused by:
1: Cannot access $TEST_ENV/repo/.jj/repo/store/git_target
[EOF]
[exit status: 255]
");
// Test the error message when the commit backend is of unknown type.
work_dir.write_file(&store_type_path, "unknown");
let output = work_dir.run_jj(["log"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Internal error: This version of the jj binary doesn't support this type of repo
Caused by: Unsupported commit backend type 'unknown'
[EOF]
[exit status: 255]
");
// Test the error message when the file indicating the commit backend type
// cannot be read.
work_dir.remove_file(&store_type_path);
work_dir.create_dir(&store_type_path);
let output = work_dir.run_jj(["log"]);
insta::assert_snapshot!(output.strip_stderr_last_line(), @r"
------- stderr -------
Internal error: The repository appears broken or inaccessible
Caused by:
1: Failed to read commit backend type
2: Cannot access $TEST_ENV/repo/.jj/repo/store/type
[EOF]
[exit status: 255]
");
// Test when the .jj directory is empty. The error message is identical to
// the previous one, but writing the default type file would also fail.
work_dir.remove_dir_all(".jj");
work_dir.create_dir(".jj");
let output = work_dir.run_jj(["log"]);
insta::assert_snapshot!(output.strip_stderr_last_line(), @r"
------- stderr -------
Internal error: The repository appears broken or inaccessible
Caused by:
1: Failed to read commit backend type
2: Cannot access $TEST_ENV/repo/.jj/repo/store/type
[EOF]
[exit status: 255]
");
}
#[test]
fn test_color_config() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Test that --color=always is respected.
let output = work_dir.run_jj(["--color=always", "log", "-T", "commit_id"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m [38;5;4me8849ae12c709f2321908879bc724fdb2ab8a781[39m
[1m[38;5;14mโ[0m [38;5;4m0000000000000000000000000000000000000000[39m
[EOF]
");
// Test that color is used if it's requested in the config file
test_env.add_config(r#"ui.color="always""#);
let output = work_dir.run_jj(["log", "-T", "commit_id"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m [38;5;4me8849ae12c709f2321908879bc724fdb2ab8a781[39m
[1m[38;5;14mโ[0m [38;5;4m0000000000000000000000000000000000000000[39m
[EOF]
");
// Test that --color=never overrides the config.
let output = work_dir.run_jj(["--color=never", "log", "-T", "commit_id"]);
insta::assert_snapshot!(output, @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
โ 0000000000000000000000000000000000000000
[EOF]
");
// Test that --color=auto overrides the config.
let output = work_dir.run_jj(["--color=auto", "log", "-T", "commit_id"]);
insta::assert_snapshot!(output, @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
โ 0000000000000000000000000000000000000000
[EOF]
");
// Test that --config 'ui.color=never' overrides the config.
let output = work_dir.run_jj(["--config=ui.color=never", "log", "-T", "commit_id"]);
insta::assert_snapshot!(output, @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
โ 0000000000000000000000000000000000000000
[EOF]
");
// --color overrides --config 'ui.color=...'.
let output = work_dir.run_jj([
"--color",
"never",
"--config=ui.color=always",
"log",
"-T",
"commit_id",
]);
insta::assert_snapshot!(output, @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
โ 0000000000000000000000000000000000000000
[EOF]
");
// 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"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m [38;5;4me8849ae12c709f2321908879bc724fdb2ab8a781[39m
[1m[38;5;14mโ[0m [38;5;4m0000000000000000000000000000000000000000[39m
[EOF]
");
// Test that per-repo config overrides the user config.
work_dir.write_file(".jj/repo/config.toml", r#"ui.color = "never""#);
let output = work_dir.run_jj(["log", "-T", "commit_id"]);
insta::assert_snapshot!(output, @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
โ 0000000000000000000000000000000000000000
[EOF]
");
// Invalid --color
let output = work_dir.run_jj(["log", "--color=foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value 'foo' for '--color <WHEN>'
[possible values: always, never, debug, auto]
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Invalid ui.color
let stderr = work_dir.run_jj(["log", "--config=ui.color=true"]);
insta::assert_snapshot!(stderr, @r"
------- stderr -------
Config error: Invalid type or value for ui.color
Caused by: wanted string or table
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_color_ui_messages() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
test_env.add_config("ui.color = 'always'");
// hint and error
let output = test_env.run_jj_in(".", ["-R."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
[1m[38;5;6mHint: [0m[39mUse `jj -h` for a list of available commands.[39m
[39mRun `jj config set --user ui.default-command log` to disable this message.[39m
[1m[38;5;1mError: [39mThere is no jj repo in "."[0m
[EOF]
[exit status: 1]
"#);
// error source
let output = work_dir.run_jj(["log", ".."]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
[1m[38;5;1mError: [39mFailed to parse fileset: Invalid file pattern[0m
[1m[39mCaused by:[0m
[1m[39m1: [0m[39m --> 1:1[39m
[39m |[39m
[39m1 | ..[39m
[39m | ^^[39m
[39m |[39m
[39m = Invalid file pattern[39m
[1m[39m2: [0m[39mPath ".." is not in the repo "."[39m
[1m[39m3: [0m[39mInvalid component ".." in repo-relative path "../"[39m
[EOF]
[exit status: 1]
"#);
// warning
let output = work_dir.run_jj(["log", "@"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
[1m[38;5;3mWarning: [39mNo matching entries for paths: @[0m
[1m[38;5;3mWarning: [39mThe argument "@" is being interpreted as a fileset expression. To specify a revset, pass -r "@" instead.[0m
[EOF]
"#);
// error inlined in template output
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj([
"log",
"-r@|@--",
"--config=templates.log_node=commit_id",
"-Tdescription",
]);
insta::assert_snapshot!(output, @r"
[38;5;4m8afc18ff677d32e40043e1bc8c1683c2f9c2e916[39m
[1m[39m<[38;5;1mError: [39mNo Commit available>[0m [38;5;8m(elided revisions)[39m
[38;5;4m0000000000000000000000000000000000000000[39m
[EOF]
");
// formatted hint
let output = work_dir.run_jj(["edit", ".."]);
insta::assert_snapshot!(output, @r"
------- stderr -------
[1m[38;5;1mError: [39mRevset `..` resolved to more than one revision[0m
[1m[38;5;6mHint: [0m[39mThe revset `..` resolved to these revisions:[39m
[39m [1m[38;5;13mm[38;5;8mzvwutvl[39m [38;5;12m8[38;5;8mafc18ff[39m [38;5;10m(empty)[39m [38;5;10m(no description set)[0m[39m[39m
[39m [1m[38;5;5mq[0m[38;5;8mpvuntsm[39m [1m[38;5;4me[0m[38;5;8m8849ae1[39m [38;5;2m(empty)[39m [38;5;2m(no description set)[39m[39m
[EOF]
[exit status: 1]
");
// commit_summary template with debugging colors
let output = work_dir.run_jj(["st", "--color", "debug"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : [1m[38;5;13m<<commit working_copy change_id shortest prefix::m>>[38;5;8m<<commit working_copy change_id shortest rest::zvwutvl>>[39m<<commit working_copy:: >>[38;5;12m<<commit working_copy commit_id shortest prefix::8>>[38;5;8m<<commit working_copy commit_id shortest rest::afc18ff>>[39m<<commit working_copy:: >>[38;5;10m<<commit working_copy empty::(empty)>>[39m<<commit working_copy:: >>[38;5;10m<<commit working_copy empty description placeholder::(no description set)>>[0m
Parent commit (@-): [1m[38;5;5m<<commit change_id shortest prefix::q>>[0m[38;5;8m<<commit change_id shortest rest::pvuntsm>>[39m<<commit:: >>[1m[38;5;4m<<commit commit_id shortest prefix::e>>[0m[38;5;8m<<commit commit_id shortest rest::8849ae1>>[39m<<commit:: >>[38;5;2m<<commit empty::(empty)>>[39m<<commit:: >>[38;5;2m<<commit empty description placeholder::(no description set)>>[39m
[EOF]
");
// commit_summary template in transaction
let output = work_dir.run_jj(["revert", "--color=debug", "-r@", "-d@"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Reverted 1 commits as follows:
[1m[38;5;5m<<commit change_id shortest prefix::y>>[0m[38;5;8m<<commit change_id shortest rest::ostqsxw>>[39m<<commit:: >>[1m[38;5;4m<<commit commit_id shortest prefix::8b>>[0m[38;5;8m<<commit commit_id shortest rest::f82eec>>[39m<<commit:: >>[38;5;2m<<commit empty::(empty)>>[39m<<commit:: >><<commit description first_line::Revert "">>
[EOF]
"#);
}
#[test]
fn test_quiet() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Can skip message about new working copy with `--quiet`
work_dir.write_file("file1", "contents");
let output = work_dir.run_jj(["--quiet", "describe", "-m=new description"]);
insta::assert_snapshot!(output, @"");
}
#[test]
fn test_early_args() {
// Test that help output parses early args
let test_env = TestEnvironment::default();
// The default is no color.
let output = test_env.run_jj_in(".", ["help"]).success();
insta::assert_snapshot!(
output.stdout.normalized().lines().find(|l| l.contains("Commands:")).unwrap(),
@"Commands:");
// Check that output is colorized.
let output = test_env
.run_jj_in(".", ["--color=always", "help"])
.success();
insta::assert_snapshot!(
output.stdout.normalized().lines().find(|l| l.contains("Commands:")).unwrap(),
@"[1m[33mCommands:[0m");
// Check that early args are accepted after the help command
let output = test_env
.run_jj_in(".", ["help", "--color=always"])
.success();
insta::assert_snapshot!(
output.stdout.normalized().lines().find(|l| l.contains("Commands:")).unwrap(),
@"[1m[33mCommands:[0m");
// Check that early args are accepted after -h/--help
let output = test_env.run_jj_in(".", ["-h", "--color=always"]).success();
insta::assert_snapshot!(
output.stdout.normalized().lines().find(|l| l.contains("Usage:")).unwrap(),
@"[1m[33mUsage:[0m [1m[32mjj[0m [32m[OPTIONS][0m [32m<COMMAND>[0m");
let output = test_env
.run_jj_in(".", ["log", "--help", "--color=always"])
.success();
insta::assert_snapshot!(
output.stdout.normalized().lines().find(|l| l.contains("Usage:")).unwrap(),
@"[1m[33mUsage:[0m [1m[32mjj log[0m [32m[OPTIONS][0m [32m[FILESETS]...[0m");
// Early args are parsed with clap's ignore_errors(), but there is a known
// bug that causes defaults to be unpopulated. Test that the early args are
// tolerant of this bug and don't cause a crash.
test_env.run_jj_in(".", ["--no-pager", "help"]).success();
test_env
.run_jj_in(".", ["--config=ui.color=always", "help"])
.success();
}
#[test]
fn test_config_args() {
let test_env = TestEnvironment::default();
let list_config = |args: &[&str]| {
test_env.run_jj_in(
".",
[&["config", "list", "--include-overridden", "test"], args].concat(),
)
};
std::fs::write(
test_env.env_root().join("file1.toml"),
indoc! {"
test.key1 = 'file1'
test.key2 = 'file1'
"},
)
.unwrap();
std::fs::write(
test_env.env_root().join("file2.toml"),
indoc! {"
test.key3 = 'file2'
"},
)
.unwrap();
let output = list_config(&["--config=test.key1=arg1"]);
insta::assert_snapshot!(output, @r#"
test.key1 = "arg1"
[EOF]
"#);
let output = list_config(&["--config-file=file1.toml"]);
insta::assert_snapshot!(output, @r"
test.key1 = 'file1'
test.key2 = 'file1'
[EOF]
");
// --config items are inserted to a single layer internally
let output = list_config(&[
"--config=test.key1='arg1'",
"--config=test.key2.sub=true",
"--config=test.key1=arg3",
]);
insta::assert_snapshot!(output, @r#"
test.key1 = "arg3"
test.key2.sub = true
[EOF]
"#);
// --config* arguments are processed in order of appearance
let output = list_config(&[
"--config=test.key1=arg1",
"--config-file=file1.toml",
"--config=test.key2=arg3",
"--config-file=file2.toml",
]);
insta::assert_snapshot!(output, @r#"
# test.key1 = "arg1"
test.key1 = 'file1'
# test.key2 = 'file1'
test.key2 = "arg3"
test.key3 = 'file2'
[EOF]
"#);
let output = test_env.run_jj_in(".", ["config", "list", "--config=foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: --config must be specified as NAME=VALUE
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
let output = test_env.run_jj_in(".", ["config", "list", "--config-file=unknown.toml"]);
insta::with_settings!({
filters => [("(?m)^([2-9]): .*", "$1: <redacted>")],
}, {
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Failed to read configuration file
Caused by:
1: Cannot access unknown.toml
2: <redacted>
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
});
}
#[test]
fn test_invalid_config() {
// Test that we get a reasonable error if the config is invalid (#55)
let test_env = TestEnvironment::default();
test_env.add_config("[section]key = value-missing-quotes");
let output = test_env.run_jj_in(".", ["git", "init", "repo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Configuration cannot be parsed as TOML document
Caused by: TOML parse error at line 1, column 10
|
1 | [section]key = value-missing-quotes
| ^
unexpected key or value, expected newline, `#`
Hint: Check the config file: $TEST_ENV/config/config0002.toml
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_invalid_config_value() {
// Test that we get a reasonable error if a config value is invalid
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["status", "--config=snapshot.auto-track=[0]"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Invalid type or value for snapshot.auto-track
Caused by: invalid type: sequence, expected a string
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
}
#[test]
#[cfg_attr(windows, ignore = "dirs::home_dir() can't be overridden by $HOME")] // TODO
fn test_conditional_config() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(test_env.home_dir(), ["git", "init", "repo1"])
.success();
test_env
.run_jj_in(test_env.home_dir(), ["git", "init", "repo2"])
.success();
test_env.add_config(indoc! {"
aliases.foo = ['new', 'root()', '-mglobal']
[[--scope]]
--when.repositories = ['~']
aliases.foo = ['new', 'root()', '-mhome']
[[--scope]]
--when.repositories = ['~/repo1']
aliases.foo = ['new', 'root()', '-mrepo1']
"});
// Sanity check
let output = test_env.run_jj_in(".", ["config", "list", "--include-overridden", "aliases"]);
insta::assert_snapshot!(output, @r"
aliases.foo = ['new', 'root()', '-mglobal']
[EOF]
");
let output = test_env.run_jj_in(
&test_env.home_dir().join("repo1"),
["config", "list", "--include-overridden", "aliases"],
);
insta::assert_snapshot!(output, @r"
# aliases.foo = ['new', 'root()', '-mglobal']
# aliases.foo = ['new', 'root()', '-mhome']
aliases.foo = ['new', 'root()', '-mrepo1']
[EOF]
");
let output = test_env.run_jj_in(
&test_env.home_dir().join("repo2"),
["config", "list", "--include-overridden", "aliases"],
);
insta::assert_snapshot!(output, @r"
# aliases.foo = ['new', 'root()', '-mglobal']
aliases.foo = ['new', 'root()', '-mhome']
[EOF]
");
// Aliases can be expanded by using the conditional tables
let output = test_env.run_jj_in(&test_env.home_dir().join("repo1"), ["foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: royxmykx 7c486962 (empty) repo1
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
let output = test_env.run_jj_in(&test_env.home_dir().join("repo2"), ["foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: yqosqzyt 072741b8 (empty) home
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
}
/// Test that `jj` command works with the default configuration.
#[test]
fn test_default_config() {
let mut test_env = TestEnvironment::default();
let config_dir = test_env.env_root().join("empty-config");
std::fs::create_dir(&config_dir).unwrap();
test_env.set_config_path(&config_dir);
let envs_to_drop = test_env
.new_jj_cmd()
.get_envs()
.filter_map(|(name, _)| name.to_str())
.filter(|&name| name.starts_with("JJ_") && name != "JJ_CONFIG")
.map(|name| name.to_owned())
.sorted_unstable()
.collect_vec();
insta::assert_debug_snapshot!(envs_to_drop, @r#"
[
"JJ_EMAIL",
"JJ_OP_HOSTNAME",
"JJ_OP_TIMESTAMP",
"JJ_OP_USERNAME",
"JJ_RANDOMNESS_SEED",
"JJ_TIMESTAMP",
"JJ_TZ_OFFSET_MINS",
"JJ_USER",
]
"#);
let run_jj = |work_dir: &TestWorkDir, args: &[&str]| {
work_dir.run_jj_with(|cmd| {
for name in &envs_to_drop {
cmd.env_remove(name);
}
cmd.args(args)
})
};
let mut insta_settings = insta::Settings::clone_current();
insta_settings.add_filter(r"\b[a-zA-Z0-9\-._]+@[a-zA-Z0-9\-._]+\b", "<user>@<host>");
insta_settings.add_filter(
r"\b[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\b",
"<date-time>",
);
insta_settings.add_filter(r"\b[k-z]{8,12}\b", "<change-id>");
insta_settings.add_filter(r"\b[0-9a-f]{8,12}\b", "<id>");
let _guard = insta_settings.bind_to_scope();
let maskable_op_user = {
let maskable_re = Regex::new(r"^[a-zA-Z0-9\-._]+$").unwrap();
let hostname = whoami::fallible::hostname().expect("hostname should be set");
let username = whoami::fallible::username().expect("username should be set");
maskable_re.is_match(&hostname) && maskable_re.is_match(&username)
};
let output = run_jj(
&test_env.work_dir(""),
&["config", "list", r#"-Tname ++ "\n""#],
);
insta::assert_snapshot!(output, @r"
operation.hostname
operation.username
[EOF]
");
let output = run_jj(&test_env.work_dir(""), &["git", "init", "repo"]);
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_git_init.rs | cli/tests/test_git_init.rs | // Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use std::path::PathBuf;
use indoc::formatdoc;
use test_case::test_case;
use testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::to_toml_value;
fn init_git_repo(git_repo_path: &Path, bare: bool) -> gix::Repository {
let git_repo = if bare {
git::init_bare(git_repo_path)
} else {
git::init(git_repo_path)
};
let git::CommitResult { commit_id, .. } = git::add_commit(
&git_repo,
"refs/heads/my-bookmark",
"some-file",
b"some content",
"My commit message",
&[],
);
git::set_head_to_id(&git_repo, commit_id);
git_repo
}
#[must_use]
fn get_bookmark_output(work_dir: &TestWorkDir) -> CommandOutput {
work_dir.run_jj(["bookmark", "list", "--all-remotes"])
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"
separate(" ",
commit_id.short(),
bookmarks,
description,
)"#;
work_dir.run_jj(["log", "-T", template, "-r=all()"])
}
#[must_use]
fn get_colocation_status(work_dir: &TestWorkDir) -> CommandOutput {
work_dir.run_jj([
"git",
"colocation",
"status",
"--ignore-working-copy",
"--quiet", // suppress hint
])
}
fn read_git_target(work_dir: &TestWorkDir) -> String {
String::from_utf8(work_dir.read_file(".jj/repo/store/git_target").into()).unwrap()
}
#[test]
fn test_git_init_internal() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["git", "init", "repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Initialized repo in "repo"
[EOF]
"#);
let work_dir = test_env.work_dir("repo");
let jj_path = work_dir.root().join(".jj");
let repo_path = jj_path.join("repo");
let store_path = repo_path.join("store");
assert!(work_dir.root().is_dir());
assert!(jj_path.is_dir());
assert!(jj_path.join("working_copy").is_dir());
assert!(repo_path.is_dir());
assert!(store_path.is_dir());
assert!(store_path.join("git").is_dir());
assert_eq!(read_git_target(&work_dir), "git");
}
#[test]
fn test_git_init_internal_ignore_working_copy() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("").create_dir("repo");
work_dir.write_file("file1", "");
let output = work_dir.run_jj(["git", "init", "--ignore-working-copy"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --ignore-working-copy is not respected
[EOF]
[exit status: 2]
");
}
#[test]
fn test_git_init_internal_at_operation() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("").create_dir("repo");
let output = work_dir.run_jj(["git", "init", "--at-op=@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --at-op is not respected
[EOF]
[exit status: 2]
");
}
#[test_case(false; "full")]
#[test_case(true; "bare")]
fn test_git_init_external(bare: bool) {
let test_env = TestEnvironment::default();
let git_repo_path = test_env.env_root().join("git-repo");
init_git_repo(&git_repo_path, bare);
let output = test_env.run_jj_in(
".",
[
"git",
"init",
"repo",
"--git-repo",
git_repo_path.to_str().unwrap(),
],
);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Working copy (@) now at: sqpuoqvx ed6b5138 (empty) (no description set)
Parent commit (@-) : nntyzxmz e80a42cc my-bookmark | My commit message
Added 1 files, modified 0 files, removed 0 files
Initialized repo in "repo"
[EOF]
"#);
}
let work_dir = test_env.work_dir("repo");
let jj_path = work_dir.root().join(".jj");
let repo_path = jj_path.join("repo");
let store_path = repo_path.join("store");
assert!(work_dir.root().is_dir());
assert!(jj_path.is_dir());
assert!(jj_path.join("working_copy").is_dir());
assert!(repo_path.is_dir());
assert!(store_path.is_dir());
let unix_git_target_file_contents = read_git_target(&work_dir).replace('\\', "/");
if bare {
assert!(unix_git_target_file_contents.ends_with("/git-repo"));
} else {
assert!(unix_git_target_file_contents.ends_with("/git-repo/.git"));
}
// Check that the Git repo's HEAD got checked out
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ ed6b513890ae
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently not colocated with Git.
Last imported/exported Git HEAD: e80a42cccd069007c7a2bb427ac7f1d10b408633
[EOF]
");
}
}
#[test_case(false; "full")]
#[test_case(true; "bare")]
fn test_git_init_external_import_trunk(bare: bool) {
let test_env = TestEnvironment::default();
let git_repo_path = test_env.env_root().join("git-repo");
let git_repo = init_git_repo(&git_repo_path, bare);
// Add remote bookmark "trunk" for remote "origin", and set it as "origin/HEAD"
let oid = git_repo
.find_reference("refs/heads/my-bookmark")
.unwrap()
.id();
git_repo
.reference(
"refs/remotes/origin/trunk",
oid.detach(),
gix::refs::transaction::PreviousValue::MustNotExist,
"create remote ref",
)
.unwrap();
git::set_symbolic_reference(
&git_repo,
"refs/remotes/origin/HEAD",
"refs/remotes/origin/trunk",
);
let output = test_env.run_jj_in(
".",
[
"git",
"init",
"repo",
"--git-repo",
git_repo_path.to_str().unwrap(),
],
);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Setting the revset alias `trunk()` to `trunk@origin`
Working copy (@) now at: sqpuoqvx ed6b5138 (empty) (no description set)
Parent commit (@-) : nntyzxmz e80a42cc my-bookmark trunk@origin | My commit message
Added 1 files, modified 0 files, removed 0 files
Initialized repo in "repo"
[EOF]
"#);
}
// "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! {
insta::assert_snapshot!(output, @r#"
revset-aliases."trunk()" = "trunk@origin"
[EOF]
"#);
}
}
#[test]
fn test_git_init_external_import_trunk_upstream_takes_precedence() {
let test_env = TestEnvironment::default();
let git_repo_path = test_env.env_root().join("git-repo");
let git_repo = init_git_repo(&git_repo_path, false);
let oid = git_repo
.find_reference("refs/heads/my-bookmark")
.unwrap()
.id();
// Add both upstream and origin remotes with different default branches
// upstream has "develop" as default
git_repo
.reference(
"refs/remotes/upstream/develop",
oid.detach(),
gix::refs::transaction::PreviousValue::MustNotExist,
"create upstream remote ref",
)
.unwrap();
git::set_symbolic_reference(
&git_repo,
"refs/remotes/upstream/HEAD",
"refs/remotes/upstream/develop",
);
// origin has "trunk" as default
git_repo
.reference(
"refs/remotes/origin/trunk",
oid.detach(),
gix::refs::transaction::PreviousValue::MustNotExist,
"create origin remote ref",
)
.unwrap();
git::set_symbolic_reference(
&git_repo,
"refs/remotes/origin/HEAD",
"refs/remotes/origin/trunk",
);
let output = test_env.run_jj_in(
".",
[
"git",
"init",
"repo",
"--git-repo",
git_repo_path.to_str().unwrap(),
],
);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Setting the revset alias `trunk()` to `develop@upstream`
Working copy (@) now at: sqpuoqvx ed6b5138 (empty) (no description set)
Parent commit (@-) : nntyzxmz e80a42cc develop@upstream my-bookmark trunk@origin | My commit message
Added 1 files, modified 0 files, removed 0 files
Initialized repo in "repo"
[EOF]
"#);
}
// "trunk()" alias should be set to "upstream"'s default, not "origin"'s
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["config", "list", "--repo", "revset-aliases.\"trunk()\""]);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r#"
revset-aliases."trunk()" = "develop@upstream"
[EOF]
"#);
}
}
#[test]
fn test_git_init_external_ignore_working_copy() {
let test_env = TestEnvironment::default();
let git_repo_path = test_env.env_root().join("git-repo");
init_git_repo(&git_repo_path, false);
let work_dir = test_env.work_dir("").create_dir("repo");
work_dir.write_file("file1", "");
// No snapshot should be taken
let output = work_dir.run_jj([
"git",
"init",
"--ignore-working-copy",
"--git-repo",
git_repo_path.to_str().unwrap(),
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --ignore-working-copy is not respected
[EOF]
[exit status: 2]
");
}
#[test]
fn test_git_init_external_at_operation() {
let test_env = TestEnvironment::default();
let git_repo_path = test_env.env_root().join("git-repo");
init_git_repo(&git_repo_path, false);
let work_dir = test_env.work_dir("").create_dir("repo");
let output = work_dir.run_jj([
"git",
"init",
"--at-op=@-",
"--git-repo",
git_repo_path.to_str().unwrap(),
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --at-op is not respected
[EOF]
[exit status: 2]
");
}
#[test]
fn test_git_init_external_non_existent_directory() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["git", "init", "repo", "--git-repo", "non-existent"]);
insta::assert_snapshot!(output.strip_stderr_last_line(), @r"
------- stderr -------
Error: Failed to access the repository
Caused by:
1: Cannot access $TEST_ENV/non-existent
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_init_external_non_existent_git_directory() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let output = test_env.run_jj_in(".", ["git", "init", "repo", "--git-repo", "repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Failed to access the repository
Caused by:
1: Failed to open git repository
2: "$TEST_ENV/repo" does not appear to be a git repository
3: Missing HEAD at '.git/HEAD'
[EOF]
[exit status: 1]
"#);
let jj_path = work_dir.root().join(".jj");
assert!(!jj_path.exists());
}
#[test]
fn test_git_init_colocated_via_git_repo_path() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
init_git_repo(work_dir.root(), false);
let output = work_dir.run_jj(["git", "init", "--git-repo", "."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Initialized repo in "."
[EOF]
"#);
let jj_path = work_dir.root().join(".jj");
let repo_path = jj_path.join("repo");
let store_path = repo_path.join("store");
assert!(work_dir.root().is_dir());
assert!(jj_path.is_dir());
assert!(jj_path.join("working_copy").is_dir());
assert!(repo_path.is_dir());
assert!(store_path.is_dir());
assert!(
read_git_target(&work_dir)
.replace('\\', "/")
.ends_with("../../../.git")
);
// Check that the Git repo's HEAD got checked out
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: e80a42cccd069007c7a2bb427ac7f1d10b408633
[EOF]
");
// Check that the Git repo's HEAD moves
work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bacc067e7740
โ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: f3fe58bc88ccfb820b930a21297d8e48bf76ac2a
[EOF]
");
}
#[test]
fn test_git_init_colocated_via_git_repo_path_gitlink() {
let test_env = TestEnvironment::default();
// <jj_work_dir>/.git -> <git_repo_path>
let git_repo_path = test_env.env_root().join("git-repo");
let git_repo = init_git_repo(&git_repo_path, false);
let jj_work_dir = test_env.work_dir("").create_dir("repo");
git::create_gitlink(jj_work_dir.root(), git_repo.path());
assert!(jj_work_dir.root().join(".git").is_file());
let output = jj_work_dir.run_jj(["git", "init", "--git-repo", "."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Initialized repo in "."
[EOF]
"#);
insta::assert_snapshot!(read_git_target(&jj_work_dir), @"../../../.git");
// Check that the Git repo's HEAD got checked out
insta::assert_snapshot!(get_log_output(&jj_work_dir), @r"
@ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&jj_work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: e80a42cccd069007c7a2bb427ac7f1d10b408633
[EOF]
");
// Check that the Git repo's HEAD moves
jj_work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&jj_work_dir), @r"
@ bacc067e7740
โ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&jj_work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: f3fe58bc88ccfb820b930a21297d8e48bf76ac2a
[EOF]
");
}
#[cfg(unix)]
#[test]
fn test_git_init_colocated_via_git_repo_path_symlink_directory() {
let test_env = TestEnvironment::default();
// <jj_work_dir>/.git -> <git_repo_path>
let git_repo_path = test_env.env_root().join("git-repo");
init_git_repo(&git_repo_path, false);
let jj_work_dir = test_env.work_dir("").create_dir("repo");
std::os::unix::fs::symlink(git_repo_path.join(".git"), jj_work_dir.root().join(".git"))
.unwrap();
let output = jj_work_dir.run_jj(["git", "init", "--git-repo", "."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Initialized repo in "."
[EOF]
"#);
insta::assert_snapshot!(read_git_target(&jj_work_dir), @"../../../.git");
// Check that the Git repo's HEAD got checked out
insta::assert_snapshot!(get_log_output(&jj_work_dir), @r"
@ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&jj_work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: e80a42cccd069007c7a2bb427ac7f1d10b408633
[EOF]
");
// Check that the Git repo's HEAD moves
jj_work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&jj_work_dir), @r"
@ bacc067e7740
โ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&jj_work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: f3fe58bc88ccfb820b930a21297d8e48bf76ac2a
[EOF]
");
}
#[cfg(unix)]
#[test]
fn test_git_init_colocated_via_git_repo_path_symlink_directory_without_bare_config() {
let test_env = TestEnvironment::default();
// <jj_work_dir>/.git -> <git_repo_path>
let git_repo_path = test_env.env_root().join("git-repo.git");
let jj_work_dir = test_env.work_dir("repo");
// Set up git repo without core.bare set (as the "repo" tool would do.)
// The core.bare config is deduced from the directory name.
let git_repo = init_git_repo(jj_work_dir.root(), false);
git::remove_config_value(git_repo, "config", "bare");
std::fs::rename(jj_work_dir.root().join(".git"), &git_repo_path).unwrap();
std::os::unix::fs::symlink(&git_repo_path, jj_work_dir.root().join(".git")).unwrap();
let output = jj_work_dir.run_jj(["git", "init", "--git-repo", "."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Initialized repo in "."
[EOF]
"#);
insta::assert_snapshot!(read_git_target(&jj_work_dir), @"../../../.git");
// Check that the Git repo's HEAD got checked out
insta::assert_snapshot!(get_log_output(&jj_work_dir), @r"
@ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&jj_work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: e80a42cccd069007c7a2bb427ac7f1d10b408633
[EOF]
");
// Check that the Git repo's HEAD moves
jj_work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&jj_work_dir), @r"
@ bacc067e7740
โ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&jj_work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: f3fe58bc88ccfb820b930a21297d8e48bf76ac2a
[EOF]
");
}
#[cfg(unix)]
#[test]
fn test_git_init_colocated_via_git_repo_path_symlink_gitlink() {
let test_env = TestEnvironment::default();
// <jj_work_dir>/.git -> <git_workdir_path>/.git -> <git_repo_path>
let git_repo_path = test_env.env_root().join("git-repo");
let git_workdir_path = test_env.env_root().join("git-workdir");
let git_repo = init_git_repo(&git_repo_path, false);
std::fs::create_dir(&git_workdir_path).unwrap();
git::create_gitlink(&git_workdir_path, git_repo.path());
assert!(git_workdir_path.join(".git").is_file());
let jj_work_dir = test_env.work_dir("").create_dir("repo");
std::os::unix::fs::symlink(
git_workdir_path.join(".git"),
jj_work_dir.root().join(".git"),
)
.unwrap();
let output = jj_work_dir.run_jj(["git", "init", "--git-repo", "."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Initialized repo in "."
[EOF]
"#);
insta::assert_snapshot!(read_git_target(&jj_work_dir), @"../../../.git");
// Check that the Git repo's HEAD got checked out
insta::assert_snapshot!(get_log_output(&jj_work_dir), @r"
@ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&jj_work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: e80a42cccd069007c7a2bb427ac7f1d10b408633
[EOF]
");
// Check that the Git repo's HEAD moves
jj_work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&jj_work_dir), @r"
@ bacc067e7740
โ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&jj_work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: f3fe58bc88ccfb820b930a21297d8e48bf76ac2a
[EOF]
");
}
#[test]
fn test_git_init_colocated_via_git_repo_path_imported_refs() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
// Set up remote refs
test_env.run_jj_in(".", ["git", "init", "remote"]).success();
let remote_dir = test_env.work_dir("remote");
remote_dir
.run_jj(["bookmark", "create", "-r@", "local-remote", "remote-only"])
.success();
remote_dir.run_jj(["new"]).success();
remote_dir.run_jj(["git", "export"]).success();
let remote_git_path = remote_dir
.root()
.join(PathBuf::from_iter([".jj", "repo", "store", "git"]));
let set_up_local_repo = |local_path: &Path| {
let git_repo = git::clone(local_path, remote_git_path.to_str().unwrap(), None);
let git_ref = git_repo
.find_reference("refs/remotes/origin/local-remote")
.unwrap();
git_repo
.reference(
"refs/heads/local-remote",
git_ref.target().id().to_owned(),
gix::refs::transaction::PreviousValue::MustNotExist,
"move local-remote bookmark",
)
.unwrap();
};
// With remotes.origin.auto-track-bookmarks = '*'
let local_dir = test_env.work_dir("local1");
set_up_local_repo(local_dir.root());
let output = local_dir.run_jj(["git", "init", "--git-repo=."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Initialized repo in "."
[EOF]
"#);
insta::assert_snapshot!(get_bookmark_output(&local_dir), @r"
local-remote: qpvuntsm e8849ae1 (empty) (no description set)
@git: qpvuntsm e8849ae1 (empty) (no description set)
@origin: qpvuntsm e8849ae1 (empty) (no description set)
remote-only: qpvuntsm e8849ae1 (empty) (no description set)
@git: qpvuntsm e8849ae1 (empty) (no description set)
@origin: qpvuntsm e8849ae1 (empty) (no description set)
[EOF]
");
// With remotes.origin.auto-track-bookmarks = '~*'
test_env.add_config("remotes.origin.auto-track-bookmarks = '~*'");
let local_dir = test_env.work_dir("local2");
set_up_local_repo(local_dir.root());
let output = local_dir.run_jj(["git", "init", "--git-repo=."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Hint: The following remote bookmarks aren't associated with the existing local bookmarks:
local-remote@origin
Hint: Run the following command to keep local bookmarks updated on future pulls:
jj bookmark track local-remote --remote=origin
Initialized repo in "."
[EOF]
"#);
insta::assert_snapshot!(get_bookmark_output(&local_dir), @r"
local-remote: qpvuntsm e8849ae1 (empty) (no description set)
@git: qpvuntsm e8849ae1 (empty) (no description set)
local-remote@origin: qpvuntsm e8849ae1 (empty) (no description set)
remote-only@origin: qpvuntsm e8849ae1 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_git_init_colocated_dirty_working_copy() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let git_repo = init_git_repo(work_dir.root(), false);
let mut index_manager = git::IndexManager::new(&git_repo);
index_manager.add_file("new-staged-file", b"new content");
index_manager.add_file("some-file", b"new content");
index_manager.sync_index();
work_dir.write_file("unstaged-file", "new content");
insta::assert_debug_snapshot!(git::status(&git_repo), @r#"
[
GitStatus {
path: "new-staged-file",
status: Index(
Addition,
),
},
GitStatus {
path: "some-file",
status: Index(
Modification,
),
},
GitStatus {
path: "unstaged-file",
status: Worktree(
Added,
),
},
]
"#);
let output = work_dir.run_jj(["git", "init", "--git-repo", "."]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Initialized repo in "."
[EOF]
"#);
// Working-copy changes should have been snapshotted.
let output = work_dir.run_jj(["log", "-s", "--ignore-working-copy"]);
insta::assert_snapshot!(output, @r"
@ sqpuoqvx test.user@example.com 2001-02-03 08:05:07 6efc2a53
โ (no description set)
โ C {some-file => new-staged-file}
โ M some-file
โ C {some-file => unstaged-file}
โ nntyzxmz someone@example.org 1970-01-01 11:00:00 my-bookmark e80a42cc
โ My commit message
โ A some-file
โ zzzzzzzz root() 00000000
[EOF]
");
// Git index should be consistent with the working copy parent. With the
// current implementation, the index is unchanged. Since jj created new
// working copy commit, it's also okay to update the index reflecting the
// working copy commit or the working copy parent.
insta::assert_debug_snapshot!(git::status(&git_repo), @r#"
[
GitStatus {
path: ".jj/.gitignore",
status: Worktree(
Ignored,
),
},
GitStatus {
path: ".jj/repo",
status: Worktree(
Ignored,
),
},
GitStatus {
path: ".jj/working_copy",
status: Worktree(
Ignored,
),
},
GitStatus {
path: "new-staged-file",
status: Index(
Addition,
),
},
GitStatus {
path: "some-file",
status: Index(
Modification,
),
},
GitStatus {
path: "unstaged-file",
status: Worktree(
IntentToAdd,
),
},
]
"#);
}
#[test]
fn test_git_init_colocated_ignore_working_copy() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
init_git_repo(work_dir.root(), false);
work_dir.write_file("file1", "");
let output = work_dir.run_jj(["git", "init", "--ignore-working-copy", "--colocate"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --ignore-working-copy is not respected
[EOF]
[exit status: 2]
");
}
#[test]
fn test_git_init_colocated_at_operation() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
init_git_repo(work_dir.root(), false);
let output = work_dir.run_jj(["git", "init", "--at-op=@-", "--colocate"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --at-op is not respected
[EOF]
[exit status: 2]
");
}
#[test]
fn test_git_init_external_but_git_dir_exists() {
let test_env = TestEnvironment::default();
let git_repo_path = test_env.env_root().join("git-repo");
let work_dir = test_env.work_dir("repo");
git::init(&git_repo_path);
init_git_repo(work_dir.root(), false);
let output = work_dir.run_jj(["git", "init", "--git-repo", git_repo_path.to_str().unwrap()]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Initialized repo in "."
[EOF]
"#);
// The local ".git" repository is unrelated, so no commits should be imported
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e8849ae12c70
โ 000000000000
[EOF]
");
// Check that Git HEAD is not set because this isn't a colocated workspace
work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 1c1c95df80e5
โ e8849ae12c70
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently not colocated with Git.
Last imported/exported Git HEAD: (none)
[EOF]
");
}
#[test]
fn test_git_init_colocated_via_flag_git_dir_exists() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
init_git_repo(work_dir.root(), false);
let output = test_env.run_jj_in(".", ["git", "init", "--colocate", "repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Initialized repo in "repo"
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
// Check that the Git repo's HEAD got checked out
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: e80a42cccd069007c7a2bb427ac7f1d10b408633
[EOF]
");
// Check that the Git repo's HEAD moves
work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bacc067e7740
โ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: f3fe58bc88ccfb820b930a21297d8e48bf76ac2a
[EOF]
");
}
#[test]
fn test_git_init_colocated_via_config_git_dir_exists() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
init_git_repo(work_dir.root(), false);
test_env.add_config("git.colocate = true");
let output = test_env.run_jj_in(".", ["git", "init", "repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Done importing changes from the underlying Git repo.
Initialized repo in "repo"
Hint: Running `git clean -xdf` will remove `.jj/`!
[EOF]
"#);
// Check that the Git repo's HEAD got checked out
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: e80a42cccd069007c7a2bb427ac7f1d10b408633
[EOF]
");
// Check that the Git repo's HEAD moves
work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bacc067e7740
โ f3fe58bc88cc
โ e80a42cccd06 my-bookmark My commit message
โ 000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: f3fe58bc88ccfb820b930a21297d8e48bf76ac2a
[EOF]
");
}
#[test]
fn test_git_init_no_colocate() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
test_env.add_config("git.colocate = true");
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_squash_command.rs | cli/tests/test_squash_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::PathBuf;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_squash() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["bookmark", "create", "-r@", "a"])
.success();
work_dir.write_file("file1", "a\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "b"])
.success();
work_dir.write_file("file1", "b\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "c"])
.success();
work_dir.write_file("file1", "c\n");
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 22be6c4e01da c
โ 75591b1896b4 b
โ e6086990958c a
โ 000000000000 (empty)
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// Squashes the working copy into the parent by default
let output = work_dir.run_jj(["squash"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 2cf02eb8 (empty) (no description set)
Parent commit (@-) : kkmpptxz 9422c8d6 b c | (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 2cf02eb82d82 (empty)
โ 9422c8d6f294 b c
โ e6086990958c a
โ 000000000000 (empty)
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1"]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
// Can squash a given commit into its parent
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["squash", "-r", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: mzvwutvl 441a7a3a c | (no description set)
Parent commit (@-) : qpvuntsm 105931bf a b | (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 441a7a3a17b0 c
โ 105931bfedad a b
โ 000000000000 (empty)
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1", "-r", "b"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1"]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
// 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();
work_dir
.run_jj(["bookmark", "create", "-r@", "d"])
.success();
work_dir.write_file("file2", "d\n");
work_dir.run_jj(["new", "c", "d"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "e"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e05d4caaf6ce e (empty)
โโโฎ
โ โ 9bb7863cfc78 d
โ โ 22be6c4e01da c
โโโฏ
โ 75591b1896b4 b
โ e6086990958c a
โ 000000000000 (empty)
[EOF]
");
let output = work_dir.run_jj(["squash"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Cannot squash merge commits without a specified destination
Hint: Use `--into` to specify which parent to squash into
[EOF]
[exit status: 1]
");
// Can squash into a merge commit
work_dir.run_jj(["new", "e"]).success();
work_dir.write_file("file1", "e\n");
let output = work_dir.run_jj(["squash"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: xlzxqlsl 91a81249 (empty) (no description set)
Parent commit (@-) : nmzmmopx 9155baf5 e | (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 91a81249954f (empty)
โ 9155baf5ced1 e
โโโฎ
โ โ 9bb7863cfc78 d
โ โ 22be6c4e01da c
โโโฏ
โ 75591b1896b4 b
โ e6086990958c a
โ 000000000000 (empty)
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1", "-r", "e"]);
insta::assert_snapshot!(output, @r"
e
[EOF]
");
}
#[test]
fn test_squash_partial() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["bookmark", "create", "-r@", "a"])
.success();
work_dir.write_file("file1", "a\n");
work_dir.write_file("file2", "a\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "b"])
.success();
work_dir.write_file("file1", "b\n");
work_dir.write_file("file2", "b\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "c"])
.success();
work_dir.write_file("file1", "c\n");
work_dir.write_file("file2", "c\n");
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 87059ac9657b c
โ f2c9709f39e9 b
โ 64ea60be8d77 a
โ 000000000000 (empty)
[EOF]
");
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
std::fs::write(&edit_script, "dump JJ-INSTRUCTIONS instrs").unwrap();
let output = work_dir.run_jj(["squash", "-r", "b", "-i"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: mzvwutvl 34484d82 c | (no description set)
Parent commit (@-) : qpvuntsm 3141e675 a b | (no description set)
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("instrs")).unwrap(), @r"
You are moving changes from: kkmpptxz f2c9709f b | (no description set)
into commit: qpvuntsm 64ea60be a | (no description set)
The left side of the diff shows the contents of the parent commit. The
right side initially shows the contents of the commit you're moving
changes from.
Adjust the right side until the diff shows the changes you want to move
to the destination. If you don't make any changes, then all the changes
from the source will be moved into the destination.
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 34484d825f47 c
โ 3141e67514f6 a b
โ 000000000000 (empty)
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1", "-r", "a"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
// Can squash only some changes in interactive mode
work_dir.run_jj(["op", "restore", &start_op_id]).success();
std::fs::write(&edit_script, "reset file1").unwrap();
let output = work_dir.run_jj(["squash", "-r", "b", "-i"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 descendant commits
Working copy (@) now at: mzvwutvl 37e1a0ef c | (no description set)
Parent commit (@-) : kkmpptxz b41e789d b | (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 37e1a0ef57ff c
โ b41e789df71c b
โ 3af17565155e a
โ 000000000000 (empty)
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1", "-r", "a"]);
insta::assert_snapshot!(output, @r"
a
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file2", "-r", "a"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1", "-r", "b"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file2", "-r", "b"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
// Can squash only some changes in non-interactive mode
work_dir.run_jj(["op", "restore", &start_op_id]).success();
// Clear the script so we know it won't be used even without -i
std::fs::write(&edit_script, "").unwrap();
let output = work_dir.run_jj(["squash", "-r", "b", "file2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 descendant commits
Working copy (@) now at: mzvwutvl 72ff256c c | (no description set)
Parent commit (@-) : kkmpptxz dd056a92 b | (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 72ff256cd290 c
โ dd056a925eb3 b
โ cf083f1d9ccf a
โ 000000000000 (empty)
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1", "-r", "a"]);
insta::assert_snapshot!(output, @r"
a
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file2", "-r", "a"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1", "-r", "b"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file2", "-r", "b"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
// If we specify only a non-existent file, then nothing changes.
work_dir.run_jj(["op", "restore", &start_op_id]).success();
let output = work_dir.run_jj(["squash", "-r", "b", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
Nothing changed.
[EOF]
");
// 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#"
------- stderr -------
Warning: No matching entries for paths: b
Warning: The argument "b" is being interpreted as a fileset expression. To specify a revset, pass -r "b" instead.
Nothing changed.
[EOF]
"#);
// No warning if we pass a positional argument does not parse as a revset
work_dir.run_jj(["op", "restore", &start_op_id]).success();
let output = work_dir.run_jj(["squash", ".tmp"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: .tmp
Nothing changed.
[EOF]
");
// we can use --interactive and fileset together
work_dir.run_jj(["op", "restore", &start_op_id]).success();
work_dir.write_file("file3", "foo\n");
std::fs::write(&edit_script, "reset file1").unwrap();
let output = work_dir.run_jj(["squash", "-i", "file1", "file3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: mzvwutvl 3615d80e c | (no description set)
Parent commit (@-) : kkmpptxz 037106c4 b | (no description set)
[EOF]
");
let output = work_dir.run_jj(["log", "-s"]);
insta::assert_snapshot!(output, @r"
@ mzvwutvl test.user@example.com 2001-02-03 08:05:38 c 3615d80e
โ (no description set)
โ M file1
โ M file2
โ kkmpptxz test.user@example.com 2001-02-03 08:05:38 b 037106c4
โ (no description set)
โ M file1
โ M file2
โ A file3
โ qpvuntsm test.user@example.com 2001-02-03 08:05:09 a 64ea60be
โ (no description set)
โ A file1
โ A file2
โ zzzzzzzz root() 00000000
[EOF]
");
// Error if no changes selected in interactive mode
work_dir.run_jj(["op", "restore", &start_op_id]).success();
std::fs::write(&edit_script, "reset file1\0reset file2").unwrap();
let output = work_dir.run_jj(["squash", "-r", "b", "-i"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No changes selected
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 87059ac9657b c
โ f2c9709f39e9 b
โ 64ea60be8d77 a
โ 000000000000 (empty)
[EOF]
");
}
#[test]
fn test_squash_keep_emptied() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["bookmark", "create", "-r@", "a"])
.success();
work_dir.write_file("file1", "a\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "b"])
.success();
work_dir.write_file("file1", "b\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "c"])
.success();
work_dir.write_file("file1", "c\n");
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 22be6c4e01da c
โ 75591b1896b4 b
โ e6086990958c a
โ 000000000000 (empty)
[EOF]
");
let output = work_dir.run_jj(["squash", "-r", "b", "--keep-emptied"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 descendant commits
Working copy (@) now at: mzvwutvl 093590e0 c | (no description set)
Parent commit (@-) : kkmpptxz 357946cf b | (empty) (no description set)
[EOF]
");
// With --keep-emptied, b remains even though it is now empty.
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 093590e044bd c
โ 357946cf85df b (empty)
โ 2269fb3b12f5 a
โ 000000000000 (empty)
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file1", "-r", "a"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
}
#[test]
fn test_squash_from_to() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Create history like this:
// F
// |
// E C
// | |
// D B
// |/
// A
//
// 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();
work_dir.write_file("file1", "a\n");
work_dir.write_file("file2", "a\n");
work_dir.write_file("file3", "a\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "b"])
.success();
work_dir.write_file("file3", "b\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "c"])
.success();
work_dir.write_file("file1", "c\n");
work_dir.run_jj(["edit", "a"]).success();
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "d"])
.success();
work_dir.write_file("file3", "d\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "e"])
.success();
work_dir.write_file("file2", "e\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "f"])
.success();
work_dir.write_file("file2", "f\n");
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0fac1124d1ad f
โ 4ebe104a0e4e e
โ dc71a460d5d6 d
โ โ ee0b260ffc44 c
โ โ e31bf988d7c9 b
โโโฏ
โ e3e04beaf7d3 a
โ 000000000000 (empty)
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// No-op if source and destination are the same
let output = work_dir.run_jj(["squash", "--into", "@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Can squash from sibling, which results in the source being abandoned
let output = work_dir.run_jj(["squash", "--from", "c"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kmkuslsw 941ab024 f | (no description set)
Parent commit (@-) : znkkpsqq 4ebe104a e | (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 941ab024b3f8 f
โ 4ebe104a0e4e e
โ dc71a460d5d6 d
โ โ e31bf988d7c9 b c
โโโฏ
โ e3e04beaf7d3 a
โ 000000000000 (empty)
[EOF]
");
// The change from the source has been applied
let output = work_dir.run_jj(["file", "show", "file1"]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
// File `file2`, which was not changed in source, is unchanged
let output = work_dir.run_jj(["file", "show", "file2"]);
insta::assert_snapshot!(output, @r"
f
[EOF]
");
// Can squash from ancestor
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["squash", "--from", "@--"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kmkuslsw c102d2c4 f | (no description set)
Parent commit (@-) : znkkpsqq beb7c033 e | (no description set)
[EOF]
");
// The change has been removed from the source (the change pointed to by 'd'
// became empty and was abandoned)
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c102d2c4e165 f
โ beb7c0338f7c e
โ โ ee0b260ffc44 c
โ โ e31bf988d7c9 b
โโโฏ
โ e3e04beaf7d3 a d
โ 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)
let output = work_dir.run_jj(["file", "show", "file2"]);
insta::assert_snapshot!(output, @r"
f
[EOF]
");
// Can squash from descendant
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["squash", "--from", "e", "--into", "d"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: kmkuslsw 1bc21d4e f | (no description set)
Parent commit (@-) : vruxwmqv 8b6b080a d e | (no description set)
[EOF]
");
// The change has been removed from the source (the change pointed to by 'e'
// became empty and was abandoned)
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 1bc21d4e92d6 f
โ 8b6b080ab587 d e
โ โ ee0b260ffc44 c
โ โ e31bf988d7c9 b
โโโฏ
โ e3e04beaf7d3 a
โ 000000000000 (empty)
[EOF]
");
// The change from the source has been applied
let output = work_dir.run_jj(["file", "show", "file2", "-r", "d"]);
insta::assert_snapshot!(output, @r"
e
[EOF]
");
// Can squash into the sources
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["squash", "--from", "e::f", "--into", "d"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: pkstwlsy 76baa567 (empty) (no description set)
Parent commit (@-) : vruxwmqv 415e4069 d e f | (no description set)
[EOF]
");
// The change has been removed from the source (the change pointed to by 'e'
// became empty and was abandoned)
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 76baa567ed0a (empty)
โ 415e40694e88 d e f
โ โ ee0b260ffc44 c
โ โ e31bf988d7c9 b
โโโฏ
โ e3e04beaf7d3 a
โ 000000000000 (empty)
[EOF]
");
// The change from the source has been applied
let output = work_dir.run_jj(["file", "show", "file2", "-r", "d"]);
insta::assert_snapshot!(output, @r"
f
[EOF]
");
}
#[test]
fn test_squash_from_to_partial() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_diff_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Create history like this:
// C
// |
// D B
// |/
// A
work_dir
.run_jj(["bookmark", "create", "-r@", "a"])
.success();
work_dir.write_file("file1", "a\n");
work_dir.write_file("file2", "a\n");
work_dir.write_file("file3", "a\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "b"])
.success();
work_dir.write_file("file3", "b\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "c"])
.success();
work_dir.write_file("file1", "c\n");
work_dir.write_file("file2", "c\n");
work_dir.run_jj(["edit", "a"]).success();
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "d"])
.success();
work_dir.write_file("file3", "d\n");
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ dc71a460d5d6 d
โ โ 499d601f6046 c
โ โ e31bf988d7c9 b
โโโฏ
โ e3e04beaf7d3 a
โ 000000000000 (empty)
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// 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, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 85589465 d | (no description set)
Parent commit (@-) : qpvuntsm e3e04bea a | (no description set)
Added 0 files, modified 2 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 85589465a5f7 d
โ โ e31bf988d7c9 b c
โโโฏ
โ e3e04beaf7d3 a
โ 000000000000 (empty)
[EOF]
");
// The changes from the source has been applied
let output = work_dir.run_jj(["file", "show", "file1"]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
let output = work_dir.run_jj(["file", "show", "file2"]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
// File `file3`, which was not changed in source, is unchanged
let output = work_dir.run_jj(["file", "show", "file3"]);
insta::assert_snapshot!(output, @r"
d
[EOF]
");
// Can squash only part of the change in interactive mode
work_dir.run_jj(["op", "restore", &setup_opid]).success();
std::fs::write(&edit_script, "reset file2").unwrap();
let output = work_dir.run_jj(["squash", "-i", "--from", "c"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 62bd5cd9 d | (no description set)
Parent commit (@-) : qpvuntsm e3e04bea a | (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 62bd5cd9f413 d
โ โ 2748f30463ed c
โ โ e31bf988d7c9 b
โโโฏ
โ e3e04beaf7d3 a
โ 000000000000 (empty)
[EOF]
");
// The selected change from the source has been applied
let output = work_dir.run_jj(["file", "show", "file1"]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
// The unselected change from the source has not been applied
let output = work_dir.run_jj(["file", "show", "file2"]);
insta::assert_snapshot!(output, @r"
a
[EOF]
");
// File `file3`, which was changed in source's parent, is unchanged
let output = work_dir.run_jj(["file", "show", "file3"]);
insta::assert_snapshot!(output, @r"
d
[EOF]
");
// Can squash only part of the change from a sibling 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, "").unwrap();
let output = work_dir.run_jj(["squash", "--from", "c", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 76bf6139 d | (no description set)
Parent commit (@-) : qpvuntsm e3e04bea a | (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 76bf613928cf d
โ โ 9d4418d4828e c
โ โ e31bf988d7c9 b
โโโฏ
โ e3e04beaf7d3 a
โ 000000000000 (empty)
[EOF]
");
// The selected change from the source has been applied
let output = work_dir.run_jj(["file", "show", "file1"]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
// The unselected change from the source has not been applied
let output = work_dir.run_jj(["file", "show", "file2"]);
insta::assert_snapshot!(output, @r"
a
[EOF]
");
// File `file3`, which was changed in source's parent, is unchanged
let output = work_dir.run_jj(["file", "show", "file3"]);
insta::assert_snapshot!(output, @r"
d
[EOF]
");
// 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, "").unwrap();
let output = work_dir.run_jj(["squash", "--from", "c", "--into", "b", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ dc71a460d5d6 d
โ โ f964ce4bca71 c
โ โ e12c895adba6 b
โโโฏ
โ e3e04beaf7d3 a
โ 000000000000 (empty)
[EOF]
");
// The selected change from the source has been applied
let output = work_dir.run_jj(["file", "show", "file1", "-r", "b"]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
// The unselected change from the source has not been applied
let output = work_dir.run_jj(["file", "show", "file2", "-r", "b"]);
insta::assert_snapshot!(output, @r"
a
[EOF]
");
// If we specify only a non-existent file, then nothing changes.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["squash", "--from", "c", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
Nothing changed.
[EOF]
");
}
#[test]
fn test_squash_from_multiple() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Create history like this:
// F
// |
// E
// /|\
// B C D
// \|/
// A
work_dir
.run_jj(["bookmark", "create", "-r@", "a"])
.success();
work_dir.write_file("file", "a\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "b"])
.success();
work_dir.write_file("file", "b\n");
work_dir.run_jj(["new", "@-"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "c"])
.success();
work_dir.write_file("file", "c\n");
work_dir.run_jj(["new", "@-"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "d"])
.success();
work_dir.write_file("file", "d\n");
work_dir.run_jj(["new", "visible_heads()"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "e"])
.success();
work_dir.write_file("file", "e\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "f"])
.success();
work_dir.write_file("file", "f\n");
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 65e53f39b4d6 f
โ 7dc592781647 e
โโโฌโโฎ
โ โ โ fed4d1a2e491 b
โ โ โ d7e94ec7e73e c
โ โโโฏ
โ โ 8acbb71558d5 d
โโโฏ
โ e88768e65e67 a
โ 000000000000 (empty)
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// Squash a few commits sideways
let output = work_dir.run_jj(["squash", "--from=b", "--from=c", "--into=d"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 descendant commits
Working copy (@) now at: kpqxywon d64492cf f | (no description set)
Parent commit (@-) : yostqsxw 7e58dc67 e | (no description set)
New conflicts appeared in 1 commits:
yqosqzyt 4198211f d | (conflict) (no description set)
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new yqosqzyt
Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved, you can inspect the result with `jj diff`.
Then run `jj squash` to move the resolution into the conflicted commit.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d64492cf8e79 f
โ 7e58dc679ec0 e
โโโฎ
ร โ 4198211f54c1 d
โโโฏ
โ e88768e65e67 a b c
โ 000000000000 (empty)
[EOF]
");
// The changes from the sources have been applied
let output = work_dir.run_jj(["file", "show", "-r=d", "file"]);
insta::assert_snapshot!(output, @r"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: qpvuntsm e88768e6 (parents of squashed revision)
\\\\\\\ to: yqosqzyt 8acbb715 (squash destination)
-a
+d
%%%%%%% diff from: qpvuntsm e88768e6 (parents of squashed revision)
\\\\\\\ to: kkmpptxz fed4d1a2 (squashed revision)
-a
+b
+++++++ mzvwutvl d7e94ec7 (squashed revision)
c
>>>>>>> conflict 1 of 1 ends
[EOF]
");
// Squash a few commits up an down
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["squash", "--from=b|c|f", "--into=e"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: xznxytkn ec32238b (empty) (no description set)
Parent commit (@-) : yostqsxw 5298eef6 e f | (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ ec32238b2be5 (empty)
โ 5298eef6bca5 e f
โโโฎ
โ โ 8acbb71558d5 d
โโโฏ
โ e88768e65e67 a b c
โ 000000000000 (empty)
[EOF]
");
// The changes from the sources have been applied to the destination
let output = work_dir.run_jj(["file", "show", "-r=e", "file"]);
insta::assert_snapshot!(output, @r"
f
[EOF]
");
// Empty squash shouldn't crash
let output = work_dir.run_jj(["squash", "--from=none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
}
#[test]
fn test_squash_from_multiple_partial() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Create history like this:
// F
// |
// E
// /|\
// B C D
// \|/
// A
work_dir
.run_jj(["bookmark", "create", "-r@", "a"])
.success();
work_dir.write_file("file1", "a\n");
work_dir.write_file("file2", "a\n");
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "b"])
.success();
work_dir.write_file("file1", "b\n");
work_dir.write_file("file2", "b\n");
work_dir.run_jj(["new", "@-"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "c"])
.success();
work_dir.write_file("file1", "c\n");
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_debug_init_simple_command.rs | cli/tests/test_debug_init_simple_command.rs | // Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::common::TestEnvironment;
#[test]
fn test_init_local() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["debug", "init-simple", "repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Initialized repo in "repo"
[EOF]
"#);
let workspace_root = test_env.env_root().join("repo");
let jj_path = workspace_root.join(".jj");
let repo_path = jj_path.join("repo");
let store_path = repo_path.join("store");
assert!(workspace_root.is_dir());
assert!(jj_path.is_dir());
assert!(jj_path.join("working_copy").is_dir());
assert!(repo_path.is_dir());
assert!(store_path.is_dir());
assert!(store_path.join("commits").is_dir());
assert!(store_path.join("trees").is_dir());
assert!(store_path.join("files").is_dir());
assert!(store_path.join("symlinks").is_dir());
assert!(store_path.join("conflicts").is_dir());
let output = test_env.run_jj_in(
".",
["debug", "init-simple", "--ignore-working-copy", "repo2"],
);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --ignore-working-copy is not respected
[EOF]
[exit status: 2]
");
let output = test_env.run_jj_in(".", ["debug", "init-simple", "--at-op=@-", "repo3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --at-op is not respected
[EOF]
[exit status: 2]
");
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/tests/test_describe_command.rs | cli/tests/test_describe_command.rs | // Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::PathBuf;
use indoc::indoc;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::force_interactive;
#[test]
fn test_describe() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Set a description using `-m` flag
let output = work_dir.run_jj(["describe", "-m", "description from CLI"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 7b186b4f (empty) description from CLI
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// Set the same description using `-m` flag, but with explicit newline
let output = work_dir.run_jj(["describe", "-m", "description from CLI\n"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Check that the text file gets initialized with the current description and
// make no changes
std::fs::write(&edit_script, "dump editor0").unwrap();
let output = work_dir.run_jj(["describe"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor0")).unwrap(), @r#"
description from CLI
JJ: Change ID: qpvuntsm
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
// Set a description in editor
std::fs::write(&edit_script, "write\ndescription from editor").unwrap();
let output = work_dir.run_jj(["describe"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 28173c3e (empty) description from editor
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// Lines in editor starting with "JJ: " are ignored
std::fs::write(
&edit_script,
"write\nJJ: ignored\ndescription among comment\nJJ: ignored",
)
.unwrap();
let output = work_dir.run_jj(["describe"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm e7488502 (empty) description among comment
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// Multi-line description
std::fs::write(&edit_script, "write\nline1\nline2\n\nline4\n\n").unwrap();
let output = work_dir.run_jj(["describe"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 7438c202 (empty) line1
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["log", "--no-graph", "-r@", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
line1
line2
line4
[EOF]
");
// Multi-line description again with CRLF, which should make no changes
std::fs::write(&edit_script, "write\nline1\r\nline2\r\n\r\nline4\r\n\r\n").unwrap();
let output = work_dir.run_jj(["describe"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Multi-line description starting with newlines
std::fs::write(&edit_script, "write\n\n\nline1\nline2").unwrap();
let output = work_dir.run_jj(["describe"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm f38e2bd7 (empty) line1
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["log", "--no-graph", "-r@", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
line1
line2
[EOF]
");
// Clear description
let output = work_dir.run_jj(["describe", "-m", ""]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 7c00df81 (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
std::fs::write(&edit_script, "write\n").unwrap();
let output = work_dir.run_jj(["describe"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Fails if the editor fails
std::fs::write(&edit_script, "fail").unwrap();
let output = work_dir.run_jj(["describe"]);
insta::with_settings!({
filters => [
(r"\bEditor '[^']*'", "Editor '<redacted>'"),
(r"in .*(editor-)[^.]*(\.jjdescription)\b", "in <redacted>$1<redacted>$2"),
("exit code", "exit status"), // Windows
],
}, {
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to edit description
Caused by: Editor '<redacted>' exited with exit status: 1
Hint: Edited description is left in <redacted>editor-<redacted>.jjdescription
[EOF]
[exit status: 1]
");
});
// ignore everything after the first ignore-rest line
std::fs::write(
&edit_script,
indoc! {"
write
description from editor
content of message from editor
JJ: ignore-rest
content after ignore line should not be included
JJ: ignore-rest
ignore everything until EOF or next description
"},
)
.unwrap();
let output = work_dir.run_jj(["describe"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 0ec68094 (empty) description from editor
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["log", "--no-graph", "-r@", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
description from editor
content of message from editor
[EOF]
");
}
#[test]
fn test_describe_editor_env() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Fails if the editor doesn't exist
let output = work_dir.run_jj_with(|cmd| {
cmd.arg("describe")
.env("EDITOR", "this-editor-does-not-exist")
});
insta::assert_snapshot!(
output.normalize_stderr_with(|s| s.split_inclusive('\n').take(3).collect()), @r"
------- stderr -------
Error: Failed to edit description
Caused by:
1: Failed to run editor 'this-editor-does-not-exist'
[EOF]
[exit status: 1]
");
// `$VISUAL` overrides `$EDITOR`
let output = work_dir.run_jj_with(|cmd| {
cmd.arg("describe")
.env("VISUAL", "bad-editor-from-visual-env")
.env("EDITOR", "bad-editor-from-editor-env")
});
insta::assert_snapshot!(
output.normalize_stderr_with(|s| s.split_inclusive('\n').take(3).collect()), @r"
------- stderr -------
Error: Failed to edit description
Caused by:
1: Failed to run editor 'bad-editor-from-visual-env'
[EOF]
[exit status: 1]
");
// `ui.editor` config overrides `$VISUAL`
test_env.add_config(r#"ui.editor = "bad-editor-from-config""#);
let output = work_dir.run_jj_with(|cmd| {
cmd.arg("describe")
.env("VISUAL", "bad-editor-from-visual-env")
});
insta::assert_snapshot!(
output.normalize_stderr_with(|s| s.split_inclusive('\n').take(3).collect()), @r"
------- stderr -------
Error: Failed to edit description
Caused by:
1: Failed to run editor 'bad-editor-from-config'
[EOF]
[exit status: 1]
");
// `$JJ_EDITOR` overrides `ui.editor` config
let output = work_dir.run_jj_with(|cmd| {
cmd.arg("describe")
.env("JJ_EDITOR", "bad-jj-editor-from-jj-editor-env")
});
insta::assert_snapshot!(
output.normalize_stderr_with(|s| s.split_inclusive('\n').take(3).collect()), @r"
------- stderr -------
Error: Failed to edit description
Caused by:
1: Failed to run editor 'bad-jj-editor-from-jj-editor-env'
[EOF]
[exit status: 1]
");
}
#[test]
fn test_describe_no_matching_revisions() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["describe", "none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No revisions to describe.
[EOF]
");
}
#[test]
fn test_describe_multiple_commits() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Initial setup
work_dir.run_jj(["new"]).success();
work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 3cd3b246e098
โ 43444d88b009
โ e8849ae12c70
โ 000000000000
[EOF]
");
// Set the description of multiple commits using `-m` flag
let output = work_dir.run_jj(["describe", "-r@", "-r@--", "-m", "description from CLI"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Updated 2 commits
Rebased 1 descendant commits
Working copy (@) now at: kkmpptxz 4c3ccb9d (empty) description from CLI
Parent commit (@-) : rlvkpnrz 650ac8f2 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 4c3ccb9d4fb2 description from CLI
โ 650ac8f249be
โ 0ff65c91377a description from CLI
โ 000000000000
[EOF]
");
// Check that the text file gets initialized with the current description of
// each commit and doesn't update commits if no changes are made.
// Commit descriptions are edited in topological order
std::fs::write(&edit_script, "dump editor0").unwrap();
let output = work_dir.run_jj(["describe", "-r@", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor0")).unwrap(), @r#"
JJ: Enter or edit commit descriptions after the `JJ: describe` lines.
JJ: Warning:
JJ: - The text you enter will be lost on a syntax error.
JJ: - The syntax of the separator lines may change in the future.
JJ:
JJ: describe 650ac8f249be -------
JJ: Change ID: rlvkpnrz
JJ:
JJ: describe 4c3ccb9d4fb2 -------
description from CLI
JJ: Change ID: kkmpptxz
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
// Set the description of multiple commits in the editor
std::fs::write(
&edit_script,
indoc! {"
write
JJ: Enter or edit commit descriptions after the `JJ: describe` lines.
JJ: More header tests. Library tests verify parsing in other situations.
JJ: describe 650ac8f249be -------
description from editor of @-
further commit message of @-
JJ: describe 4c3ccb9d4fb2 -------
description from editor of @
further commit message of @
JJ: Lines starting with \"JJ: \" (like this one) will be removed.
"},
)
.unwrap();
let output = work_dir.run_jj(["describe", "@", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Updated 2 commits
Working copy (@) now at: kkmpptxz 87c0f3c7 (empty) description from editor of @
Parent commit (@-) : rlvkpnrz 9b9041eb (empty) description from editor of @-
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 87c0f3c75a22 description from editor of @
โ
โ further commit message of @
โ 9b9041eb2f04 description from editor of @-
โ
โ further commit message of @-
โ 0ff65c91377a description from CLI
โ 000000000000
[EOF]
");
// Fails if the edited message has a commit with multiple descriptions
std::fs::write(
&edit_script,
indoc! {"
write
JJ: describe 9b9041eb2f04 -------
first description from editor of @-
further commit message of @-
JJ: describe 9b9041eb2f04 -------
second description from editor of @-
further commit message of @-
JJ: describe 87c0f3c75a22 -------
updated description from editor of @
further commit message of @
JJ: Lines starting with \"JJ: \" (like this one) will be removed.
"},
)
.unwrap();
let output = work_dir.run_jj(["describe", "@", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The following commits were found in the edited message multiple times: 9b9041eb2f04
[EOF]
[exit status: 1]
");
// Fails if the edited message has unexpected commit IDs
std::fs::write(
&edit_script,
indoc! {"
write
JJ: describe 000000000000 -------
unexpected commit ID
JJ: describe 9b9041eb2f04 -------
description from editor of @-
further commit message of @-
JJ: describe 87c0f3c75a22 -------
description from editor of @
further commit message of @
JJ: Lines starting with \"JJ: \" (like this one) will be removed.
"},
)
.unwrap();
let output = work_dir.run_jj(["describe", "@", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The following commits were not being edited, but were found in the edited message: 000000000000
[EOF]
[exit status: 1]
");
// Fails if the edited message has missing commit messages
std::fs::write(
&edit_script,
indoc! {"
write
JJ: describe 87c0f3c75a22 -------
description from editor of @
further commit message of @
JJ: Lines starting with \"JJ: \" (like this one) will be removed.
"},
)
.unwrap();
let output = work_dir.run_jj(["describe", "@", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The description for the following commits were not found in the edited message: 9b9041eb2f04
[EOF]
[exit status: 1]
");
// Fails if the edited message has a line which does not have any preceding
// `JJ: describe` headers
std::fs::write(
&edit_script,
indoc! {"
write
description from editor of @-
JJ: describe 9b9041eb2f04 -------
description from editor of @
JJ: Lines starting with \"JJ: \" (like this one) will be removed.
"},
)
.unwrap();
let output = work_dir.run_jj(["describe", "@", "@-"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Found the following line without a commit header: "description from editor of @-"
[EOF]
[exit status: 1]
"#);
// Fails if the editor fails
std::fs::write(&edit_script, "fail").unwrap();
let output = work_dir.run_jj(["describe", "@", "@-"]);
insta::with_settings!({
filters => [
(r"\bEditor '[^']*'", "Editor '<redacted>'"),
(r"in .*(editor-)[^.]*(\.jjdescription)\b", "in <redacted>$1<redacted>$2"),
("exit code", "exit status"), // Windows
],
}, {
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to edit description
Caused by: Editor '<redacted>' exited with exit status: 1
Hint: Edited description is left in <redacted>editor-<redacted>.jjdescription
[EOF]
[exit status: 1]
");
});
// describe lines should take priority over ignore-rest
std::fs::write(
&edit_script,
indoc! {"
write
JJ: describe 9b9041eb2f04 -------
description from editor for @-
JJ: ignore-rest
content after ignore-rest should not be included
JJ: describe 0ff65c91377a -------
description from editor for @--
JJ: ignore-rest
each commit should skip their own ignore-rest
"},
)
.unwrap();
let output = work_dir.run_jj(["describe", "@-", "@--"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Updated 2 commits
Rebased 1 descendant commits
Working copy (@) now at: kkmpptxz 5a6249e9 (empty) description from editor of @
Parent commit (@-) : rlvkpnrz d1c1edbd (empty) description from editor for @-
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 5a6249e9e71a description from editor of @
โ
โ further commit message of @
โ d1c1edbd5595 description from editor for @-
โ a8bf976d72fb description from editor for @--
โ 000000000000
[EOF]
");
}
#[test]
fn test_multiple_message_args() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Set a description using `-m` flag
let output = work_dir.run_jj([
"describe",
"-m",
"First Paragraph from CLI",
"-m",
"Second Paragraph from CLI",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 9b8ad205 (empty) First Paragraph from CLI
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["log", "--no-graph", "-r@", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
First Paragraph from CLI
Second Paragraph from CLI
[EOF]
");
// Set the same description, with existing newlines
let output = work_dir.run_jj([
"describe",
"-m",
"First Paragraph from CLI\n",
"-m",
"Second Paragraph from CLI\n",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Use an empty -m flag between paragraphs to insert an extra blank line
let output = work_dir.run_jj([
"describe",
"-m",
"First Paragraph from CLI\n",
"--message",
"",
"-m",
"Second Paragraph from CLI",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm ac46ea93 (empty) First Paragraph from CLI
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["log", "--no-graph", "-r@", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
First Paragraph from CLI
Second Paragraph from CLI
[EOF]
");
}
#[test]
fn test_describe_stdin_description() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj_with(|cmd| {
force_interactive(cmd)
.args(["describe", "--stdin"])
.write_stdin("first stdin\nsecond stdin")
});
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm b9990801 (empty) first stdin
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["log", "--no-graph", "-r@", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
first stdin
second stdin
[EOF]
");
}
#[test]
fn test_describe_default_description() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
test_env.add_config(r#"template-aliases.default_commit_description = '"\n\nTESTED=TODO\n"'"#);
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
std::fs::write(edit_script, ["dump editor"].join("\0")).unwrap();
let output = work_dir.run_jj(["describe"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 7276dfff TESTED=TODO
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
TESTED=TODO
JJ: Change ID: qpvuntsm
JJ: This commit contains the following changes:
JJ: A file1
JJ: A file2
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
// Default description shouldn't be used if --no-edit
work_dir.run_jj(["new", "root()"]).success();
let output = work_dir.run_jj(["describe", "--no-edit", "--reset-author"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: `jj describe --no-edit` is deprecated; use `jj metaedit` instead
Warning: `jj describe --reset-author` is deprecated; use `jj metaedit --update-author` instead
Working copy (@) now at: kkmpptxz 7118bcb8 (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_describe_author() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
std::fs::write(edit_script, ["dump editor"].join("\0")).unwrap();
test_env.add_config(indoc! {r#"
[template-aliases]
'format_signature(signature)' = 'signature.name() ++ " " ++ signature.email() ++ " " ++ signature.timestamp()'
[templates]
draft_commit_description = '''
concat(
description,
"\n",
indent(
"JJ: ",
concat(
"Author: " ++ format_detailed_signature(author) ++ "\n",
"Committer: " ++ format_detailed_signature(committer) ++ "\n",
"\n",
diff.stat(76),
),
),
)
'''
"#});
let get_signatures = || {
let template = r#"format_signature(author) ++ "\n" ++ format_signature(committer)"#;
work_dir.run_jj(["log", "-r..", "-T", template])
};
// Initial setup
work_dir.run_jj(["new"]).success();
work_dir.run_jj(["new"]).success();
work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_signatures(), @r"
@ Test User test.user@example.com 2001-02-03 04:05:10.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:10.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:09.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:09.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:08.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:08.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:07.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:07.000 +07:00
~
[EOF]
");
// Change the author for the latest commit (the committer is always reset)
work_dir
.run_jj([
"describe",
"--author",
"Super Seeder <super.seeder@example.com>",
])
.success();
insta::assert_snapshot!(get_signatures(), @r"
@ Super Seeder super.seeder@example.com 2001-02-03 04:05:12.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:12.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:09.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:09.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:08.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:08.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:07.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:07.000 +07:00
~
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
JJ: Author: Super Seeder <super.seeder@example.com> (2001-02-03 08:05:12)
JJ: Committer: Test User <test.user@example.com> (2001-02-03 08:05:12)
JJ: 0 files changed, 0 insertions(+), 0 deletions(-)
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
// Change the author for multiple commits (the committer is always reset)
work_dir
.run_jj([
"describe",
"@---",
"@-",
"--no-edit",
"--author",
"Super Seeder <super.seeder@example.com>",
])
.success();
insta::assert_snapshot!(get_signatures(), @r"
@ Super Seeder super.seeder@example.com 2001-02-03 04:05:12.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
โ Super Seeder super.seeder@example.com 2001-02-03 04:05:14.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
โ Super Seeder super.seeder@example.com 2001-02-03 04:05:14.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
~
[EOF]
");
// Reset the author for the latest commit (the committer is always reset)
work_dir
.run_jj([
"describe",
"--config=user.name=Ove Ridder",
"--config=user.email=ove.ridder@example.com",
"--no-edit",
"--reset-author",
])
.success();
insta::assert_snapshot!(get_signatures(), @r"
@ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:16.000 +07:00
โ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:16.000 +07:00
โ Super Seeder super.seeder@example.com 2001-02-03 04:05:14.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
โ Super Seeder super.seeder@example.com 2001-02-03 04:05:14.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
~
[EOF]
");
// Reset the author for multiple commits (the committer is always reset)
work_dir
.run_jj([
"describe",
"@---",
"@-",
"--config=user.name=Ove Ridder",
"--config=user.email=ove.ridder@example.com",
"--reset-author",
])
.success();
insta::assert_snapshot!(get_signatures(), @r"
@ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:18.000 +07:00
โ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:18.000 +07:00
โ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:18.000 +07:00
โ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:18.000 +07:00
โ Test User test.user@example.com 2001-02-03 04:05:14.000 +07:00
โ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:18.000 +07:00
โ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:18.000 +07:00
โ Ove Ridder ove.ridder@example.com 2001-02-03 04:05:18.000 +07:00
~
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
JJ: Enter or edit commit descriptions after the `JJ: describe` lines.
JJ: Warning:
JJ: - The text you enter will be lost on a syntax error.
JJ: - The syntax of the separator lines may change in the future.
JJ:
JJ: describe b6fdbcc93170 -------
JJ: Author: Ove Ridder <ove.ridder@example.com> (2001-02-03 08:05:18)
JJ: Committer: Ove Ridder <ove.ridder@example.com> (2001-02-03 08:05:18)
JJ: 0 files changed, 0 insertions(+), 0 deletions(-)
JJ:
JJ: describe 3c9fefe4bede -------
JJ: Author: Ove Ridder <ove.ridder@example.com> (2001-02-03 08:05:18)
JJ: Committer: Ove Ridder <ove.ridder@example.com> (2001-02-03 08:05:18)
JJ: 0 files changed, 0 insertions(+), 0 deletions(-)
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
}
#[test]
fn test_describe_avoids_unc() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
std::fs::write(edit_script, "dump-path path").unwrap();
work_dir.run_jj(["describe"]).success();
let edited_path =
PathBuf::from(std::fs::read_to_string(test_env.env_root().join("path")).unwrap());
// While `assert!(!edited_path.starts_with("//?/"))` could work here in most
// cases, it fails when it is not safe to strip the prefix, such as paths
// over 260 chars.
assert_eq!(edited_path, dunce::simplified(&edited_path));
}
#[test]
fn test_describe_with_editor_and_message_args_opens_editor() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
std::fs::write(edit_script, ["dump editor"].join("\0")).unwrap();
let output = work_dir.run_jj(["describe", "-m", "message from command line", "--editor"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm f9bee6de (empty) message from command line
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
message from command line
JJ: Change ID: qpvuntsm
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
}
#[test]
fn test_describe_change_with_existing_message_with_editor_and_message_args_opens_editor() {
let mut test_env = TestEnvironment::default();
let edit_script = test_env.set_up_fake_editor();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj(["describe", "-m", "original message"])
.success();
std::fs::write(edit_script, ["dump editor"].join("\0")).unwrap();
let output = work_dir.run_jj(["describe", "-m", "new message", "--editor"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm f8f14f7c (empty) new message
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor")).unwrap(), @r#"
new message
JJ: Change ID: qpvuntsm
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
}
#[test]
fn test_editor_cannot_be_used_with_no_edit() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["describe", "--no-edit", "--editor"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--no-edit' cannot be used with '--editor'
Usage: jj describe [OPTIONS] [REVSETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.