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/tests/test_git_colocated.rs | cli/tests/test_git_colocated.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::fmt::Write as _;
use std::path::Path;
use testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_git_colocated() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let git_repo = git::init(work_dir.root());
// Create an initial commit in Git
let tree_id = git::add_commit(
&git_repo,
"refs/heads/master",
"file",
b"contents",
"initial",
&[],
)
.tree_id;
git::checkout_tree_index(&git_repo, tree_id);
assert_eq!(work_dir.read_file("file"), b"contents");
insta::assert_snapshot!(
git_repo.head_id().unwrap().to_string(),
@"97358f54806c7cd005ed5ade68a779595efbae7e"
);
// Import the repo
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 524826059adc6f74de30f6be8f8eb86715d75b62
○ 97358f54806c7cd005ed5ade68a779595efbae7e master initial
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(
git_repo.head_id().unwrap().to_string(),
@"97358f54806c7cd005ed5ade68a779595efbae7e"
);
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: 97358f54806c7cd005ed5ade68a779595efbae7e
[EOF]
");
// Modify the working copy. The working-copy commit should changed, but the Git
// HEAD commit should not
work_dir.write_file("file", "modified");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 9dfe8c7005c8dff6078ecdfd953c6bfddc633c90
○ 97358f54806c7cd005ed5ade68a779595efbae7e master initial
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(
git_repo.head_id().unwrap().to_string(),
@"97358f54806c7cd005ed5ade68a779595efbae7e"
);
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: 97358f54806c7cd005ed5ade68a779595efbae7e
[EOF]
");
// Create a new change from jj and check that it's reflected in Git
work_dir.run_jj(["new"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 4ddddef596e9d68f729f1be9e1b2cdaaf45bef08
○ 9dfe8c7005c8dff6078ecdfd953c6bfddc633c90
○ 97358f54806c7cd005ed5ade68a779595efbae7e master initial
◆ 0000000000000000000000000000000000000000
[EOF]
");
assert!(git_repo.head().unwrap().is_detached());
insta::assert_snapshot!(
git_repo.head_id().unwrap().to_string(),
@"9dfe8c7005c8dff6078ecdfd953c6bfddc633c90"
);
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: 9dfe8c7005c8dff6078ecdfd953c6bfddc633c90
[EOF]
");
}
#[test]
fn test_git_colocated_intent_to_add() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
// A file added directly on top of the root commit should be marked as
// intent-to-add
work_dir.write_file("file1.txt", "contents");
work_dir.run_jj(["status"]).success();
insta::assert_snapshot!(get_index_state(work_dir.root()), @"Unconflicted Mode(FILE) e69de29bb2d1 ctime=0:0 mtime=0:0 size=0 flags=20004000 file1.txt");
// Previously, this would fail due to the empty blob not being written to the
// store when marking files as intent-to-add.
work_dir.run_jj(["util", "gc"]).success();
// Another new file should be marked as intent-to-add
work_dir.run_jj(["new"]).success();
work_dir.write_file("file2.txt", "contents");
work_dir.run_jj(["status"]).success();
insta::assert_snapshot!(get_index_state(work_dir.root()), @r"
Unconflicted Mode(FILE) 0839b2e9412b ctime=0:0 mtime=0:0 size=0 flags=0 file1.txt
Unconflicted Mode(FILE) e69de29bb2d1 ctime=0:0 mtime=0:0 size=0 flags=20004000 file2.txt
");
let op_id_new_file = work_dir.current_operation_id();
// After creating a new commit, it should not longer be marked as intent-to-add
work_dir.run_jj(["new"]).success();
work_dir.write_file("file2.txt", "contents");
work_dir.run_jj(["status"]).success();
insta::assert_snapshot!(get_index_state(work_dir.root()), @r"
Unconflicted Mode(FILE) 0839b2e9412b ctime=0:0 mtime=0:0 size=0 flags=0 file1.txt
Unconflicted Mode(FILE) 0839b2e9412b ctime=0:0 mtime=0:0 size=0 flags=0 file2.txt
");
// If we edit an existing commit, new files are marked as intent-to-add
work_dir.run_jj(["edit", "@-"]).success();
work_dir.run_jj(["status"]).success();
insta::assert_snapshot!(get_index_state(work_dir.root()), @r"
Unconflicted Mode(FILE) 0839b2e9412b ctime=0:0 mtime=0:0 size=0 flags=0 file1.txt
Unconflicted Mode(FILE) e69de29bb2d1 ctime=0:0 mtime=0:0 size=0 flags=20004000 file2.txt
");
// If we remove the added file, it's removed from the index
work_dir.remove_file("file2.txt");
work_dir.run_jj(["status"]).success();
insta::assert_snapshot!(get_index_state(work_dir.root()), @"Unconflicted Mode(FILE) 0839b2e9412b ctime=0:0 mtime=0:0 size=0 flags=0 file1.txt");
// If we untrack the file, it's removed from the index
work_dir
.run_jj(["op", "restore", op_id_new_file.as_str()])
.success();
work_dir.write_file(".gitignore", "file2.txt");
work_dir.run_jj(["file", "untrack", "file2.txt"]).success();
insta::assert_snapshot!(get_index_state(work_dir.root()), @r"
Unconflicted Mode(FILE) e69de29bb2d1 ctime=0:0 mtime=0:0 size=0 flags=20004000 .gitignore
Unconflicted Mode(FILE) 0839b2e9412b ctime=0:0 mtime=0:0 size=0 flags=0 file1.txt
");
}
#[test]
fn test_git_colocated_unborn_bookmark() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let git_repo = git::init(work_dir.root());
// add a file to an (in memory) index
let add_file_to_index = |name: &str, data: &str| {
let mut index_manager = git::IndexManager::new(&git_repo);
index_manager.add_file(name, data.as_bytes());
index_manager.sync_index();
};
// checkout index (i.e., drop the in-memory changes)
let checkout_index = || {
let mut index = git_repo.open_index().unwrap();
let objects = git_repo.objects.clone();
gix::worktree::state::checkout(
&mut index,
git_repo.workdir().unwrap(),
objects,
&gix::progress::Discard,
&gix::progress::Discard,
&gix::interrupt::IS_INTERRUPTED,
gix::worktree::state::checkout::Options::default(),
)
.unwrap();
};
// Initially, HEAD isn't set.
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
assert!(git_repo.head().unwrap().is_unborn());
assert_eq!(
git_repo.head_name().unwrap().unwrap().as_bstr(),
b"refs/heads/master"
);
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: (none)
[EOF]
");
// Stage some change, and check out root. This shouldn't clobber the HEAD.
add_file_to_index("file0", "");
let output = work_dir.run_jj(["new", "root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: zsuskuln c2934cfb (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
assert!(git_repo.head().unwrap().is_unborn());
assert_eq!(
git_repo.head_name().unwrap().unwrap().as_bstr(),
b"refs/heads/master"
);
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c2934cfbfb196d2c473959667beffcc19e71e5e8
│ ○ e6669bb3438ef218fa618e1047a1911d2b3410dd
├─╯
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: (none)
[EOF]
");
// Staged change shouldn't persist.
checkout_index();
insta::assert_snapshot!(work_dir.run_jj(["status"]), @r"
The working copy has no changes.
Working copy (@) : zsuskuln c2934cfb (empty) (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// Stage some change, and create new HEAD. This shouldn't move the default
// bookmark.
add_file_to_index("file1", "");
let output = work_dir.run_jj(["new"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 2d7a8abb (empty) (no description set)
Parent commit (@-) : zsuskuln ff536684 (no description set)
[EOF]
");
assert!(git_repo.head().unwrap().is_detached());
insta::assert_snapshot!(
git_repo.head_id().unwrap().to_string(),
@"ff5366846b039b25c6c4998fa74dca821c246243"
);
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 2d7a8abb601ebf559df4037279e9f2e851a75e63
○ ff5366846b039b25c6c4998fa74dca821c246243
│ ○ e6669bb3438ef218fa618e1047a1911d2b3410dd
├─╯
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: ff5366846b039b25c6c4998fa74dca821c246243
[EOF]
");
// Staged change shouldn't persist.
checkout_index();
insta::assert_snapshot!(work_dir.run_jj(["status"]), @r"
The working copy has no changes.
Working copy (@) : vruxwmqv 2d7a8abb (empty) (no description set)
Parent commit (@-): zsuskuln ff536684 (no description set)
[EOF]
");
// Assign the default bookmark. The bookmark is no longer "unborn".
work_dir
.run_jj(["bookmark", "create", "-r@-", "master"])
.success();
// Stage some change, and check out root again. This should unset the HEAD.
// https://github.com/jj-vcs/jj/issues/1495
add_file_to_index("file2", "");
let output = work_dir.run_jj(["new", "root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: wqnwkozp 88e8407a (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
assert!(git_repo.head().unwrap().is_unborn());
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 88e8407a4f0a5e6f40a7c6c494106764adc00fed
│ ○ 2dd7385602e703388fd266b939bba6f57a1439d3
│ ○ ff5366846b039b25c6c4998fa74dca821c246243 master
├─╯
│ ○ e6669bb3438ef218fa618e1047a1911d2b3410dd
├─╯
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: (none)
[EOF]
");
// Staged change shouldn't persist.
checkout_index();
insta::assert_snapshot!(work_dir.run_jj(["status"]), @r"
The working copy has no changes.
Working copy (@) : wqnwkozp 88e8407a (empty) (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// New snapshot and commit can be created after the HEAD got unset.
work_dir.write_file("file3", "");
let output = work_dir.run_jj(["new"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: uyznsvlq 2fb16499 (empty) (no description set)
Parent commit (@-) : wqnwkozp bb21bc2d (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 2fb16499a987e632407402e38976ed250c939c42
○ bb21bc2dce2af92973fdd6d42686d77bd16bc466
│ ○ 2dd7385602e703388fd266b939bba6f57a1439d3
│ ○ ff5366846b039b25c6c4998fa74dca821c246243 master
├─╯
│ ○ e6669bb3438ef218fa618e1047a1911d2b3410dd
├─╯
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: bb21bc2dce2af92973fdd6d42686d77bd16bc466
[EOF]
");
}
#[test]
fn test_git_colocated_export_bookmarks_on_snapshot() {
// Checks that we export bookmarks that were changed only because the working
// copy was snapshotted
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let git_repo = git::init(work_dir.root());
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
// Create bookmark pointing to the initial commit
work_dir.write_file("file", "initial");
work_dir
.run_jj(["bookmark", "create", "-r@", "foo"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 82a10a4d9ef783fd68b661f40ce10dd80d599d9e foo
◆ 0000000000000000000000000000000000000000
[EOF]
");
// The bookmark gets updated when we modify the working copy, and it should get
// exported to Git without requiring any other changes
work_dir.write_file("file", "modified");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 00fc09f48ccf5c8b025a0f93b0ec3b0e4294a598 foo
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(git_repo
.find_reference("refs/heads/foo")
.unwrap()
.id()
.to_string(), @"00fc09f48ccf5c8b025a0f93b0ec3b0e4294a598");
}
#[test]
fn test_git_colocated_rebase_on_import() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let git_repo = git::init(work_dir.root());
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
// Make some changes in jj and check that they're reflected in git
work_dir.write_file("file", "contents");
work_dir.run_jj(["commit", "-m", "add a file"]).success();
work_dir.write_file("file", "modified");
work_dir
.run_jj(["bookmark", "create", "-r@", "master"])
.success();
work_dir.run_jj(["commit", "-m", "modify a file"]).success();
// TODO: We shouldn't need this command here to trigger an import of the
// refs/heads/master we just exported
work_dir.run_jj(["st"]).success();
// Move `master` backwards, which should result in commit2 getting hidden,
// and the working-copy commit rebased.
let parent_commit = git_repo
.find_reference("refs/heads/master")
.unwrap()
.peel_to_commit()
.unwrap()
.parent_ids()
.next()
.unwrap()
.detach();
git_repo
.reference(
"refs/heads/master",
parent_commit,
gix::refs::transaction::PreviousValue::Any,
"update ref",
)
.unwrap();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d46583362b91d0e172aec469ea1689995540de81
○ cbd6c887108743a4abb0919305646a6a914a665e master add a file
◆ 0000000000000000000000000000000000000000
[EOF]
------- stderr -------
Abandoned 1 commits that are no longer reachable.
Rebased 1 descendant commits off of commits rewritten from git
Working copy (@) now at: zsuskuln d4658336 (empty) (no description set)
Parent commit (@-) : qpvuntsm cbd6c887 master | add a file
Added 0 files, modified 1 files, removed 0 files
Done importing changes from the underlying Git repo.
[EOF]
");
}
#[test]
fn test_git_colocated_bookmarks() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let git_repo = git::init(work_dir.root());
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
work_dir.run_jj(["new", "-m", "foo"]).success();
work_dir.run_jj(["new", "@-", "-m", "bar"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 95e79774f8e7c785fc36da2b798ecfe0dc864e02 bar
│ ○ b51ab2e2c88fe2d38bd7ca6946c4d87f281ce7e2 foo
├─╯
○ e8849ae12c709f2321908879bc724fdb2ab8a781
◆ 0000000000000000000000000000000000000000
[EOF]
");
// Create a bookmark in jj. It should be exported to Git even though it points
// to the working-copy commit.
work_dir
.run_jj(["bookmark", "create", "-r@", "master"])
.success();
insta::assert_snapshot!(
git_repo.find_reference("refs/heads/master").unwrap().target().id().to_string(),
@"95e79774f8e7c785fc36da2b798ecfe0dc864e02"
);
assert!(git_repo.head().unwrap().is_detached());
insta::assert_snapshot!(
git_repo.head_id().unwrap().to_string(),
@"e8849ae12c709f2321908879bc724fdb2ab8a781"
);
// Update the bookmark in Git
let target_id = work_dir
.run_jj(["log", "--no-graph", "-T=commit_id", "-r=subject(foo)"])
.success()
.stdout
.into_raw();
git_repo
.reference(
"refs/heads/master",
gix::ObjectId::from_hex(target_id.as_bytes()).unwrap(),
gix::refs::transaction::PreviousValue::Any,
"test",
)
.unwrap();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 507c0edcfc028f714f3c7a3027cb141f6610e867
│ ○ b51ab2e2c88fe2d38bd7ca6946c4d87f281ce7e2 master foo
├─╯
○ e8849ae12c709f2321908879bc724fdb2ab8a781
◆ 0000000000000000000000000000000000000000
[EOF]
------- stderr -------
Abandoned 1 commits that are no longer reachable.
Working copy (@) now at: yqosqzyt 507c0edc (empty) (no description set)
Parent commit (@-) : qpvuntsm e8849ae1 (empty) (no description set)
Done importing changes from the underlying Git repo.
[EOF]
");
}
#[test]
fn test_git_colocated_bookmark_forget() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
git::init(work_dir.root());
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "foo"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 43444d88b0096888ebfd664c0cf792c9d15e3f14 foo
○ e8849ae12c709f2321908879bc724fdb2ab8a781
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
foo: rlvkpnrz 43444d88 (empty) (no description set)
@git: rlvkpnrz 43444d88 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["bookmark", "forget", "--include-remotes", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Forgot 1 local bookmarks.
Forgot 1 remote bookmarks.
[EOF]
");
// A forgotten bookmark is deleted in the git repo. For a detailed demo
// explaining this, see `test_bookmark_forget_export` in
// `test_bookmark_command.rs`.
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
}
#[test]
fn test_git_colocated_bookmark_at_root() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["bookmark", "create", "foo", "-r=root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Created 1 bookmarks pointing to zzzzzzzz 00000000 foo | (empty) (no description set)
Warning: Failed to export some bookmarks:
foo@git: Ref cannot point to the root commit in Git
[EOF]
");
let output = work_dir.run_jj(["bookmark", "move", "foo", "--to=@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Moved 1 bookmarks to qpvuntsm e8849ae1 foo | (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj([
"bookmark",
"move",
"foo",
"--allow-backwards",
"--to=root()",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Moved 1 bookmarks to zzzzzzzz 00000000 foo* | (empty) (no description set)
Warning: Failed to export some bookmarks:
foo@git: Ref cannot point to the root commit in Git
[EOF]
");
}
#[test]
fn test_git_colocated_conflicting_git_refs() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
git::init(work_dir.root());
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
let output = work_dir.run_jj(["bookmark", "create", "-r@", "main/sub"]);
insta::with_settings!({filters => vec![("Failed to set: .*", "Failed to set: ...")]}, {
insta::assert_snapshot!(output, @r#"
------- stderr -------
Warning: Target revision is empty.
Created 1 bookmarks pointing to qpvuntsm e8849ae1 main main/sub | (empty) (no description set)
Warning: Failed to export some bookmarks:
main/sub@git: Failed to set: ...
Hint: Git doesn't allow a branch/tag name that looks like a parent directory of
another (e.g. `foo` and `foo/bar`). Try to rename the bookmarks/tags that failed
to export or their "parent" bookmarks/tags.
[EOF]
"#);
});
}
#[test]
fn test_git_colocated_checkout_non_empty_working_copy() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let git_repo = git::init(work_dir.root());
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
// Create an initial commit in Git
// We use this to set HEAD to master
let tree_id = git::add_commit(
&git_repo,
"refs/heads/master",
"file",
b"contents",
"initial",
&[],
)
.tree_id;
git::checkout_tree_index(&git_repo, tree_id);
assert_eq!(work_dir.read_file("file"), b"contents");
insta::assert_snapshot!(
git_repo.head_id().unwrap().to_string(),
@"97358f54806c7cd005ed5ade68a779595efbae7e"
);
work_dir.write_file("two", "y");
work_dir.run_jj(["describe", "-m", "two"]).success();
work_dir.run_jj(["new", "@-"]).success();
let output = work_dir.run_jj(["describe", "-m", "new"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 986aa548 (empty) new
Parent commit (@-) : slsumksp 97358f54 master | initial
[EOF]
");
assert_eq!(
git_repo.head_name().unwrap().unwrap().as_bstr(),
b"refs/heads/master"
);
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 986aa548466ed43b48c059854720e70d8ec2bf71 new
│ ○ 6b0f7d59e0749d3a6ff2ecf686d5fa48023b7b93 two
├─╯
○ 97358f54806c7cd005ed5ade68a779595efbae7e master initial
◆ 0000000000000000000000000000000000000000
[EOF]
");
insta::assert_snapshot!(get_colocation_status(&work_dir), @r"
Workspace is currently colocated with Git.
Last imported/exported Git HEAD: 97358f54806c7cd005ed5ade68a779595efbae7e
[EOF]
");
}
#[test]
fn test_git_colocated_fetch_deleted_or_moved_bookmark() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
let origin_dir = test_env.work_dir("origin");
git::init(origin_dir.root());
origin_dir.run_jj(["git", "init", "--git-repo=."]).success();
origin_dir.run_jj(["describe", "-m=A"]).success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "A"])
.success();
origin_dir.run_jj(["new", "-m=B_to_delete"]).success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "B_to_delete"])
.success();
origin_dir.run_jj(["new", "-m=original C", "@-"]).success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "C_to_move"])
.success();
let clone_dir = test_env.work_dir("clone");
git::clone(clone_dir.root(), origin_dir.root().to_str().unwrap(), None);
clone_dir.run_jj(["git", "init", "--git-repo=."]).success();
clone_dir.run_jj(["new", "A"]).success();
insta::assert_snapshot!(get_log_output(&clone_dir), @r"
@ 0060713e4c7c46c4ce0d69a43ac16451582eda79
│ ○ dd905babf5b4ad4689f2da1350fd4f0ac5568209 C_to_move original C
├─╯
│ ○ b2ea51c027e11c0f2871cce2a52e648e194df771 B_to_delete B_to_delete
├─╯
◆ 8777db25171cace71ad014598663d5ffc4fae6b1 A A
◆ 0000000000000000000000000000000000000000
[EOF]
");
origin_dir
.run_jj(["bookmark", "delete", "B_to_delete"])
.success();
// Move bookmark C sideways
origin_dir
.run_jj(["describe", "C_to_move", "-m", "moved C"])
.success();
let output = clone_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: B_to_delete@origin [deleted] untracked
bookmark: C_to_move@origin [updated] tracked
Abandoned 2 commits that are no longer reachable.
[EOF]
");
// "original C" and "B_to_delete" are abandoned, as the corresponding bookmarks
// were deleted or moved on the remote (#864)
insta::assert_snapshot!(get_log_output(&clone_dir), @r"
@ 0060713e4c7c46c4ce0d69a43ac16451582eda79
│ ○ fb297975e4ef98dc057f65b761aed2cdb0386598 C_to_move moved C
├─╯
◆ 8777db25171cace71ad014598663d5ffc4fae6b1 A A
◆ 0000000000000000000000000000000000000000
[EOF]
");
}
#[test]
fn test_git_colocated_rebase_dirty_working_copy() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let git_repo = git::init(work_dir.root());
work_dir.run_jj(["git", "init", "--git-repo=."]).success();
work_dir.write_file("file", "base");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "old");
work_dir
.run_jj(["bookmark", "create", "-r@", "feature"])
.success();
// Make the working-copy dirty, delete the checked out bookmark.
work_dir.write_file("file", "new");
git_repo
.find_reference("refs/heads/feature")
.unwrap()
.delete()
.unwrap();
// Because the working copy is dirty, the new working-copy commit will be
// diverged. Therefore, the feature bookmark has change-delete conflict.
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
M file
Working copy (@) : rlvkpnrz e23559e3 feature?? | (no description set)
Parent commit (@-): qpvuntsm f99015d7 (no description set)
Warning: These bookmarks have conflicts:
feature
Hint: Use `jj bookmark list` to see details. Use `jj bookmark set <name> -r <rev>` to resolve.
[EOF]
------- stderr -------
Warning: Failed to export some bookmarks:
feature@git: Modified ref had been deleted in Git
Done importing changes from the underlying Git repo.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e23559e3bc6f22a5562297696fc357e2c581df77 feature??
○ f99015d7d9b82a5912ec4d96a18d2a4afbd8dd49
◆ 0000000000000000000000000000000000000000
[EOF]
");
// The working-copy content shouldn't be lost.
insta::assert_snapshot!(work_dir.read_file("file"), @"new");
}
#[test]
fn test_git_colocated_external_checkout() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
let git_repo = git::init(work_dir.root());
let git_check_out_ref = |name| {
let target = git_repo
.find_reference(name)
.unwrap()
.into_fully_peeled_id()
.unwrap()
.detach();
git::set_head_to_id(&git_repo, target);
};
work_dir.run_jj(["git", "init", "--git-repo=."]).success();
work_dir.run_jj(["ci", "-m=A"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@-", "master"])
.success();
work_dir.run_jj(["new", "-m=B", "root()"]).success();
work_dir.run_jj(["new"]).success();
// Checked out anonymous bookmark
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 6f8612f0e7f6d52efd8a72615796df06f8d64cdc
○ 319eaafc8fd04c763a0683a000bba5452082feb3 B
│ ○ 8777db25171cace71ad014598663d5ffc4fae6b1 master A
├─╯
◆ 0000000000000000000000000000000000000000
[EOF]
");
// Check out another bookmark by external command
git_check_out_ref("refs/heads/master");
// The old working-copy commit gets abandoned, but the whole bookmark should not
// be abandoned. (#1042)
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 7ceeaaae54c8ac99ad34eeed7fe1e896f535be99
○ 8777db25171cace71ad014598663d5ffc4fae6b1 master A
│ ○ 319eaafc8fd04c763a0683a000bba5452082feb3 B
├─╯
◆ 0000000000000000000000000000000000000000
[EOF]
------- stderr -------
Reset the working copy parent to the new Git HEAD.
[EOF]
");
// Edit non-head commit
work_dir.run_jj(["new", "subject(B)"]).success();
work_dir.run_jj(["new", "-m=C", "--no-edit"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ 823204bc895aad19d46b895bc510fb3e9d0c97c7 C
@ c6abf242550b7c4116d3821b69c79326889aeba0
○ 319eaafc8fd04c763a0683a000bba5452082feb3 B
│ ○ 8777db25171cace71ad014598663d5ffc4fae6b1 master A
├─╯
◆ 0000000000000000000000000000000000000000
[EOF]
");
// Check out another bookmark by external command
git_check_out_ref("refs/heads/master");
// The old working-copy commit shouldn't be abandoned. (#3747)
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 277b693c61dcdea59ac26d6982370f78751f6ef5
○ 8777db25171cace71ad014598663d5ffc4fae6b1 master A
│ ○ 823204bc895aad19d46b895bc510fb3e9d0c97c7 C
│ ○ c6abf242550b7c4116d3821b69c79326889aeba0
│ ○ 319eaafc8fd04c763a0683a000bba5452082feb3 B
├─╯
◆ 0000000000000000000000000000000000000000
[EOF]
------- stderr -------
Reset the working copy parent to the new Git HEAD.
[EOF]
");
}
#[test]
#[cfg_attr(windows, ignore = "uses POSIX sh")]
fn test_git_colocated_concurrent_checkout() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["new", "-mcommit1"]).success();
work_dir.write_file("file1", "");
work_dir.run_jj(["new", "-mcommit2"]).success();
work_dir.write_file("file2", "");
work_dir.run_jj(["new", "-mcommit3"]).success();
// Run "jj commit" and "git checkout" concurrently
let output = work_dir.run_jj([
"commit",
"--config=ui.editor=['sh', '-c', 'git checkout -q HEAD^']",
]);
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/datatest_config_schema.rs | cli/tests/datatest_config_schema.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::path::Path;
use itertools::Itertools as _;
fn validate_config_toml(config_toml: String) -> Result<(), String> {
let config = toml_edit::de::from_str(&config_toml).unwrap();
// TODO: Fix unfortunate duplication with `test_config_schema.rs`.
const SCHEMA_SRC: &str = include_str!("../src/config-schema.json");
let schema = serde_json::from_str(SCHEMA_SRC).expect("`config-schema.json` to be valid JSON");
let validator =
jsonschema::validator_for(&schema).expect("`config-schema.json` to be a valid schema");
let evaluation = validator.evaluate(&config);
if evaluation.flag().valid {
Ok(())
} else {
Err(evaluation
.iter_errors()
.map(|err| format!("* {}: {}", err.instance_location, err.error))
.join("\n"))
}
}
pub(crate) fn check_config_file_valid(
path: &Path,
config_toml: String,
) -> datatest_stable::Result<()> {
if let Err(err) = validate_config_toml(config_toml) {
panic!("Failed to validate `{}`:\n{err}", path.display());
}
Ok(())
}
pub(crate) fn check_config_file_invalid(
path: &Path,
config_toml: String,
) -> datatest_stable::Result<()> {
if let Ok(()) = validate_config_toml(config_toml) {
panic!("Validation for `{}` unexpectedly passed", 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/tests/test_gerrit_upload.rs | cli/tests/test_gerrit_upload.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;
use crate::common::create_commit;
use crate::common::create_commit_with_files;
#[test]
fn test_gerrit_upload_dryrun() {
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"]);
let output = work_dir.run_jj(["gerrit", "upload", "-r", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No remote specified, and no 'gerrit' remote was found
[EOF]
[exit status: 1]
");
// With remote specified but.
test_env.add_config(r#"gerrit.default-remote="origin""#);
let output = work_dir.run_jj(["gerrit", "upload", "-r", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The remote 'origin' (configured via `gerrit.default-remote`) does not exist
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["gerrit", "upload", "-r", "b", "--remote=origin"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The remote 'origin' (specified via `--remote`) does not exist
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj([
"git",
"remote",
"add",
"origin",
"http://example.com/repo/foo",
]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["gerrit", "upload", "-r", "b", "--remote=origin"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No target branch specified via --remote-branch, and no 'gerrit.default-remote-branch' was found
[EOF]
[exit status: 1]
");
test_env.add_config(r#"gerrit.default-remote-branch="main""#);
let output = work_dir.run_jj(["gerrit", "upload", "-r", "b", "--dry-run"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Found 1 heads to push to Gerrit (remote 'origin'), target branch 'main'
Dry-run: Would push zsuskuln 123b4d91 b | b
[EOF]
");
let output = work_dir.run_jj(["gerrit", "upload", "-r", "b", "--dry-run", "-b", "other"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Found 1 heads to push to Gerrit (remote 'origin'), target branch 'other'
Dry-run: Would push zsuskuln 123b4d91 b | b
[EOF]
");
}
#[test]
fn test_gerrit_upload_failure() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "remote"])
.success();
let remote_dir = test_env.work_dir("remote");
create_commit(&remote_dir, "a", &[]);
test_env
.run_jj_in(".", ["git", "clone", "remote", "local"])
.success();
let local_dir = test_env.work_dir("local");
// construct test revisions
create_commit_with_files(&local_dir, "b", &["a@origin"], &[]);
create_commit(&local_dir, "c", &["a@origin"]);
local_dir.run_jj(["describe", "-m="]).success();
create_commit(&local_dir, "d", &["a@origin"]);
let output = local_dir.run_jj(["gerrit", "upload", "-r", "none()", "--remote-branch=main"]);
insta::assert_snapshot!(output, @"
------- stderr -------
No revisions to upload.
[EOF]
");
// empty revisions are not allowed
let output = local_dir.run_jj(["gerrit", "upload", "-r", "b", "--remote-branch=main"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Error: Refusing to upload revision mzvwutvlkqwt because it is empty
Hint: Perhaps you squashed then ran upload? Maybe you meant to upload the parent commit instead (eg. @-)
[EOF]
[exit status: 1]
");
// empty descriptions are not allowed
let output = local_dir.run_jj(["gerrit", "upload", "-r", "c", "--remote-branch=main"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Error: Refusing to upload revision yqosqzytrlsw because it is has no description
Hint: Maybe you meant to upload the parent commit instead (eg. @-)
[EOF]
[exit status: 1]
");
// upload failure
local_dir
.run_jj(["git", "remote", "set-url", "origin", "nonexistent"])
.success();
let output = local_dir.run_jj(["gerrit", "upload", "-r", "d", "--remote-branch=main"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Found 1 heads to push to Gerrit (remote 'origin'), target branch 'main'
Pushing znkkpsqq 47f1f88c d | d
Error: Internal git error while pushing to gerrit
Caused by: Could not find repository at '$TEST_ENV/local/nonexistent'
[EOF]
[exit status: 1]
");
}
#[test]
fn test_gerrit_upload_local_implicit_change_ids() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "remote"])
.success();
let remote_dir = test_env.work_dir("remote");
create_commit(&remote_dir, "a", &[]);
test_env
.run_jj_in(".", ["git", "clone", "remote", "local"])
.success();
let local_dir = test_env.work_dir("local");
create_commit(&local_dir, "b", &["a@origin"]);
create_commit(&local_dir, "c", &["b"]);
// Ensure other trailers are preserved (no extra newlines)
local_dir
.run_jj([
"describe",
"c",
"-m",
"c\n\nSigned-off-by: Lucky K Maintainer <lucky@maintainer.example.org>\n",
])
.success();
// The output should only mention commit IDs from the log output above (no
// temporary commits)
let output = local_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @"
@ yqosqzyt test.user@example.com 2001-02-03 08:05:15 c f6e97ced
│ c
○ mzvwutvl test.user@example.com 2001-02-03 08:05:12 b 3bcb28c4
│ b
◆ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a@origin 7d980be7
│ a
◆ zzzzzzzz root() 00000000
[EOF]
");
let output = local_dir.run_jj(["gerrit", "upload", "-r", "c", "--remote-branch=main"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Found 1 heads to push to Gerrit (remote 'origin'), target branch 'main'
Pushing yqosqzyt f6e97ced c | c
[EOF]
");
// The output should be unchanged because we only add Change-Id trailers
// transiently
let output = local_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @"
@ yqosqzyt test.user@example.com 2001-02-03 08:05:15 c f6e97ced
│ c
○ mzvwutvl test.user@example.com 2001-02-03 08:05:12 b 3bcb28c4
│ b
◆ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a@origin 7d980be7
│ a
◆ zzzzzzzz root() 00000000
[EOF]
");
// There's no particular reason to run this with jj util exec, it's just that
// the infra makes it easier to run this way.
let output = remote_dir.run_jj(["util", "exec", "--", "git", "log", "refs/for/main"]);
insta::assert_snapshot!(output, @"
commit 68b986d2eb820643b767ae219fb48128dcc2fc03
Author: Test User <test.user@example.com>
Date: Sat Feb 3 04:05:13 2001 +0700
c
Signed-off-by: Lucky K Maintainer <lucky@maintainer.example.org>
Change-Id: I19b790168e73f7a73a98deae21e807c06a6a6964
commit 81b723522d1c1a583a045eab5bfb323e45e6198d
Author: Test User <test.user@example.com>
Date: Sat Feb 3 04:05:11 2001 +0700
b
Change-Id: Id043564ef93650b06a70f92f9d91912b6a6a6964
commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
Author: Test User <test.user@example.com>
Date: Sat Feb 3 04:05:08 2001 +0700
a
[EOF]
");
}
#[test]
fn test_gerrit_upload_local_explicit_change_ids() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "remote"])
.success();
let remote_dir = test_env.work_dir("remote");
create_commit(&remote_dir, "a", &[]);
test_env
.run_jj_in(".", ["git", "clone", "remote", "local"])
.success();
let local_dir = test_env.work_dir("local");
create_commit(&local_dir, "b", &["a@origin"]);
// Add an explicit Change-Id footer to b
let output = local_dir.run_jj([
"describe",
"b",
"-m",
"b\n\nChange-Id: Id39b308212fe7e0b746d16c13355f3a90712d7f9\n",
]);
insta::assert_snapshot!(output, @r###"
------- stderr -------
Working copy (@) now at: mzvwutvl 887a7016 b | b
Parent commit (@-) : rlvkpnrz 7d980be7 a@origin | a
[EOF]
"###);
create_commit(&local_dir, "c", &["b"]);
// Add an explicit Change-Id footer to c
let output = local_dir.run_jj([
"describe",
"c",
"-m",
"c\n\nChange-Id: Idfac1e8c149efddf5c7a286f787b43886a6a6964\n",
]);
insta::assert_snapshot!(output, @r###"
------- stderr -------
Working copy (@) now at: vruxwmqv 27c0bdd0 c | c
Parent commit (@-) : mzvwutvl 887a7016 b | b
[EOF]
"###);
// The output should only mention commit IDs from the log output above (no
// temporary commits)
let output = local_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r###"
@ vruxwmqv test.user@example.com 2001-02-03 08:05:16 c 27c0bdd0
│ c
○ mzvwutvl test.user@example.com 2001-02-03 08:05:13 b 887a7016
│ b
◆ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a@origin 7d980be7
│ a
◆ zzzzzzzz root() 00000000
[EOF]
"###);
let output = local_dir.run_jj(["gerrit", "upload", "-r", "c", "--remote-branch=main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Found 1 heads to push to Gerrit (remote 'origin'), target branch 'main'
Pushing vruxwmqv 27c0bdd0 c | c
[EOF]
");
// The output should be unchanged because no temporary commits should have
// been created
let output = local_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r###"
@ vruxwmqv test.user@example.com 2001-02-03 08:05:16 c 27c0bdd0
│ c
○ mzvwutvl test.user@example.com 2001-02-03 08:05:13 b 887a7016
│ b
◆ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a@origin 7d980be7
│ a
◆ zzzzzzzz root() 00000000
[EOF]
"###);
// There's no particular reason to run this with jj util exec, it's just that
// the infra makes it easier to run this way.
let output = remote_dir.run_jj(["util", "exec", "--", "git", "log", "refs/for/main"]);
insta::assert_snapshot!(output, @r###"
commit 27c0bdd070a0dd4aec5a22bd3ea454cd2502f430
Author: Test User <test.user@example.com>
Date: Sat Feb 3 04:05:14 2001 +0700
c
Change-Id: Idfac1e8c149efddf5c7a286f787b43886a6a6964
commit 887a7016ec03a904835da1059543d8cc34b6ba76
Author: Test User <test.user@example.com>
Date: Sat Feb 3 04:05:11 2001 +0700
b
Change-Id: Id39b308212fe7e0b746d16c13355f3a90712d7f9
commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
Author: Test User <test.user@example.com>
Date: Sat Feb 3 04:05:08 2001 +0700
a
[EOF]
"###);
}
#[test]
fn test_gerrit_upload_local_mixed_change_ids() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "remote"])
.success();
let remote_dir = test_env.work_dir("remote");
create_commit(&remote_dir, "a", &[]);
test_env
.run_jj_in(".", ["git", "clone", "remote", "local"])
.success();
let local_dir = test_env.work_dir("local");
create_commit(&local_dir, "b", &["a@origin"]);
create_commit(&local_dir, "c", &["b"]);
// Add an explicit Change-Id footer to c but not b
let output = local_dir.run_jj([
"describe",
"c",
"-m",
"c\n\nChange-Id: Id39b308212fe7e0b746d16c13355f3a90712d7f9\n",
]);
insta::assert_snapshot!(output, @r###"
------- stderr -------
Working copy (@) now at: yqosqzyt 8d46d915 c | c
Parent commit (@-) : mzvwutvl 3bcb28c4 b | b
[EOF]
"###);
// The output should only mention commit IDs from the log output above (no
// temporary commits)
let output = local_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r###"
@ yqosqzyt test.user@example.com 2001-02-03 08:05:15 c 8d46d915
│ c
○ mzvwutvl test.user@example.com 2001-02-03 08:05:12 b 3bcb28c4
│ b
◆ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a@origin 7d980be7
│ a
◆ zzzzzzzz root() 00000000
[EOF]
"###);
let output = local_dir.run_jj(["gerrit", "upload", "-r", "c", "--remote-branch=main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Found 1 heads to push to Gerrit (remote 'origin'), target branch 'main'
Pushing yqosqzyt 8d46d915 c | c
[EOF]
");
// The output should be unchanged because commits created within 'upload'
// should all be temporary
let output = local_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r###"
@ yqosqzyt test.user@example.com 2001-02-03 08:05:15 c 8d46d915
│ c
○ mzvwutvl test.user@example.com 2001-02-03 08:05:12 b 3bcb28c4
│ b
◆ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a@origin 7d980be7
│ a
◆ zzzzzzzz root() 00000000
[EOF]
"###);
// There's no particular reason to run this with jj util exec, it's just that
// the infra makes it easier to run this way.
let output = remote_dir.run_jj(["util", "exec", "--", "git", "log", "refs/for/main"]);
insta::assert_snapshot!(output, @r###"
commit 015df2b1d38bdc71ae7ef24c2889100e39d34ef8
Author: Test User <test.user@example.com>
Date: Sat Feb 3 04:05:13 2001 +0700
c
Change-Id: Id39b308212fe7e0b746d16c13355f3a90712d7f9
commit 81b723522d1c1a583a045eab5bfb323e45e6198d
Author: Test User <test.user@example.com>
Date: Sat Feb 3 04:05:11 2001 +0700
b
Change-Id: Id043564ef93650b06a70f92f9d91912b6a6a6964
commit 7d980be7a1d499e4d316ab4c01242885032f7eaf
Author: Test User <test.user@example.com>
Date: Sat Feb 3 04:05:08 2001 +0700
a
[EOF]
"###);
}
#[test]
fn test_gerrit_upload_bad_change_ids() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "remote"])
.success();
let remote_dir = test_env.work_dir("remote");
create_commit(&remote_dir, "a", &[]);
test_env
.run_jj_in(".", ["git", "clone", "remote", "local"])
.success();
let local_dir = test_env.work_dir("local");
create_commit(&local_dir, "b", &["a@origin"]);
create_commit(&local_dir, "c", &["a@origin"]);
create_commit(&local_dir, "bb", &["b"]);
local_dir
.run_jj(["describe", "-rb", "-m\n\nChange-Id: malformed\n"])
.success();
local_dir
.run_jj([
"describe",
"-rbb",
"-m\n\nChange-Id: i0000000000000000000000000000000000000000\n",
])
.success();
local_dir
.run_jj([
"describe",
"-rc",
"-m",
concat!(
"\n\n",
"Change-Id: I1111111111111111111111111111111111111111\n",
"Change-Id: I2222222222222222222222222222222222222222\n",
),
])
.success();
let output = local_dir.run_jj(["gerrit", "upload", "-rc", "--remote-branch=main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Multiple Change-Id footers in revision yqosqzytrlsw
[EOF]
[exit status: 1]
");
// check both badly and slightly malformed Change-Id trailers
let output = local_dir.run_jj(["gerrit", "upload", "-rbb", "--remote-branch=main"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Warning: Invalid Change-Id footer in revision mzvwutvlkqwt
Warning: Invalid Change-Id footer in revision yostqsxwqrlt
Found 1 heads to push to Gerrit (remote 'origin'), target branch 'main'
Pushing yostqsxw 7252a52a bb
[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_revset_output.rs | cli/tests/test_revset_output.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_syntax_error() {
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", ":x"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: `:` is not a prefix operator
Caused by: --> 1:1
|
1 | :x
| ^
|
= `:` is not a prefix operator
Hint: Did you mean `::` for ancestors?
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "x &"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Syntax error
Caused by: --> 1:4
|
1 | x &
| ^---
|
= expected `::`, `..`, `~`, or <primary>
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for revsets syntax and how to quote symbols.
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "x - y"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: `-` is not an infix operator
Caused by: --> 1:3
|
1 | x - y
| ^
|
= `-` is not an infix operator
Hint: Did you mean `~` for difference?
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "HEAD^"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: `^` is not a postfix operator
Caused by: --> 1:5
|
1 | HEAD^
| ^
|
= `^` is not a postfix operator
Hint: Did you mean `-` for parents?
[EOF]
[exit status: 1]
");
}
#[test]
fn test_bad_function_call() {
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", "all(or::nothing)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Function `all`: Expected 0 arguments
Caused by: --> 1:5
|
1 | all(or::nothing)
| ^---------^
|
= Function `all`: Expected 0 arguments
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "parents()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Function `parents`: Expected 1 to 2 arguments
Caused by: --> 1:9
|
1 | parents()
| ^
|
= Function `parents`: Expected 1 to 2 arguments
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "parents(foo, bar, baz)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Function `parents`: Expected 1 to 2 arguments
Caused by: --> 1:9
|
1 | parents(foo, bar, baz)
| ^-----------^
|
= Function `parents`: Expected 1 to 2 arguments
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "heads(foo, bar)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Function `heads`: Expected 1 arguments
Caused by: --> 1:7
|
1 | heads(foo, bar)
| ^------^
|
= Function `heads`: Expected 1 arguments
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "latest(a, not_an_integer)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Expected integer
Caused by: --> 1:11
|
1 | latest(a, not_an_integer)
| ^------------^
|
= Expected integer
[EOF]
[exit status: 1]
");
// "N to M arguments"
let output = work_dir.run_jj(["log", "-r", "ancestors()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Function `ancestors`: Expected 1 to 2 arguments
Caused by: --> 1:11
|
1 | ancestors()
| ^
|
= Function `ancestors`: Expected 1 to 2 arguments
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "change_id(glob:a)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Expected change ID prefix
Caused by: --> 1:11
|
1 | change_id(glob:a)
| ^----^
|
= Expected change ID prefix
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "commit_id(xyzzy)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Invalid commit ID prefix
Caused by: --> 1:11
|
1 | commit_id(xyzzy)
| ^---^
|
= Invalid commit ID prefix
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "files(not::a-fileset)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: In fileset expression
Caused by:
1: --> 1:7
|
1 | files(not::a-fileset)
| ^------------^
|
= In fileset expression
2: --> 1:5
|
1 | not::a-fileset
| ^---
|
= expected <identifier>, <string_literal>, or <raw_string_literal>
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]
");
let output = work_dir.run_jj(["log", "-r", r#"files(foo:"bar")"#]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Failed to parse revset: In fileset expression
Caused by:
1: --> 1:7
|
1 | files(foo:"bar")
| ^-------^
|
= In fileset expression
2: --> 1:1
|
1 | foo:"bar"
| ^-------^
|
= Invalid file pattern
3: Invalid file pattern kind `foo:`
Hint: See https://docs.jj-vcs.dev/latest/filesets/#file-patterns or `jj help -k filesets` for valid prefixes.
[EOF]
[exit status: 1]
"#);
let output = work_dir.run_jj(["log", "-r", r#"files("../out")"#]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Error: Failed to parse revset: In fileset expression
Caused by:
1: --> 1:7
|
1 | files("../out")
| ^------^
|
= In fileset expression
2: --> 1:1
|
1 | "../out"
| ^------^
|
= Invalid file pattern
3: Path "../out" is not in the repo "."
4: Invalid component ".." in repo-relative path "../out"
[EOF]
[exit status: 1]
"#);
let output = work_dir.run_jj(["log", "-r", "bookmarks(bad:pattern)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Invalid string pattern
Caused by:
1: --> 1:11
|
1 | bookmarks(bad:pattern)
| ^---------^
|
= Invalid string pattern
2: Invalid string pattern kind `bad:`
Hint: Try prefixing with one of `exact:`, `glob:`, `regex:`, `substring:`, or one of these with `-i` suffix added (e.g. `glob-i:`) for case-insensitive matching
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "bookmarks(regex:'(')"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Invalid string pattern
Caused by:
1: --> 1:11
|
1 | bookmarks(regex:'(')
| ^-------^
|
= Invalid string pattern
2: regex parse error:
(
^
error: unclosed group
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "root()::whatever()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Function `whatever` doesn't exist
Caused by: --> 1:9
|
1 | root()::whatever()
| ^------^
|
= Function `whatever` doesn't exist
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "remote_bookmarks(a, b, remote=c)"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Failed to parse revset: Function `remote_bookmarks`: Got multiple values for keyword "remote"
Caused by: --> 1:24
|
1 | remote_bookmarks(a, b, remote=c)
| ^------^
|
= Function `remote_bookmarks`: Got multiple values for keyword "remote"
[EOF]
[exit status: 1]
"#);
let output = work_dir.run_jj(["log", "-r", "remote_bookmarks(remote=a, b)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Function `remote_bookmarks`: Positional argument follows keyword argument
Caused by: --> 1:28
|
1 | remote_bookmarks(remote=a, b)
| ^
|
= Function `remote_bookmarks`: Positional argument follows keyword argument
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "remote_bookmarks(=foo)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Syntax error
Caused by: --> 1:18
|
1 | remote_bookmarks(=foo)
| ^---
|
= expected <strict_identifier> or <expression>
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for revsets syntax and how to quote symbols.
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "remote_bookmarks(remote=)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Syntax error
Caused by: --> 1:25
|
1 | remote_bookmarks(remote=)
| ^---
|
= expected <expression>
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for revsets syntax and how to quote symbols.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_function_name_hint() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let evaluate = |expr| work_dir.run_jj(["log", "-r", expr]);
test_env.add_config(
r###"
[revset-aliases]
'bookmarks(x)' = 'x' # override builtin function
'my_author(x)' = 'author(x)' # similar name to builtin function
'author_sym' = 'x' # not a function alias
'my_bookmarks' = 'bookmark()' # typo in alias
"###,
);
// The suggestion "bookmarks" shouldn't be duplicated
insta::assert_snapshot!(evaluate("bookmark()"), @r"
------- stderr -------
Error: Failed to parse revset: Function `bookmark` doesn't exist
Caused by: --> 1:1
|
1 | bookmark()
| ^------^
|
= Function `bookmark` doesn't exist
Hint: Did you mean `bookmarks`, `remote_bookmarks`?
[EOF]
[exit status: 1]
");
// Both builtin function and function alias should be suggested
insta::assert_snapshot!(evaluate("author_()"), @r"
------- stderr -------
Error: Failed to parse revset: Function `author_` doesn't exist
Caused by: --> 1:1
|
1 | author_()
| ^-----^
|
= Function `author_` doesn't exist
Hint: Did you mean `author`, `author_date`, `author_email`, `author_name`, `my_author`?
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(evaluate("my_bookmarks"), @r"
------- stderr -------
Error: Failed to parse revset: In alias `my_bookmarks`
Caused by:
1: --> 1:1
|
1 | my_bookmarks
| ^----------^
|
= In alias `my_bookmarks`
2: --> 1:1
|
1 | bookmark()
| ^------^
|
= Function `bookmark` doesn't exist
Hint: Did you mean `bookmarks`, `remote_bookmarks`?
[EOF]
[exit status: 1]
");
}
#[test]
fn test_bad_symbol_or_argument_should_not_be_optimized_out() {
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", "unknown & none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revision `unknown` doesn't exist
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "all() | unknown"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revision `unknown` doesn't exist
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "description(regex:'(') & none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Invalid string pattern
Caused by:
1: --> 1:13
|
1 | description(regex:'(') & none()
| ^-------^
|
= Invalid string pattern
2: regex parse error:
(
^
error: unclosed group
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "files('..') & none()"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Error: Failed to parse revset: In fileset expression
Caused by:
1: --> 1:7
|
1 | files('..') & none()
| ^--^
|
= In fileset expression
2: --> 1:1
|
1 | '..'
| ^--^
|
= Invalid file pattern
3: Path ".." is not in the repo "."
4: Invalid component ".." in repo-relative path "../"
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_default_string_pattern() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// glob match by default
let output = work_dir.run_jj(["log", "-rauthor('*test.user*')"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:07 e8849ae1
│ (empty) (no description set)
~
[EOF]
");
// with default flipped
let output = work_dir.run_jj([
"log",
"-rauthor('test.user')",
"--config=ui.revsets-use-glob-by-default=false",
]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:07 e8849ae1
│ (empty) (no description set)
~
[EOF]
------- stderr -------
Warning: In revset expression
--> 1:8
|
1 | author('test.user')
| ^---------^
|
= ui.revsets-use-glob-by-default=false will be removed in a future release
[EOF]
");
}
#[test]
fn test_alias() {
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###"
[revset-aliases]
'my-root' = 'root()'
'syntax-error' = 'whatever &'
'recurse' = 'recurse1'
'recurse1' = 'recurse2()'
'recurse2()' = 'recurse'
'identity(x)' = 'x'
'my_author(x)' = 'author(x)'
"###,
);
let output = work_dir.run_jj(["log", "-r", "my-root"]);
insta::assert_snapshot!(output, @r"
◆ zzzzzzzz root() 00000000
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "identity(my-root)"]);
insta::assert_snapshot!(output, @r"
◆ zzzzzzzz root() 00000000
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "root() & syntax-error"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: In alias `syntax-error`
Caused by:
1: --> 1:10
|
1 | root() & syntax-error
| ^----------^
|
= In alias `syntax-error`
2: --> 1:11
|
1 | whatever &
| ^---
|
= expected `::`, `..`, `~`, or <primary>
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for revsets syntax and how to quote symbols.
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "identity()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Function `identity`: Expected 1 arguments
Caused by: --> 1:10
|
1 | identity()
| ^
|
= Function `identity`: Expected 1 arguments
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "my_author(none())"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: In alias `my_author(x)`
Caused by:
1: --> 1:1
|
1 | my_author(none())
| ^---------------^
|
= In alias `my_author(x)`
2: --> 1:8
|
1 | author(x)
| ^
|
= In function parameter `x`
3: --> 1:11
|
1 | my_author(none())
| ^----^
|
= Invalid string expression
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "my_author(unknown:pat)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: In alias `my_author(x)`
Caused by:
1: --> 1:1
|
1 | my_author(unknown:pat)
| ^--------------------^
|
= In alias `my_author(x)`
2: --> 1:8
|
1 | author(x)
| ^
|
= In function parameter `x`
3: --> 1:11
|
1 | my_author(unknown:pat)
| ^---------^
|
= Invalid string pattern
4: Invalid string pattern kind `unknown:`
Hint: Try prefixing with one of `exact:`, `glob:`, `regex:`, `substring:`, or one of these with `-i` suffix added (e.g. `glob-i:`) for case-insensitive matching
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["log", "-r", "root() & recurse"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: In alias `recurse`
Caused by:
1: --> 1:10
|
1 | root() & 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]
");
}
#[test]
fn test_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###"
[revset-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", "-r", "f(_)", "--config=revset-aliases.'f(a)'=arg"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revision `arg` doesn't exist
[EOF]
[exit status: 1]
");
}
#[test]
fn test_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#"
[revset-aliases]
'my-root' = 'root()'
'"bad"' = 'root()'
'badfn(a, a)' = 'root()'
"#,
);
// Invalid declaration should be warned and ignored.
let output = work_dir.run_jj(["log", "-r", "my-root"]);
insta::assert_snapshot!(output, @r#"
◆ zzzzzzzz root() 00000000
[EOF]
------- stderr -------
Warning: Failed to load `revset-aliases."bad"`: --> 1:1
|
1 | "bad"
| ^---
|
= expected <strict_identifier> or <function_name>
Warning: Failed to load `revset-aliases.badfn(a, a)`: --> 1:7
|
1 | badfn(a, a)
| ^--^
|
= Redefinition of function parameter
[EOF]
"#);
}
#[test]
fn test_all_modifier() {
let test_env = TestEnvironment::default();
test_env.add_config("ui.always-allow-large-revsets=false");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Command that accepts single revision by default
let output = work_dir.run_jj(["new", "all()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revset `all()` resolved to more than one revision
Hint: The revset `all()` resolved to these revisions:
qpvuntsm e8849ae1 (empty) (no description set)
zzzzzzzz 00000000 (empty) (no description set)
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["new", "all:all()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: In revset expression
--> 1:1
|
1 | all:all()
| ^-^
|
= Multiple revisions are allowed by default; `all:` is planned for removal
Error: The Git backend does not support creating merge commits with the root commit as one of the parents.
[EOF]
[exit status: 1]
");
// Command that accepts multiple revisions by default
let output = work_dir.run_jj(["log", "-rall:all()"]);
insta::assert_snapshot!(output, @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:07 e8849ae1
│ (empty) (no description set)
◆ zzzzzzzz root() 00000000
[EOF]
------- stderr -------
Warning: In revset expression
--> 1:1
|
1 | all:all()
| ^-^
|
= Multiple revisions are allowed by default; `all:` is planned for removal
[EOF]
");
// Command that accepts only single revision
let output = work_dir.run_jj(["bookmark", "create", "-rall:@", "x"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: In revset expression
--> 1:1
|
1 | all:@
| ^-^
|
= Multiple revisions are allowed by default; `all:` is planned for removal
Warning: Target revision is empty.
Created 1 bookmarks pointing to qpvuntsm e8849ae1 x | (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["bookmark", "set", "-rall:all()", "x"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: In revset expression
--> 1:1
|
1 | all:all()
| ^-^
|
= Multiple revisions are allowed by default; `all:` is planned for removal
Error: Revset `all:all()` resolved to more than one revision
Hint: The revset `all:all()` resolved to these revisions:
qpvuntsm e8849ae1 x | (empty) (no description set)
zzzzzzzz 00000000 (empty) (no description set)
[EOF]
[exit status: 1]
");
// Template expression that accepts multiple revisions by default
let output = work_dir.run_jj(["log", "-Tself.contained_in('all:all()')"]);
insta::assert_snapshot!(output, @r"
@ true
◆ true
[EOF]
------- stderr -------
Warning: In template expression
--> 1:19
|
1 | self.contained_in('all:all()')
| ^---------^
|
= In revset expression
--> 1:1
|
1 | all:all()
| ^-^
|
= Multiple revisions are allowed by default; `all:` is planned for removal
[EOF]
");
// Typo
let output = work_dir.run_jj(["new", "ale:x"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: Modifier `ale` doesn't exist
Caused by: --> 1:1
|
1 | ale:x
| ^-^
|
= Modifier `ale` doesn't exist
[EOF]
[exit status: 1]
");
// Modifier shouldn't be allowed in sub expression
let output = work_dir.run_jj(["new", "x..", "--config=revset-aliases.x='all:@'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse revset: In alias `x`
Caused by:
1: --> 1:1
|
1 | x..
| ^
|
= In alias `x`
2: --> 1:1
|
1 | all:@
| ^-^
|
= Modifier `all:` is not allowed in sub expression
[EOF]
[exit status: 1]
");
// Modifier shouldn't be allowed in a top-level immutable_heads() expression
let output = work_dir.run_jj([
"new",
"--config=revset-aliases.'immutable_heads()'='all:@'",
"--config=revsets.short-prefixes='none()'",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Invalid `revset-aliases.immutable_heads()`
Caused by: --> 1:4
|
1 | all:@
| ^
|
= `:` is not an infix operator
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
}
/// Verifies that the committer_date revset honors the local time zone.
/// This test cannot run on Windows because The TZ env var does not control
/// chrono::Local on that platform.
#[test]
#[cfg(not(target_os = "windows"))]
fn test_revset_committer_date_with_time_zone() {
// Use these for the test instead of tzdb identifiers like America/New_York
// because the tz database may not be installed on some build servers
const NEW_YORK: &str = "EST+5EDT+4,M3.1.0,M11.1.0";
const CHICAGO: &str = "CST+6CDT+5,M3.1.0,M11.1.0";
const AUSTRALIA: &str = "AEST-10";
let mut test_env = TestEnvironment::default();
test_env.add_env_var("TZ", NEW_YORK);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir
.run_jj([
"--config=debug.commit-timestamp=2023-01-25T11:30:00-05:00",
"describe",
"-m",
"first",
])
.success();
work_dir
.run_jj([
"--config=debug.commit-timestamp=2023-01-25T12:30:00-05:00",
"new",
"-m",
"second",
])
.success();
work_dir
.run_jj([
"--config=debug.commit-timestamp=2023-01-25T13:30:00-05:00",
"new",
"-m",
"third",
])
.success();
let mut log_commits_before_and_after = |committer_date: &str, now: &str, tz: &str| {
test_env.add_env_var("TZ", tz);
let config = format!("debug.commit-timestamp={now}");
let work_dir = test_env.work_dir("repo");
let before_log = work_dir.run_jj([
"--config",
config.as_str(),
"log",
"--no-graph",
"-T",
"description.first_line() ++ ' ' ++ committer.timestamp() ++ '\n'",
"-r",
format!("committer_date(before:'{committer_date}') ~ root()").as_str(),
]);
let after_log = work_dir.run_jj([
"--config",
config.as_str(),
"log",
"--no-graph",
"-T",
"description.first_line() ++ ' ' ++ committer.timestamp() ++ '\n'",
"-r",
format!("committer_date(after:'{committer_date}')").as_str(),
]);
(before_log, after_log)
};
let (before_log, after_log) =
log_commits_before_and_after("2023-01-25 12:00", "2023-02-01T00:00:00-05:00", NEW_YORK);
insta::assert_snapshot!(before_log, @r"
first 2023-01-25 11:30:00.000 -05:00
[EOF]
");
insta::assert_snapshot!(after_log, @r"
third 2023-01-25 13:30:00.000 -05:00
second 2023-01-25 12:30:00.000 -05:00
[EOF]
");
// Switch to DST and ensure we get the same results, because it should
// evaluate 12:00 on commit date, not the current date
let (before_log, after_log) =
log_commits_before_and_after("2023-01-25 12:00", "2023-06-01T00:00:00-04:00", NEW_YORK);
insta::assert_snapshot!(before_log, @r"
first 2023-01-25 11:30:00.000 -05:00
[EOF]
");
insta::assert_snapshot!(after_log, @r"
third 2023-01-25 13:30:00.000 -05:00
second 2023-01-25 12:30:00.000 -05:00
[EOF]
");
// Change the local time zone and ensure the result changes
let (before_log, after_log) =
log_commits_before_and_after("2023-01-25 12:00", "2023-06-01T00:00:00-06:00", CHICAGO);
insta::assert_snapshot!(before_log, @r"
second 2023-01-25 12:30:00.000 -05:00
first 2023-01-25 11:30:00.000 -05:00
[EOF]
");
insta::assert_snapshot!(after_log, @r"
third 2023-01-25 13:30:00.000 -05:00
[EOF]
");
// Time zone far outside USA with no DST
let (before_log, after_log) =
log_commits_before_and_after("2023-01-26 03:00", "2023-06-01T00:00:00+10:00", AUSTRALIA);
insta::assert_snapshot!(before_log, @r"
first 2023-01-25 11:30:00.000 -05:00
[EOF]
");
insta::assert_snapshot!(after_log, @r"
third 2023-01-25 13:30:00.000 -05:00
second 2023-01-25 12:30:00.000 -05:00
[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_diff_command.rs | cli/tests/test_diff_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 indoc::indoc;
use itertools::Itertools as _;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit;
use crate::common::create_commit_with_files;
use crate::common::fake_diff_editor_path;
use crate::common::to_toml_value;
#[test]
fn test_diff_basic() {
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", "1\n2\n3\n4\n");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.write_file("file2", "1\n5\n3\n");
work_dir.write_file("file3", "foo\n");
work_dir.write_file("file4", "1\n2\n3\n4\n");
let output = work_dir.run_jj(["diff"]);
insta::assert_snapshot!(output, @r"
Modified regular file file2:
1 1: 1
2 2: 25
3 3: 3
4 : 4
Modified regular file file3 (file1 => file3):
Modified regular file file4 (file2 => file4):
[EOF]
");
let output = work_dir.run_jj(["diff", "--context=0"]);
insta::assert_snapshot!(output, @r"
Modified regular file file2:
1 1: 1
2 2: 25
3 3: 3
4 : 4
Modified regular file file3 (file1 => file3):
Modified regular file file4 (file2 => file4):
[EOF]
");
let output = work_dir.run_jj(["diff", "--color=debug"]);
insta::assert_snapshot!(output, @r"
[38;5;3m<<diff header::Modified regular file file2:>>[39m
[2m[38;5;1m<<diff context removed line_number:: 1>>[0m<<diff context:: >>[2m[38;5;2m<<diff context added line_number:: 1>>[0m<<diff context::: 1>>
[38;5;1m<<diff removed line_number:: 2>>[39m<<diff:: >>[38;5;2m<<diff added line_number:: 2>>[39m<<diff::: >>[4m[38;5;1m<<diff removed token::2>>[38;5;2m<<diff added token::5>>[24m[39m<<diff::>>
[2m[38;5;1m<<diff context removed line_number:: 3>>[0m<<diff context:: >>[2m[38;5;2m<<diff context added line_number:: 3>>[0m<<diff context::: 3>>
[38;5;1m<<diff removed line_number:: 4>>[39m<<diff:: : >>[4m[38;5;1m<<diff removed token::4>>[24m[39m
[38;5;3m<<diff header::Modified regular file file3 (file1 => file3):>>[39m
[38;5;3m<<diff header::Modified regular file file4 (file2 => file4):>>[39m
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
M file2
R {file1 => file3}
C {file2 => file4}
[EOF]
");
let output = work_dir.run_jj(["diff", "--types"]);
insta::assert_snapshot!(output, @r"
FF file2
FF {file1 => file3}
FF {file2 => file4}
[EOF]
");
let output = work_dir.run_jj(["diff", "--types", "glob:file[12]"]);
insta::assert_snapshot!(output, @r"
F- file1
FF file2
[EOF]
");
let template = r#"source.path() ++ ' => ' ++ target.path() ++ ' (' ++ status ++ ")\n""#;
let output = work_dir.run_jj(["diff", "-T", template]);
insta::assert_snapshot!(output, @r"
file2 => file2 (modified)
file1 => file3 (renamed)
file2 => file4 (copied)
[EOF]
");
let output = work_dir.run_jj(["diff", "--git", "file1"]);
insta::assert_snapshot!(output, @r"
diff --git a/file1 b/file1
deleted file mode 100644
index 257cc5642c..0000000000
--- a/file1
+++ /dev/null
@@ -1,1 +0,0 @@
-foo
[EOF]
");
let output = work_dir.run_jj(["diff", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file2 b/file2
index 94ebaf9001..1ffc51b472 100644
--- a/file2
+++ b/file2
@@ -1,4 +1,3 @@
1
-2
+5
3
-4
diff --git a/file1 b/file3
rename from file1
rename to file3
diff --git a/file2 b/file4
copy from file2
copy to file4
[EOF]
");
let output = work_dir.run_jj(["diff", "--git", "--context=0"]);
insta::assert_snapshot!(output, @r"
diff --git a/file2 b/file2
index 94ebaf9001..1ffc51b472 100644
--- a/file2
+++ b/file2
@@ -2,1 +2,1 @@
-2
+5
@@ -4,1 +3,0 @@
-4
diff --git a/file1 b/file3
rename from file1
rename to file3
diff --git a/file2 b/file4
copy from file2
copy to file4
[EOF]
");
let output = work_dir.run_jj(["diff", "--git", "--color=debug"]);
insta::assert_snapshot!(output, @r"
[1m<<diff file_header::diff --git a/file2 b/file2>>[0m
[1m<<diff file_header::index 94ebaf9001..1ffc51b472 100644>>[0m
[1m<<diff file_header::--- a/file2>>[0m
[1m<<diff file_header::+++ b/file2>>[0m
[38;5;6m<<diff hunk_header::@@ -1,4 +1,3 @@>>[39m
<<diff context:: 1>>
[38;5;1m<<diff removed::->>[4m<<diff removed token::2>>[24m<<diff removed::>>[39m
[38;5;2m<<diff added::+>>[4m<<diff added token::5>>[24m<<diff added::>>[39m
<<diff context:: 3>>
[38;5;1m<<diff removed::->>[4m<<diff removed token::4>>[24m[39m
[1m<<diff file_header::diff --git a/file1 b/file3>>[0m
[1m<<diff file_header::rename from file1>>[0m
[1m<<diff file_header::rename to file3>>[0m
[1m<<diff file_header::diff --git a/file2 b/file4>>[0m
[1m<<diff file_header::copy from file2>>[0m
[1m<<diff file_header::copy to file4>>[0m
[EOF]
");
let output = work_dir.run_jj(["diff", "-s", "--git"]);
insta::assert_snapshot!(output, @r"
M file2
R {file1 => file3}
C {file2 => file4}
diff --git a/file2 b/file2
index 94ebaf9001..1ffc51b472 100644
--- a/file2
+++ b/file2
@@ -1,4 +1,3 @@
1
-2
+5
3
-4
diff --git a/file1 b/file3
rename from file1
rename to file3
diff --git a/file2 b/file4
copy from file2
copy to file4
[EOF]
");
let output = work_dir.run_jj(["diff", "--stat"]);
insta::assert_snapshot!(output, @r"
file2 | 3 +--
{file1 => file3} | 0
{file2 => file4} | 0
3 files changed, 1 insertion(+), 2 deletions(-)
[EOF]
");
// Reverse-order diff
let output = work_dir.run_jj(["diff", "--to", "@-", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file3 b/file1
rename from file3
rename to file1
diff --git a/file2 b/file2
index 1ffc51b472..94ebaf9001 100644
--- a/file2
+++ b/file2
@@ -1,3 +1,4 @@
1
-5
+2
3
+4
diff --git a/file4 b/file4
deleted file mode 100644
index 94ebaf9001..0000000000
--- a/file4
+++ /dev/null
@@ -1,4 +0,0 @@
-1
-2
-3
-4
[EOF]
");
// Filter by glob pattern
let output = work_dir.run_jj(["diff", "-s", "glob:file[12]"]);
insta::assert_snapshot!(output, @r"
D file1
M file2
[EOF]
");
// Unmatched paths should generate warnings
let output = test_env.run_jj_in(
".",
[
"diff",
"-Rrepo",
"-s",
"repo", // matches directory
"repo/file1", // deleted in to_tree, but exists in from_tree
"repo/x",
"repo/y/z",
],
);
insta::assert_snapshot!(output.normalize_backslash(), @r"
M repo/file2
R repo/{file1 => file3}
C repo/{file2 => file4}
[EOF]
------- stderr -------
Warning: No matching entries for paths: repo/x, repo/y/z
[EOF]
");
// Unmodified paths shouldn't generate warnings
let output = work_dir.run_jj(["diff", "-s", "--from=@", "file2"]);
insta::assert_snapshot!(output, @"");
// --tool=:<builtin>
let output = work_dir.run_jj(["diff", "--tool=:summary", "--color-words", "file2"]);
insta::assert_snapshot!(output, @r"
M file2
Modified regular file file2:
1 1: 1
2 2: 25
3 3: 3
4 : 4
[EOF]
");
let output = work_dir.run_jj(["diff", "--tool=:git", "--stat", "file2"]);
insta::assert_snapshot!(output, @r"
file2 | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/file2 b/file2
index 94ebaf9001..1ffc51b472 100644
--- a/file2
+++ b/file2
@@ -1,4 +1,3 @@
1
-2
+5
3
-4
[EOF]
");
// Bad combination
let output = work_dir.run_jj(["diff", "--summary", "--tool=:stat"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --tool=:stat cannot be used with --summary
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["diff", "--git", "--tool=:git"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --tool=:git cannot be used with --git
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["diff", "--git", "--tool=external"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --tool=external cannot be used with --git
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["diff", "-T''", "--summary"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--template <TEMPLATE>' cannot be used with:
--summary
--stat
--types
--name-only
Usage: jj diff --template <TEMPLATE> --summary [FILESETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["diff", "-T''", "--git"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--template <TEMPLATE>' cannot be used with:
--git
--color-words
Usage: jj diff --template <TEMPLATE> --git [FILESETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["diff", "-T''", "--tool=:git"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--template <TEMPLATE>' cannot be used with '--tool <TOOL>'
Usage: jj diff --template <TEMPLATE> [FILESETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Bad builtin format
let output = work_dir.run_jj(["diff", "--config=ui.diff-formatter=:unknown"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Invalid type or value for ui.diff-formatter
Caused by: Invalid builtin diff format: unknown
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_diff_empty() {
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", "");
let output = work_dir.run_jj(["diff"]);
insta::assert_snapshot!(output, @r"
Added regular file file1:
(empty)
[EOF]
");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
let output = work_dir.run_jj(["diff"]);
insta::assert_snapshot!(output, @r"
Removed regular file file1:
(empty)
[EOF]
");
let output = work_dir.run_jj(["diff", "--stat"]);
insta::assert_snapshot!(output, @r"
file1 | 0
1 file changed, 0 insertions(+), 0 deletions(-)
[EOF]
");
}
#[test]
fn test_diff_file_mode() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Test content+mode/mode-only changes of empty/non-empty files:
// - file1: ("", x) -> ("2", n) empty, content+mode
// - file2: ("1", x) -> ("1", n) non-empty, mode-only
// - file3: ("1", n) -> ("2", x) non-empty, content+mode
// - file4: ("", n) -> ("", x) empty, mode-only
work_dir.write_file("file1", "");
work_dir.write_file("file2", "1\n");
work_dir.write_file("file3", "1\n");
work_dir.write_file("file4", "");
work_dir
.run_jj(["file", "chmod", "x", "file1", "file2"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "2\n");
work_dir.write_file("file3", "2\n");
work_dir
.run_jj(["file", "chmod", "n", "file1", "file2"])
.success();
work_dir
.run_jj(["file", "chmod", "x", "file3", "file4"])
.success();
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.remove_file("file2");
work_dir.remove_file("file3");
work_dir.remove_file("file4");
let output = work_dir.run_jj(["diff", "-r@--"]);
insta::assert_snapshot!(output, @r"
Added executable file file1:
(empty)
Added executable file file2:
1: 1
Added regular file file3:
1: 1
Added regular file file4:
(empty)
[EOF]
");
let output = work_dir.run_jj(["diff", "-r@-"]);
insta::assert_snapshot!(output, @r"
Executable file became non-executable at file1:
1: 2
Executable file became non-executable at file2:
Non-executable file became executable at file3:
1 1: 12
Non-executable file became executable at file4:
[EOF]
");
let output = work_dir.run_jj(["diff", "-r@"]);
insta::assert_snapshot!(output, @r"
Removed regular file file1:
1 : 2
Removed regular file file2:
1 : 1
Removed executable file file3:
1 : 2
Removed executable file file4:
(empty)
[EOF]
");
let output = work_dir.run_jj(["diff", "-r@--", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file1 b/file1
new file mode 100755
index 0000000000..e69de29bb2
diff --git a/file2 b/file2
new file mode 100755
index 0000000000..d00491fd7e
--- /dev/null
+++ b/file2
@@ -0,0 +1,1 @@
+1
diff --git a/file3 b/file3
new file mode 100644
index 0000000000..d00491fd7e
--- /dev/null
+++ b/file3
@@ -0,0 +1,1 @@
+1
diff --git a/file4 b/file4
new file mode 100644
index 0000000000..e69de29bb2
[EOF]
");
let output = work_dir.run_jj(["diff", "-r@-", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file1 b/file1
old mode 100755
new mode 100644
index e69de29bb2..0cfbf08886
--- a/file1
+++ b/file1
@@ -0,0 +1,1 @@
+2
diff --git a/file2 b/file2
old mode 100755
new mode 100644
diff --git a/file3 b/file3
old mode 100644
new mode 100755
index d00491fd7e..0cfbf08886
--- a/file3
+++ b/file3
@@ -1,1 +1,1 @@
-1
+2
diff --git a/file4 b/file4
old mode 100644
new mode 100755
[EOF]
");
let output = work_dir.run_jj(["diff", "-r@", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file1 b/file1
deleted file mode 100644
index 0cfbf08886..0000000000
--- a/file1
+++ /dev/null
@@ -1,1 +0,0 @@
-2
diff --git a/file2 b/file2
deleted file mode 100644
index d00491fd7e..0000000000
--- a/file2
+++ /dev/null
@@ -1,1 +0,0 @@
-1
diff --git a/file3 b/file3
deleted file mode 100755
index 0cfbf08886..0000000000
--- a/file3
+++ /dev/null
@@ -1,1 +0,0 @@
-2
diff --git a/file4 b/file4
deleted file mode 100755
index e69de29bb2..0000000000
[EOF]
");
}
#[test]
fn test_diff_types() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let file_path = "foo";
// Missing
work_dir.run_jj(["new", "root()", "-m=missing"]).success();
// Normal file
work_dir.run_jj(["new", "root()", "-m=file"]).success();
work_dir.write_file(file_path, "foo");
// Conflict (add/add)
work_dir.run_jj(["new", "root()", "-m=conflict"]).success();
work_dir.write_file(file_path, "foo");
work_dir.run_jj(["new", "root()"]).success();
work_dir.write_file(file_path, "bar");
work_dir
.run_jj(["squash", "--into=subject(conflict)"])
.success();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
use std::path::PathBuf;
// Executable
work_dir
.run_jj(["new", "root()", "-m=executable"])
.success();
work_dir.write_file(file_path, "foo");
std::fs::set_permissions(
work_dir.root().join(file_path),
std::fs::Permissions::from_mode(0o755),
)
.unwrap();
// Symlink
work_dir.run_jj(["new", "root()", "-m=symlink"]).success();
std::os::unix::fs::symlink(PathBuf::from("."), work_dir.root().join(file_path)).unwrap();
}
let diff = |from: &str, to: &str| {
work_dir.run_jj([
"diff",
"--types",
&format!(r#"--from=subject("{from}")"#),
&format!(r#"--to=subject("{to}")"#),
])
};
insta::assert_snapshot!(diff("missing", "file"), @r"
-F foo
[EOF]
");
insta::assert_snapshot!(diff("file", "conflict"), @r"
FC foo
[EOF]
");
insta::assert_snapshot!(diff("conflict", "missing"), @r"
C- foo
[EOF]
");
#[cfg(unix)]
{
insta::assert_snapshot!(diff("symlink", "file"), @r"
LF foo
[EOF]
");
insta::assert_snapshot!(diff("missing", "executable"), @r"
-F foo
[EOF]
");
}
}
#[test]
fn test_diff_name_only() {
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.write_file("deleted", "d");
work_dir.write_file("modified", "m");
insta::assert_snapshot!(work_dir.run_jj(["diff", "--name-only"]), @r"
deleted
modified
[EOF]
");
work_dir.run_jj(["commit", "-mfirst"]).success();
work_dir.remove_file("deleted");
work_dir.write_file("modified", "mod");
work_dir.write_file("added", "add");
work_dir.create_dir("sub");
work_dir.write_file("sub/added", "sub/add");
insta::assert_snapshot!(work_dir.run_jj(["diff", "--name-only"]).normalize_backslash(), @r"
added
deleted
modified
sub/added
[EOF]
");
}
#[test]
fn test_diff_renamed_file_and_dir() {
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("x", "content1");
work_dir.create_dir("y");
work_dir.write_file("y/file", "content2");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("x");
work_dir.remove_dir_all("y");
work_dir.create_dir("x");
work_dir.write_file("x/file", "content2");
work_dir.write_file("y", "content1");
// Renamed directory y->x shouldn't be reported
let output = work_dir.run_jj(["diff", "--summary"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
R {y => x}/file
R {x => y}
[EOF]
");
let output = work_dir.run_jj(["diff", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/y/file b/x/file
rename from y/file
rename to x/file
diff --git a/x b/y
rename from x
rename to y
[EOF]
");
}
#[test]
fn test_diff_bad_args() {
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(["diff", "-s", "--types"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--summary' cannot be used with '--types'
Usage: jj diff --summary [FILESETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["diff", "--color-words", "--git"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--color-words' cannot be used with '--git'
Usage: jj diff --color-words [FILESETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_diff_relative_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.create_dir_all("dir1/subdir1");
work_dir.create_dir("dir2");
work_dir.write_file("file1", "foo1\n");
work_dir.write_file("dir1/file2", "foo2\n");
work_dir.write_file("dir1/subdir1/file3", "foo3\n");
work_dir.write_file("dir2/file4", "foo4\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "bar1\n");
work_dir.write_file("dir1/file2", "bar2\n");
work_dir.write_file("dir1/subdir1/file3", "bar3\n");
work_dir.write_file("dir2/file4", "bar4\n");
let sub_dir1 = work_dir.dir("dir1");
let output = sub_dir1.run_jj(["diff"]);
#[cfg(unix)]
insta::assert_snapshot!(output, @r"
Modified regular file file2:
1 1: foo2bar2
Modified regular file subdir1/file3:
1 1: foo3bar3
Modified regular file ../dir2/file4:
1 1: foo4bar4
Modified regular file ../file1:
1 1: foo1bar1
[EOF]
");
#[cfg(windows)]
insta::assert_snapshot!(output, @r"
Modified regular file file2:
1 1: foo2bar2
Modified regular file subdir1\file3:
1 1: foo3bar3
Modified regular file ..\dir2\file4:
1 1: foo4bar4
Modified regular file ..\file1:
1 1: foo1bar1
[EOF]
");
let output = sub_dir1.run_jj(["diff", "-s"]);
#[cfg(unix)]
insta::assert_snapshot!(output, @r"
M file2
M subdir1/file3
M ../dir2/file4
M ../file1
[EOF]
");
#[cfg(windows)]
insta::assert_snapshot!(output, @r"
M file2
M subdir1\file3
M ..\dir2\file4
M ..\file1
[EOF]
");
let output = sub_dir1.run_jj(["diff", "--types"]);
#[cfg(unix)]
insta::assert_snapshot!(output, @r"
FF file2
FF subdir1/file3
FF ../dir2/file4
FF ../file1
[EOF]
");
#[cfg(windows)]
insta::assert_snapshot!(output, @r"
FF file2
FF subdir1\file3
FF ..\dir2\file4
FF ..\file1
[EOF]
");
let output = sub_dir1.run_jj(["diff", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/dir1/file2 b/dir1/file2
index 54b060eee9..1fe912cdd8 100644
--- a/dir1/file2
+++ b/dir1/file2
@@ -1,1 +1,1 @@
-foo2
+bar2
diff --git a/dir1/subdir1/file3 b/dir1/subdir1/file3
index c1ec6c6f12..f3c8b75ec6 100644
--- a/dir1/subdir1/file3
+++ b/dir1/subdir1/file3
@@ -1,1 +1,1 @@
-foo3
+bar3
diff --git a/dir2/file4 b/dir2/file4
index a0016dbc4c..17375f7a12 100644
--- a/dir2/file4
+++ b/dir2/file4
@@ -1,1 +1,1 @@
-foo4
+bar4
diff --git a/file1 b/file1
index 1715acd6a5..05c4fe6772 100644
--- a/file1
+++ b/file1
@@ -1,1 +1,1 @@
-foo1
+bar1
[EOF]
");
let output = sub_dir1.run_jj(["diff", "--stat"]);
#[cfg(unix)]
insta::assert_snapshot!(output, @r"
file2 | 2 +-
subdir1/file3 | 2 +-
../dir2/file4 | 2 +-
../file1 | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
[EOF]
");
#[cfg(windows)]
insta::assert_snapshot!(output, @r"
file2 | 2 +-
subdir1\file3 | 2 +-
..\dir2\file4 | 2 +-
..\file1 | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
[EOF]
");
}
#[test]
fn test_diff_hunks() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Test added, removed, inserted, and modified lines. The modified line
// contains unchanged words.
work_dir.write_file("file1", "");
work_dir.write_file("file2", "foo\n");
work_dir.write_file("file3", "foo\nbaz qux blah blah\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "");
work_dir.write_file("file3", "foo\nbar\nbaz quux blah blah\n");
let output = work_dir.run_jj(["diff"]);
insta::assert_snapshot!(output, @r"
Modified regular file file1:
1: foo
Modified regular file file2:
1 : foo
Modified regular file file3:
1 1: foo
2: bar
2 3: baz quxquux blah blah
[EOF]
");
let output = work_dir.run_jj(["diff", "--color=debug"]);
insta::assert_snapshot!(output, @r"
[38;5;3m<<diff header::Modified regular file file1:>>[39m
<<diff:: >>[38;5;2m<<diff added line_number:: 1>>[39m<<diff::: >>[4m[38;5;2m<<diff added token::foo>>[24m[39m
[38;5;3m<<diff header::Modified regular file file2:>>[39m
[38;5;1m<<diff removed line_number:: 1>>[39m<<diff:: : >>[4m[38;5;1m<<diff removed token::foo>>[24m[39m
[38;5;3m<<diff header::Modified regular file file3:>>[39m
[2m[38;5;1m<<diff context removed line_number:: 1>>[0m<<diff context:: >>[2m[38;5;2m<<diff context added line_number:: 1>>[0m<<diff context::: foo>>
<<diff:: >>[38;5;2m<<diff added line_number:: 2>>[39m<<diff::: >>[4m[38;5;2m<<diff added token::bar>>[24m[39m
[38;5;1m<<diff removed line_number:: 2>>[39m<<diff:: >>[38;5;2m<<diff added line_number:: 3>>[39m<<diff::: baz >>[4m[38;5;1m<<diff removed token::qux>>[38;5;2m<<diff added token::quux>>[24m[39m<<diff:: blah blah>>
[EOF]
");
let output = work_dir.run_jj(["diff", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file1 b/file1
index e69de29bb2..257cc5642c 100644
--- a/file1
+++ b/file1
@@ -0,0 +1,1 @@
+foo
diff --git a/file2 b/file2
index 257cc5642c..e69de29bb2 100644
--- a/file2
+++ b/file2
@@ -1,1 +0,0 @@
-foo
diff --git a/file3 b/file3
index 221a95a095..a543ef3892 100644
--- a/file3
+++ b/file3
@@ -1,2 +1,3 @@
foo
-baz qux blah blah
+bar
+baz quux blah blah
[EOF]
");
let output = work_dir.run_jj(["diff", "--git", "--color=debug"]);
insta::assert_snapshot!(output, @r"
[1m<<diff file_header::diff --git a/file1 b/file1>>[0m
[1m<<diff file_header::index e69de29bb2..257cc5642c 100644>>[0m
[1m<<diff file_header::--- a/file1>>[0m
[1m<<diff file_header::+++ b/file1>>[0m
[38;5;6m<<diff hunk_header::@@ -0,0 +1,1 @@>>[39m
[38;5;2m<<diff added::+>>[4m<<diff added token::foo>>[24m[39m
[1m<<diff file_header::diff --git a/file2 b/file2>>[0m
[1m<<diff file_header::index 257cc5642c..e69de29bb2 100644>>[0m
[1m<<diff file_header::--- a/file2>>[0m
[1m<<diff file_header::+++ b/file2>>[0m
[38;5;6m<<diff hunk_header::@@ -1,1 +0,0 @@>>[39m
[38;5;1m<<diff removed::->>[4m<<diff removed token::foo>>[24m[39m
[1m<<diff file_header::diff --git a/file3 b/file3>>[0m
[1m<<diff file_header::index 221a95a095..a543ef3892 100644>>[0m
[1m<<diff file_header::--- a/file3>>[0m
[1m<<diff file_header::+++ b/file3>>[0m
[38;5;6m<<diff hunk_header::@@ -1,2 +1,3 @@>>[39m
<<diff context:: foo>>
[38;5;1m<<diff removed::-baz >>[4m<<diff removed token::qux>>[24m<<diff removed:: blah blah>>[39m
[38;5;2m<<diff added::+>>[4m<<diff added token::bar>>[24m[39m
[38;5;2m<<diff added::+baz >>[4m<<diff added token::quux>>[24m<<diff added:: blah blah>>[39m
[EOF]
");
}
#[test]
fn test_diff_color_words_inlining_threshold() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let render_diff = |max_alternation: i32, args: &[&str]| {
let config = format!("diff.color-words.max-inline-alternation={max_alternation}");
work_dir.run_jj_with(|cmd| cmd.args(["diff", "--config", &config]).args(args))
};
let file1_path = "file1-single-line";
let file2_path = "file2-multiple-lines-in-single-hunk";
let file3_path = "file3-changes-across-lines";
work_dir.write_file(
file1_path,
indoc! {"
== adds ==
a b c
== removes ==
a b c d e f g
== adds + removes ==
a b c d e
== adds + removes + adds ==
a b c d e
== adds + removes + adds + removes ==
a b c d e f g
"},
);
work_dir.write_file(
file2_path,
indoc! {"
== adds; removes; adds + removes ==
a b c
a b c d e f g
a b c d e
== adds + removes + adds; adds + removes + adds + removes ==
a b c d e
a b c d e f g
"},
);
work_dir.write_file(
file3_path,
indoc! {"
== adds ==
a b c
== removes ==
a b c d
e f g
== adds + removes ==
a b c
d e
== adds + removes + adds ==
a b c
d e
== adds + removes + adds + removes ==
a b
c d e f g
"},
);
work_dir.run_jj(["new"]).success();
work_dir.write_file(
file1_path,
indoc! {"
== adds ==
a X b Y Z c
== removes ==
a c f
== adds + removes ==
a X b d
== adds + removes + adds ==
a X b d Y
== adds + removes + adds + removes ==
X a Y b d Z e
"},
);
work_dir.write_file(
file2_path,
indoc! {"
== adds; removes; adds + removes ==
a X b Y Z c
a c f
a X b d
== adds + removes + adds; adds + removes + adds + removes ==
a X b d Y
X a Y b d Z e
"},
);
work_dir.write_file(
file3_path,
indoc! {"
== adds ==
a X b
Y Z c
== removes ==
a c f
== adds + removes ==
a
X b d
== adds + removes + adds ==
a X b d
Y
== adds + removes + adds + removes ==
X a Y b d
Z e
"},
);
// default
let output = work_dir.run_jj(["diff"]);
insta::assert_snapshot!(output, @r"
Modified regular file file1-single-line:
1 1: == adds ==
2 2: a X b Y Z c
3 3: == removes ==
4 4: a b c d e f g
5 5: == adds + removes ==
6 6: a X b c d e
7 7: == adds + removes + adds ==
8 8: a X b c d eY
9 9: == adds + removes + adds + removes ==
10 : a b c d e f g
10: X a Y b d Z e
Modified regular file file2-multiple-lines-in-single-hunk:
1 1: == adds; removes; adds + removes ==
2 2: a X b Y Z c
3 3: a b c d e f g
4 4: a X b c d e
5 5: == adds + removes + adds; adds + removes + adds + removes ==
6 : a b c d e
7 : a b c d e f g
6: a X b d Y
7: X a Y b d Z e
Modified regular file file3-changes-across-lines:
1 1: == adds ==
2 2: a X b
2 3: Y Z c
3 4: == removes ==
4 5: a b c d
5 5: e f g
6 6: == adds + removes ==
7 7: a
7 8: X b c
8 8: d e
9 9: == adds + removes + adds ==
10 10: a X b c
11 10: d e
11 11: Y
12 12: == adds + removes + adds + removes ==
13 : a b
14 : c d e f g
13: X a Y b d
14: Z e
[EOF]
");
// -1: inline all
insta::assert_snapshot!(render_diff(-1, &[]), @r"
Modified regular file file1-single-line:
1 1: == adds ==
2 2: a X b Y Z c
3 3: == removes ==
4 4: a b c d e f g
5 5: == adds + removes ==
| 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_copy_detection.rs | cli/tests/test_copy_detection.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_simple_rename() {
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.write_file("original", "original");
work_dir.write_file("something", "something");
work_dir.run_jj(["commit", "-mfirst"]).success();
work_dir.remove_file("original");
work_dir.write_file("modified", "original");
work_dir.write_file("something", "changed");
insta::assert_snapshot!(
work_dir.run_jj(["debug", "copy-detection"]).normalize_backslash(), @r"
original -> modified
[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_advance_bookmarks.rs | cli/tests/test_advance_bookmarks.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 test_case::test_case;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[must_use]
fn get_log_output_with_bookmarks(work_dir: &TestWorkDir) -> CommandOutput {
// Don't include commit IDs since they will be different depending on
// whether the test runs with `jj commit` or `jj describe` + `jj new`.
let template = r#""bookmarks{" ++ local_bookmarks ++ "} desc: " ++ description"#;
work_dir.run_jj(["log", "-T", template])
}
fn set_advance_bookmarks(test_env: &TestEnvironment, enabled: bool) {
if enabled {
test_env.add_config(
r#"[experimental-advance-branches]
enabled-branches = ["*"]
"#,
);
} else {
test_env.add_config(
r#"[experimental-advance-branches]
enabled-branches = []
"#,
);
}
}
// Runs a command in the specified test workspace that describes the current
// commit with `commit_message` and creates a new commit on top of it.
type CommitFn = fn(work_dir: &TestWorkDir, commit_message: &str);
// Implements CommitFn using the `jj commit` command.
fn commit_cmd(work_dir: &TestWorkDir, commit_message: &str) {
work_dir.run_jj(["commit", "-m", commit_message]).success();
}
// Implements CommitFn using the `jj describe` and `jj new`.
fn describe_new_cmd(work_dir: &TestWorkDir, commit_message: &str) {
work_dir
.run_jj(["describe", "-m", commit_message])
.success();
work_dir.run_jj(["new"]).success();
}
// Check that enabling and disabling advance-bookmarks works as expected.
#[test_case(commit_cmd ; "commit")]
#[test_case(describe_new_cmd; "new")]
fn test_advance_bookmarks_enabled(make_commit: CommitFn) {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// First, test with advance-bookmarks enabled. Start by creating a bookmark on
// the root commit.
set_advance_bookmarks(&test_env, true);
work_dir
.run_jj(["bookmark", "create", "-r", "@-", "test_bookmark"])
.success();
// Check the initial state of the repo.
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
◆ bookmarks{test_bookmark} desc:
[EOF]
");
}
// Run jj commit, which will advance the bookmark pointing to @-.
make_commit(&work_dir, "first");
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{test_bookmark} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
// Now disable advance bookmarks and commit again. The bookmark shouldn't move.
set_advance_bookmarks(&test_env, false);
make_commit(&work_dir, "second");
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{} desc: second
○ bookmarks{test_bookmark} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
}
// Check that only a bookmark pointing to @- advances. Branches pointing to @
// are not advanced.
#[test_case(commit_cmd ; "commit")]
#[test_case(describe_new_cmd; "new")]
fn test_advance_bookmarks_at_minus(make_commit: CommitFn) {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
set_advance_bookmarks(&test_env, true);
work_dir
.run_jj(["bookmark", "create", "test_bookmark", "-r", "@"])
.success();
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{test_bookmark} desc:
◆ bookmarks{} desc:
[EOF]
");
}
make_commit(&work_dir, "first");
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{test_bookmark} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
// Create a second bookmark pointing to @. On the next commit, only the first
// bookmark, which points to @-, will advance.
work_dir
.run_jj(["bookmark", "create", "test_bookmark2", "-r", "@"])
.success();
make_commit(&work_dir, "second");
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{test_bookmark test_bookmark2} desc: second
○ bookmarks{} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
}
// Test that per-bookmark overrides invert the behavior of
// experimental-advance-branches.enabled.
#[test_case(commit_cmd ; "commit")]
#[test_case(describe_new_cmd; "new")]
fn test_advance_bookmarks_overrides(make_commit: CommitFn) {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// advance-branches is disabled by default.
work_dir
.run_jj(["bookmark", "create", "-r", "@-", "test_bookmark"])
.success();
// Check the initial state of the repo.
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
◆ bookmarks{test_bookmark} desc:
[EOF]
");
}
// Commit will not advance the bookmark since advance-branches is disabled.
make_commit(&work_dir, "first");
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{} desc: first
◆ bookmarks{test_bookmark} desc:
[EOF]
");
}
// Now enable advance branches for "test_bookmark", move the bookmark, and
// commit again.
test_env.add_config(
r#"[experimental-advance-branches]
enabled-branches = ["test_bookmark"]
"#,
);
work_dir
.run_jj(["bookmark", "set", "test_bookmark", "-r", "@-"])
.success();
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{test_bookmark} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
make_commit(&work_dir, "second");
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{test_bookmark} desc: second
○ bookmarks{} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
// Now disable advance branches for "test_bookmark" and enable for
// "second_bookmark", which we will use later. Disabling always takes
// precedence over enabling.
test_env.add_config(
r#"[experimental-advance-branches]
enabled-branches = ["test_bookmark | second_bookmark"]
disabled-branches = ["test_bookmark"]
"#,
);
make_commit(&work_dir, "third");
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{} desc: third
○ bookmarks{test_bookmark} desc: second
○ bookmarks{} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
// If we create a new bookmark at @- and move test_bookmark there as well. When
// we commit, only "second_bookmark" will advance since "test_bookmark" is
// disabled.
work_dir
.run_jj(["bookmark", "create", "second_bookmark", "-r", "@-"])
.success();
work_dir
.run_jj(["bookmark", "set", "test_bookmark", "-r", "@-"])
.success();
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{second_bookmark test_bookmark} desc: third
○ bookmarks{} desc: second
○ bookmarks{} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
make_commit(&work_dir, "fourth");
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{second_bookmark} desc: fourth
○ bookmarks{test_bookmark} desc: third
○ bookmarks{} desc: second
○ bookmarks{} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
}
// If multiple eligible bookmarks point to @-, all of them will be advanced.
#[test_case(commit_cmd ; "commit")]
#[test_case(describe_new_cmd; "new")]
fn test_advance_bookmarks_multiple_bookmarks(make_commit: CommitFn) {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
set_advance_bookmarks(&test_env, true);
work_dir
.run_jj(["bookmark", "create", "-r", "@-", "first_bookmark"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r", "@-", "second_bookmark"])
.success();
insta::allow_duplicates! {
// Check the initial state of the repo.
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
◆ bookmarks{first_bookmark second_bookmark} desc:
[EOF]
");
}
// Both bookmarks are eligible and both will advance.
make_commit(&work_dir, "first");
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{first_bookmark second_bookmark} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
}
// Call `jj new` on an interior commit and see that the bookmark pointing to its
// parent's parent is advanced.
#[test]
fn test_new_advance_bookmarks_interior() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
set_advance_bookmarks(&test_env, true);
// Check the initial state of the repo.
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
◆ bookmarks{} desc:
[EOF]
");
// Create a gap in the commits for us to insert our new commit with --before.
work_dir.run_jj(["commit", "-m", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir
.run_jj(["bookmark", "create", "-r", "@---", "test_bookmark"])
.success();
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{} desc: third
○ bookmarks{} desc: second
○ bookmarks{test_bookmark} desc: first
◆ bookmarks{} desc:
[EOF]
");
work_dir.run_jj(["new", "-r", "@--"]).success();
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
│ ○ bookmarks{} desc: third
├─╯
○ bookmarks{test_bookmark} desc: second
○ bookmarks{} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
// If the `--before` flag is passed to `jj new`, bookmarks are not advanced.
#[test]
fn test_new_advance_bookmarks_before() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
set_advance_bookmarks(&test_env, true);
// Check the initial state of the repo.
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
◆ bookmarks{} desc:
[EOF]
");
// Create a gap in the commits for us to insert our new commit with --before.
work_dir.run_jj(["commit", "-m", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir
.run_jj(["bookmark", "create", "-r", "@---", "test_bookmark"])
.success();
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{} desc: third
○ bookmarks{} desc: second
○ bookmarks{test_bookmark} desc: first
◆ bookmarks{} desc:
[EOF]
");
work_dir.run_jj(["new", "--before", "@-"]).success();
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
○ bookmarks{} desc: third
@ bookmarks{} desc:
○ bookmarks{} desc: second
○ bookmarks{test_bookmark} desc: first
◆ bookmarks{} desc:
[EOF]
");
}
// If the `--after` flag is passed to `jj new`, bookmarks are not advanced.
#[test]
fn test_new_advance_bookmarks_after() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
set_advance_bookmarks(&test_env, true);
work_dir
.run_jj(["bookmark", "create", "-r", "@-", "test_bookmark"])
.success();
// Check the initial state of the repo.
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
◆ bookmarks{test_bookmark} desc:
[EOF]
");
work_dir.run_jj(["describe", "-m", "first"]).success();
work_dir.run_jj(["new", "--after", "@"]).success();
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
○ bookmarks{} desc: first
◆ bookmarks{test_bookmark} desc:
[EOF]
");
}
#[test]
fn test_new_advance_bookmarks_merge_children() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
set_advance_bookmarks(&test_env, true);
work_dir.run_jj(["desc", "-m", "0"]).success();
work_dir.run_jj(["new", "-m", "1"]).success();
work_dir.run_jj(["new", "subject(0)", "-m", "2"]).success();
work_dir
.run_jj(["bookmark", "create", "test_bookmark", "-rsubject(0)"])
.success();
// Check the initial state of the repo.
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc: 2
│ ○ bookmarks{} desc: 1
├─╯
○ bookmarks{test_bookmark} desc: 0
◆ bookmarks{} desc:
[EOF]
");
// The bookmark won't advance because `jj new` had multiple targets.
work_dir
.run_jj(["new", "subject(1)", "subject(2)"])
.success();
insta::assert_snapshot!(get_log_output_with_bookmarks(&work_dir), @r"
@ bookmarks{} desc:
├─╮
│ ○ bookmarks{} desc: 2
○ │ bookmarks{} desc: 1
├─╯
○ bookmarks{test_bookmark} desc: 0
◆ bookmarks{} desc:
[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_immutable_commits.rs | cli/tests/test_immutable_commits.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::TestEnvironment;
#[test]
fn test_rewrite_immutable_generic() {
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", "a");
work_dir.run_jj(["describe", "-m=a"]).success();
work_dir.run_jj(["new", "-m=b"]).success();
work_dir.write_file("file", "b");
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
work_dir.run_jj(["new", "main-", "-m=c"]).success();
work_dir.write_file("file", "c");
let output = work_dir.run_jj(["log"]);
insta::assert_snapshot!(output, @r"
@ mzvwutvl test.user@example.com 2001-02-03 08:05:12 a6923629
│ c
│ ○ kkmpptxz test.user@example.com 2001-02-03 08:05:10 main 9d190342
├─╯ b
○ qpvuntsm test.user@example.com 2001-02-03 08:05:08 c8c8515a
│ a
◆ zzzzzzzz root() 00000000
[EOF]
");
// Cannot rewrite a commit in the configured set
test_env.add_config(r#"revset-aliases."immutable_heads()" = "main""#);
let output = work_dir.run_jj(["edit", "main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 9d190342454d is immutable
Hint: Could not modify commit: kkmpptxz 9d190342 main | b
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]
"#);
// Cannot rewrite an ancestor of the configured set
let output = work_dir.run_jj(["edit", "main-"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit c8c8515af455 is immutable
Hint: Could not modify commit: qpvuntsm c8c8515a a
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 2 immutable commits.
[EOF]
[exit status: 1]
"#);
// Cannot rewrite the root commit even with an empty set of immutable commits
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
let output = work_dir.run_jj(["edit", "root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The root commit 000000000000 is immutable
[EOF]
[exit status: 1]
");
// Error mutating the repo if immutable_heads() uses a ref that can't be
// resolved
test_env.add_config(r#"revset-aliases."immutable_heads()" = "bookmark_that_does_not_exist""#);
// Suppress warning in the commit summary template
test_env.add_config("template-aliases.'format_short_id(id)' = 'id.short(8)'");
let output = work_dir.run_jj(["new", "main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Invalid `revset-aliases.immutable_heads()`
Caused by: Revision `bookmark_that_does_not_exist` doesn't exist
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
// Can use --ignore-immutable to override
test_env.add_config(r#"revset-aliases."immutable_heads()" = "main""#);
let output = work_dir.run_jj(["--ignore-immutable", "edit", "main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 9d190342 main | b
Parent commit (@-) : qpvuntsm c8c8515a a
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
// ... but not the root commit
let output = work_dir.run_jj(["--ignore-immutable", "edit", "root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The root commit 000000000000 is immutable
[EOF]
[exit status: 1]
");
// Mutating the repo works if ref is wrapped in present()
test_env.add_config(
r#"revset-aliases."immutable_heads()" = "present(bookmark_that_does_not_exist)""#,
);
let output = work_dir.run_jj(["new", "main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: wqnwkozp 8fc35e6e (empty) (no description set)
Parent commit (@-) : kkmpptxz 9d190342 main | b
[EOF]
");
// immutable_heads() of different arity doesn't shadow the 0-ary one
test_env.add_config(r#"revset-aliases."immutable_heads(foo)" = "none()""#);
let output = work_dir.run_jj(["edit", "root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The root commit 000000000000 is immutable
[EOF]
[exit status: 1]
");
}
#[test]
fn test_new_wc_commit_when_wc_immutable() {
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();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "main""#);
work_dir.run_jj(["new", "-m=a"]).success();
let output = work_dir.run_jj(["bookmark", "set", "main", "-r@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Moved 1 bookmarks to kkmpptxz e1cb4cf3 main | (empty) a
Warning: The working-copy commit in workspace 'default' became immutable, so a new commit has been created on top of it.
Working copy (@) now at: zsuskuln 19a353fe (empty) (no description set)
Parent commit (@-) : kkmpptxz e1cb4cf3 main | (empty) a
[EOF]
");
}
#[test]
fn test_immutable_heads_set_to_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(["bookmark", "create", "-r@", "main"])
.success();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "@""#);
let output = work_dir.run_jj(["new", "-m=a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: The working-copy commit in workspace 'default' became immutable, so a new commit has been created on top of it.
Working copy (@) now at: pmmvwywv 08e27304 (empty) (no description set)
Parent commit (@-) : kkmpptxz e1cb4cf3 (empty) a
[EOF]
");
}
#[test]
fn test_new_wc_commit_when_wc_immutable_multi_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(["bookmark", "create", "-r@", "main"])
.success();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "main""#);
work_dir.run_jj(["new", "-m=a"]).success();
work_dir
.run_jj(["workspace", "add", "../workspace1"])
.success();
let workspace1_dir = test_env.work_dir("workspace1");
workspace1_dir.run_jj(["edit", "default@"]).success();
let output = work_dir.run_jj(["bookmark", "set", "main", "-r@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Moved 1 bookmarks to kkmpptxz e1cb4cf3 main | (empty) a
Warning: The working-copy commit in workspace 'default' became immutable, so a new commit has been created on top of it.
Warning: The working-copy commit in workspace 'workspace1' became immutable, so a new commit has been created on top of it.
Working copy (@) now at: royxmykx cec19492 (empty) (no description set)
Parent commit (@-) : kkmpptxz e1cb4cf3 main | (empty) a
[EOF]
");
workspace1_dir
.run_jj(["workspace", "update-stale"])
.success();
let output = workspace1_dir.run_jj(["log", "--no-graph"]);
insta::assert_snapshot!(output, @r"
nppvrztz test.user@example.com 2001-02-03 08:05:12 workspace1@ e89ed162
(empty) (no description set)
royxmykx test.user@example.com 2001-02-03 08:05:12 default@ cec19492
(empty) (no description set)
kkmpptxz test.user@example.com 2001-02-03 08:05:09 main e1cb4cf3
(empty) a
zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_rewrite_immutable_commands() {
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", "a");
work_dir.run_jj(["describe", "-m=a"]).success();
work_dir.run_jj(["new", "-m=b"]).success();
work_dir.write_file("file", "b");
work_dir.run_jj(["new", "@-", "-m=c"]).success();
work_dir.write_file("file", "c");
work_dir
.run_jj(["new", "visible_heads()", "-m=merge"])
.success();
// Create another file to make sure the merge commit isn't empty (to satisfy `jj
// split`) and still has a conflict (to satisfy `jj resolve`).
work_dir.write_file("file2", "merged");
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
work_dir.run_jj(["new", "subject(b)"]).success();
work_dir.write_file("file", "w");
test_env.add_config(r#"revset-aliases."immutable_heads()" = "main""#);
test_env.add_config(r#"revset-aliases."trunk()" = "main""#);
// Log shows mutable commits, their parents, and trunk() by default
let output = work_dir.run_jj(["log"]);
insta::assert_snapshot!(output, @r"
@ yqosqzyt test.user@example.com 2001-02-03 08:05:14 55c97dc7
│ (no description set)
│ ◆ mzvwutvl test.user@example.com 2001-02-03 08:05:12 main 7065a923 (conflict)
╭─┤ merge
│ │
│ ~
│
◆ kkmpptxz test.user@example.com 2001-02-03 08:05:10 9d190342
│ b
~
[EOF]
");
// abandon
let output = work_dir.run_jj(["abandon", "main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// absorb
let output = work_dir.run_jj(["absorb", "--into=::@-"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 9d190342454d is immutable
Hint: Could not modify commit: kkmpptxz 9d190342 b
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 2 immutable commits.
[EOF]
[exit status: 1]
"#);
// chmod
let output = work_dir.run_jj(["file", "chmod", "-r=main", "x", "file"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// describe
let output = work_dir.run_jj(["describe", "main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// diffedit
let output = work_dir.run_jj(["diffedit", "-r=main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// edit
let output = work_dir.run_jj(["edit", "main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// metaedit
let output = work_dir.run_jj(["metaedit", "-r=main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// new --insert-before
let output = work_dir.run_jj(["new", "--insert-before", "main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// new --insert-after parent_of_main
let output = work_dir.run_jj(["new", "--insert-after", "subject(b)"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// parallelize
let output = work_dir.run_jj(["parallelize", "subject(b)", "main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// rebase -s
let output = work_dir.run_jj(["rebase", "-s=main", "-d=@"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// rebase -b
let output = work_dir.run_jj(["rebase", "-b=main", "-d=@"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit dfa21421ac56 is immutable
Hint: Could not modify commit: zsuskuln dfa21421 c
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 2 immutable commits.
[EOF]
[exit status: 1]
"#);
// rebase -r
let output = work_dir.run_jj(["rebase", "-r=main", "-d=@"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// resolve
let output = work_dir.run_jj(["resolve", "-r=subject(merge)", "file"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// restore -c
let output = work_dir.run_jj(["restore", "-c=main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// restore --into
let output = work_dir.run_jj(["restore", "--into=main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// split
let output = work_dir.run_jj(["split", "-r=main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// split -B
let output = work_dir.run_jj(["split", "-B=main", "-m", "will fail", "file"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// squash -r
let output = work_dir.run_jj(["squash", "-r=subject(b)"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 9d190342454d is immutable
Hint: Could not modify commit: kkmpptxz 9d190342 b
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 4 immutable commits.
[EOF]
[exit status: 1]
"#);
// squash --from
let output = work_dir.run_jj(["squash", "--from=main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// squash --into
let output = work_dir.run_jj(["squash", "--into=main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// squash --after
let output = work_dir.run_jj(["squash", "--after=main-"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// squash --before
let output = work_dir.run_jj(["squash", "--before=main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// sign
let output = work_dir.run_jj(["sign", "-r=main", "--config=signing.backend=test"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
// unsign
let output = work_dir.run_jj(["unsign", "-r=main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit 7065a9233f35 is immutable
Hint: Could not modify commit: mzvwutvl 7065a923 main | (conflict) merge
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]
"#);
}
#[test]
fn test_immutable_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(["new"]).success();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "@-""#);
// The immutable commits should be indicated in the graph even with
// `--ignore-immutable`
let output = work_dir.run_jj(["log", "--ignore-immutable"]);
insta::assert_snapshot!(output, @r"
@ rlvkpnrz test.user@example.com 2001-02-03 08:05:08 43444d88
│ (empty) (no description set)
◆ qpvuntsm test.user@example.com 2001-02-03 08:05:07 e8849ae1
│ (empty) (no description set)
◆ zzzzzzzz root() 00000000
[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_revert_command.rs | cli/tests/test_revert_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::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit_with_files;
#[test]
fn test_revert() {
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, "a", &[], &[("a", "a\n")]);
create_commit_with_files(&work_dir, "b", &["a"], &[]);
create_commit_with_files(&work_dir, "c", &["b"], &[]);
create_commit_with_files(&work_dir, "d", &["c"], &[]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 98fb6151f954 d
○ 96ff42270bbc c
○ 58aaf278bf58 b
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["diff", "-ra", "-s"]);
insta::assert_snapshot!(output, @r"
A a
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// Reverting without a location is an error
let output = work_dir.run_jj(["revert", "-ra"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the following required arguments were not provided:
<--onto <REVSETS>|--insert-after <REVSETS>|--insert-before <REVSETS>>
Usage: jj revert --revisions <REVSETS> <--onto <REVSETS>|--insert-after <REVSETS>|--insert-before <REVSETS>>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Revert the commit with `--onto`
let output = work_dir.run_jj(["revert", "-ra", "-d@"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Reverted 1 commits as follows:
wqnwkozp 64910788 Revert "a"
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r#"
○ 64910788f8a5 Revert "a"
│
│ This reverts commit 7d980be7a1d499e4d316ab4c01242885032f7eaf.
@ 98fb6151f954 d
○ 96ff42270bbc c
○ 58aaf278bf58 b
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
"#);
let output = work_dir.run_jj(["diff", "-s", "-r@+"]);
insta::assert_snapshot!(output, @r"
D a
[EOF]
");
// Revert the new reverted commit
let output = work_dir.run_jj(["revert", "-r@+", "-d@+"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Reverted 1 commits as follows:
nkmrtpmo 90d12316 Revert "Revert "a""
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r#"
○ 90d123162199 Revert "Revert "a""
│
│ This reverts commit 64910788f8a5d322739e1e38ef35f7d06ea4b38d.
○ 64910788f8a5 Revert "a"
│
│ This reverts commit 7d980be7a1d499e4d316ab4c01242885032f7eaf.
@ 98fb6151f954 d
○ 96ff42270bbc c
○ 58aaf278bf58 b
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
"#);
let output = work_dir.run_jj(["diff", "-s", "-r@++"]);
insta::assert_snapshot!(output, @r"
A a
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Revert the commit with `--insert-after`
let output = work_dir.run_jj(["revert", "-ra", "-Ab"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Reverted 1 commits as follows:
nmzmmopx 9e7b8585 Revert "a"
Rebased 2 descendant commits
Working copy (@) now at: vruxwmqv b1885396 d | (empty) d
Parent commit (@-) : royxmykx efc4bd83 c | (empty) c
Added 0 files, modified 0 files, removed 1 files
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r#"
@ b18853966f79 d
○ efc4bd83159f c
○ 9e7b85853718 Revert "a"
│
│ This reverts commit 7d980be7a1d499e4d316ab4c01242885032f7eaf.
○ 58aaf278bf58 b
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
"#);
let output = work_dir.run_jj(["diff", "-s", "-rb+"]);
insta::assert_snapshot!(output, @r"
D a
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Revert the commit with `--insert-before`
let output = work_dir.run_jj(["revert", "-ra", "-Bd"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Reverted 1 commits as follows:
pzsxstzt d51ea564 Revert "a"
Rebased 1 descendant commits
Working copy (@) now at: vruxwmqv 5c5d60a6 d | (empty) d
Parent commit (@-) : pzsxstzt d51ea564 Revert "a"
Added 0 files, modified 0 files, removed 1 files
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r#"
@ 5c5d60a69afd d
○ d51ea56444ce Revert "a"
│
│ This reverts commit 7d980be7a1d499e4d316ab4c01242885032f7eaf.
○ 96ff42270bbc c
○ 58aaf278bf58 b
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
"#);
let output = work_dir.run_jj(["diff", "-s", "-rd-"]);
insta::assert_snapshot!(output, @r"
D a
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Revert the commit with `--insert-after` and `--insert-before`
let output = work_dir.run_jj(["revert", "-ra", "-Aa", "-Bd"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Reverted 1 commits as follows:
oupztwtk d311a8f0 Revert "a"
Rebased 1 descendant commits
Working copy (@) now at: vruxwmqv 5b97d572 d | (empty) d
Parent commit (@-) : royxmykx 96ff4227 c | (empty) c
Parent commit (@-) : oupztwtk d311a8f0 Revert "a"
Added 0 files, modified 0 files, removed 1 files
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r#"
@ 5b97d572e457 d
├─╮
│ ○ d311a8f0c13f Revert "a"
│ │
│ │ This reverts commit 7d980be7a1d499e4d316ab4c01242885032f7eaf.
○ │ 96ff42270bbc c
○ │ 58aaf278bf58 b
├─╯
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
"#);
let output = work_dir.run_jj(["diff", "-s", "-r", "a+ & d-"]);
insta::assert_snapshot!(output, @r"
D a
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Revert nothing
let output = work_dir.run_jj(["revert", "-r", "none()", "-d", "@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No revisions to revert.
[EOF]
");
}
#[test]
fn test_revert_multiple() {
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, "a", &[], &[("a", "a\n")]);
create_commit_with_files(&work_dir, "b", &["a"], &[("a", "a\nb\n")]);
create_commit_with_files(&work_dir, "c", &["b"], &[("a", "a\nb\n"), ("b", "b\n")]);
create_commit_with_files(&work_dir, "d", &["c"], &[]);
create_commit_with_files(&work_dir, "e", &["d"], &[("a", "a\nb\nc\n")]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 51a01d6d8cc4 e
○ 4b9d123d3b33 d
○ 05e1f540476f c
○ f93a910dbdf0 b
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
");
// Revert multiple commits
let output = work_dir.run_jj(["revert", "-rb", "-rc", "-re", "-d@"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Reverted 3 commits as follows:
wqnwkozp 4329cf72 Revert "e"
mouksmqu 092f722e Revert "c"
tqvpomtp c90eef02 Revert "b"
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r#"
○ c90eef022369 Revert "b"
│
│ This reverts commit f93a910dbdf0f841e6cf2bc0ab0ba4c336d6f436.
○ 092f722e521f Revert "c"
│
│ This reverts commit 05e1f540476f8c4207ff44febbe2ce6e6696dc4b.
○ 4329cf7230d7 Revert "e"
│
│ This reverts commit 51a01d6d8cc48a296cb87f8383b34ade3c050363.
@ 51a01d6d8cc4 e
○ 4b9d123d3b33 d
○ 05e1f540476f c
○ f93a910dbdf0 b
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
"#);
// View the output of each reverted commit
let output = work_dir.run_jj(["show", "@+"]);
insta::assert_snapshot!(output, @r#"
Commit ID: 4329cf7230d7b8229e9c88087cfa2f8aa13a1317
Change ID: wqnwkozpkustnxypnnntnykwrqrkrpvv
Author : Test User <test.user@example.com> (2001-02-03 08:05:19)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:19)
Revert "e"
This reverts commit 51a01d6d8cc48a296cb87f8383b34ade3c050363.
Modified regular file a:
1 1: a
2 2: b
3 : c
[EOF]
"#);
let output = work_dir.run_jj(["show", "@++"]);
insta::assert_snapshot!(output, @r#"
Commit ID: 092f722e521fe49fde5a3830568fe1c51b8f2f5f
Change ID: mouksmquosnpvwqrpsvvxtxpywpnxlss
Author : Test User <test.user@example.com> (2001-02-03 08:05:19)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:19)
Revert "c"
This reverts commit 05e1f540476f8c4207ff44febbe2ce6e6696dc4b.
Removed regular file b:
1 : b
[EOF]
"#);
let output = work_dir.run_jj(["show", "@+++"]);
insta::assert_snapshot!(output, @r#"
Commit ID: c90eef022369d43d5eae8303101b5889b4b73963
Change ID: tqvpomtpwrqsylrpsxknultrymmqxmxv
Author : Test User <test.user@example.com> (2001-02-03 08:05:19)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:19)
Revert "b"
This reverts commit f93a910dbdf0f841e6cf2bc0ab0ba4c336d6f436.
Modified regular file a:
1 1: a
2 : b
[EOF]
"#);
}
#[test]
fn test_revert_description_template() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
test_env.add_config(
r#"
[templates]
revert_description = '''
separate(" ",
"Revert commit",
commit_id.short(),
'"' ++ description.first_line() ++ '"',
)
'''
"#,
);
let work_dir = test_env.work_dir("repo");
create_commit_with_files(&work_dir, "a", &[], &[("a", "a\n")]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 7d980be7a1d4 a
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
A a
[EOF]
");
// Verify that message of reverted commit follows the template
let output = work_dir.run_jj(["revert", "-r@", "-d@"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Reverted 1 commits as follows:
royxmykx 6bfb98a3 Revert commit 7d980be7a1d4 "a"
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r#"
○ 6bfb98a33f58 Revert commit 7d980be7a1d4 "a"
@ 7d980be7a1d4 a
◆ 000000000000
[EOF]
"#);
}
#[test]
fn test_revert_with_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, "a", &[], &[("a", "a\n")]);
create_commit_with_files(&work_dir, "b", &["a"], &[("a", "a\nb\n")]);
create_commit_with_files(&work_dir, "c", &["b"], &[("a", "a\nb\nc\n")]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 48b910edc43e c
○ f93a910dbdf0 b
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
");
// Create a conflict by reverting B onto C
let output = work_dir.run_jj(["revert", "-r=b", "--onto=c"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Reverted 1 commits as follows:
yostqsxw 0b3e98ea (conflict) Revert "b"
New conflicts appeared in 1 commits:
yostqsxw 0b3e98ea (conflict) Revert "b"
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new yostqsxw
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#"
× 0b3e98eae4a9 Revert "b"
│
│ This reverts commit f93a910dbdf0f841e6cf2bc0ab0ba4c336d6f436.
@ 48b910edc43e c
○ f93a910dbdf0 b
○ 7d980be7a1d4 a
◆ 000000000000
[EOF]
"#);
// Reverted commit should contain conflict markers
let output = work_dir.run_jj(["file", "show", "-r=@+", "a"]);
insta::assert_snapshot!(output, @r#"
a
<<<<<<< conflict 1 of 1
%%%%%%% diff from: zsuskuln f93a910d "b" (reverted revision)
\\\\\\\ to: royxmykx 48b910ed "c" (revert destination)
b
+c
+++++++ rlvkpnrz 7d980be7 "a" (parents of reverted revision)
>>>>>>> conflict 1 of 1 ends
[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_edit_command.rs | cli/tests/test_edit_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;
#[test]
fn test_edit() {
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", "0");
work_dir.run_jj(["commit", "-m", "first"]).success();
work_dir.run_jj(["describe", "-m", "second"]).success();
work_dir.write_file("file1", "1");
// Errors out without argument
let output = work_dir.run_jj(["edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the following required arguments were not provided:
<REVSET|-r <REVSET>>
Usage: jj edit <REVSET|-r <REVSET>>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Errors out with duplicated arguments
let output = work_dir.run_jj(["edit", "@", "-r@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '[REVSET]' cannot be used with '-r <REVSET>'
Usage: jj edit <REVSET|-r <REVSET>>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Makes the specified commit the working-copy commit
let output = work_dir.run_jj(["edit", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 1f6994f8 first
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = get_log_output(&work_dir);
insta::assert_snapshot!(output, @r"
○ adc8b2014db6 second
@ 1f6994f8b95b first
◆ 000000000000
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file1"), @"0");
// Changes in the working copy are amended into the commit
work_dir.write_file("file2", "0");
let output = get_log_output(&work_dir);
insta::assert_snapshot!(output, @r"
○ 29c4ac30d18f second
@ b10da1f49611 first
◆ 000000000000
[EOF]
------- stderr -------
Rebased 1 descendant commits onto updated working copy
[EOF]
");
// Cannot edit multiple revisions
let output = work_dir.run_jj(["edit", "-r::"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revset `::` resolved to more than one revision
Hint: The revset `::` resolved to these revisions:
rlvkpnrz 29c4ac30 second
qpvuntsm b10da1f4 first
zzzzzzzz 00000000 (empty) (no description set)
[EOF]
[exit status: 1]
");
}
#[test]
fn test_edit_current() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Editing the current revision is a no-op
let output = work_dir.run_jj(["edit", "@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Already editing that commit
[EOF]
");
// No operation created
let output = work_dir.run_jj(["op", "log", "--limit=1"]);
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'
[EOF]
");
}
#[test]
// Windows says "Access is denied" when trying to delete the object file.
#[cfg(unix)]
fn test_edit_current_wc_commit_missing() {
use std::path::PathBuf;
// Test that we get a reasonable error message when the current working-copy
// commit is missing
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", "first"]).success();
work_dir.run_jj(["describe", "-m", "second"]).success();
work_dir.run_jj(["edit", "@-"]).success();
let wc_id = work_dir
.run_jj(["log", "--no-graph", "-T=commit_id", "-r=@"])
.success()
.stdout
.into_raw();
let wc_child_id = work_dir
.run_jj(["log", "--no-graph", "-T=commit_id", "-r=@+"])
.success()
.stdout
.into_raw();
// Make the Git backend fail to read the current working copy commit
let commit_object_path = PathBuf::from_iter([
".jj",
"repo",
"store",
"git",
"objects",
&wc_id[..2],
&wc_id[2..],
]);
work_dir.remove_file(commit_object_path);
// Pass --ignore-working-copy to avoid triggering the error at snapshot time
let output = work_dir.run_jj(["edit", "--ignore-working-copy", &wc_child_id]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Internal error: Failed to edit a commit
Caused by:
1: Current working-copy commit not found
2: Object 68a505386f936fff6d718f55005e77ea72589bc1 of type commit not found
3: An object with id 68a505386f936fff6d718f55005e77ea72589bc1 could not be found
[EOF]
[exit status: 255]
");
}
#[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_metaedit_command.rs | cli/tests/test_metaedit_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;
#[test]
fn test_metaedit() {
let mut 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(&work_dir), @r"
@ Commit ID: 22be6c4e01da7039a1a8c3adb91b8841252bb354
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│
│ (no description set)
│
○ Commit ID: 75591b1896b4990e7695701fd7cdbb32dba3ff50
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// Without arguments, the commits are not rewritten.
// TODO: Require an argument?
let output = work_dir.run_jj(["metaedit", "kkmpptxzrspx"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// When resetting the author has no effect, the commits are not rewritten.
let output = work_dir.run_jj([
"metaedit",
"--config=user.name=Test User",
"--update-author",
"kkmpptxzrspx",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Update author, ensure the commit can be specified with -r too
work_dir.run_jj(["op", "restore", &setup_opid]).success();
work_dir
.run_jj([
"metaedit",
"--config=user.name=Ove Ridder",
"--config=user.email=ove.ridder@example.com",
"--update-author",
"-r",
"kkmpptxzrspx",
])
.success();
insta::assert_snapshot!(get_log(&work_dir), @r"
@ Commit ID: 6f31b2555777ac2261dd17008b6fdc42619ebe1f
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Ove Ridder <ove.ridder@example.com> (2001-02-03 04:05:17.000 +07:00)
│
│ (no description set)
│
○ Commit ID: 590c8b6945666401d01269190c1b82cd3311a0cd
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Ove Ridder <ove.ridder@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Ove Ridder <ove.ridder@example.com> (2001-02-03 04:05:17.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
// Update author timestamp
work_dir.run_jj(["op", "restore", &setup_opid]).success();
work_dir
.run_jj(["metaedit", "--update-author-timestamp", "kkmpptxzrspx"])
.success();
insta::assert_snapshot!(get_log(&work_dir), @r"
@ Commit ID: b23f6a3f160d122f8d8dacd8d2acff2d29d5ba84
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:20.000 +07:00)
│
│ (no description set)
│
○ Commit ID: f121a0fb72e1790e4116b2e3b6989c795ac7f74b
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:20.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:20.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
// Set author
work_dir.run_jj(["op", "restore", &setup_opid]).success();
work_dir
.run_jj([
"metaedit",
"--author",
"Alice <alice@example.com>",
"kkmpptxzrspx",
])
.success();
insta::assert_snapshot!(get_log(&work_dir), @r"
@ Commit ID: 74007c679b9e4f13d1e3d553ef8397586b033421
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:23.000 +07:00)
│
│ (no description set)
│
○ Commit ID: d070c8adbc590813c81e296591d6b2cac8f3bb41
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Alice <alice@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:23.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
// new author date
work_dir.run_jj(["op", "restore", &setup_opid]).success();
work_dir
.run_jj([
"metaedit",
"--author-timestamp",
"1995-12-19T16:39:57-08:00",
])
.success();
insta::assert_snapshot!(get_log(&work_dir), @r"
@ Commit ID: a527219f85839d58ddb6115fbc4f0f8bc6649266
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (1995-12-19 16:39:57.000 -08:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:26.000 +07:00)
│
│ (no description set)
│
○ Commit ID: 75591b1896b4990e7695701fd7cdbb32dba3ff50
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
// invalid date gives an error
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["metaedit", "--author-timestamp", "aaaaaa"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value 'aaaaaa' for '--author-timestamp <AUTHOR_TIMESTAMP>': input contains invalid characters
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Update committer timestamp
work_dir.run_jj(["op", "restore", &setup_opid]).success();
work_dir
.run_jj(["metaedit", "--force-rewrite", "kkmpptxzrspx"])
.success();
insta::assert_snapshot!(get_log(&work_dir), @r"
@ Commit ID: 6c0aa6574ef6450eaf7eae1391cc6c769c53a50c
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:31.000 +07:00)
│
│ (no description set)
│
○ Commit ID: 0a570dfbbaf794cd15bbdbf28f94785405ef5b3b
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:31.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
// change test author config for changing committer
test_env.add_env_var("JJ_USER", "Test Committer");
test_env.add_env_var("JJ_EMAIL", "test.committer@example.com");
let work_dir = test_env.work_dir("repo");
// update existing commit with restored test author config
insta::assert_snapshot!(work_dir.run_jj(["metaedit", "--force-rewrite"]), @r"
------- stderr -------
Modified 1 commits:
mzvwutvl 75259df4 c | (no description set)
Working copy (@) now at: mzvwutvl 75259df4 c | (no description set)
Parent commit (@-) : kkmpptxz 0a570dfb b | (no description set)
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["show"]), @r"
Commit ID: 75259df433eebc10b3ad78a9814d6647b764ce28
Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
Bookmarks: c
Author : Test User <test.user@example.com> (2001-02-03 08:05:13)
Committer: Test Committer <test.committer@example.com> (2001-02-03 08:05:33)
(no description set)
Modified regular file file1:
1 1: bc
[EOF]
");
// When resetting the description has no effect, the commits are not rewritten.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["metaedit", "--message", "", "kkmpptxzrspx"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Update description
work_dir
.run_jj(["metaedit", "--message", "d\ne\nf"])
.success();
insta::assert_snapshot!(get_log(&work_dir), @r"
@ Commit ID: 502004368461738c866bc690ce08f7c219a4de10
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Test Committer <test.committer@example.com> (2001-02-03 04:05:37.000 +07:00)
│
│ d
│ e
│ f
│
○ Commit ID: 75591b1896b4990e7695701fd7cdbb32dba3ff50
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
// Set empty description
work_dir.run_jj(["metaedit", "--message", ""]).success();
insta::assert_snapshot!(get_log(&work_dir), @r"
@ Commit ID: a44f230f9af7eed606af7713774feba5e39f36f7
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Test Committer <test.committer@example.com> (2001-02-03 04:05:39.000 +07:00)
│
│ (no description set)
│
○ Commit ID: 75591b1896b4990e7695701fd7cdbb32dba3ff50
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
}
#[test]
fn test_metaedit_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(["metaedit", "--update-change-id", "none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No revisions to modify.
[EOF]
");
}
#[test]
fn test_metaedit_multiple_revisions() {
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(&work_dir), @r"
@ Commit ID: 22be6c4e01da7039a1a8c3adb91b8841252bb354
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│
│ (no description set)
│
○ Commit ID: 75591b1896b4990e7695701fd7cdbb32dba3ff50
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// Update multiple revisions
work_dir.run_jj(["op", "restore", &setup_opid]).success();
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj([
"metaedit",
"--config=user.name=Ove Ridder",
"--config=user.email=ove.ridder@example.com",
"--update-author",
"kkmpptxz::mzvwutvl",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Modified 2 commits:
kkmpptxz d84add51 b | (no description set)
mzvwutvl 447d6d8a c | (no description set)
Rebased 1 descendant commits
Working copy (@) now at: yostqsxw ebd66676 (empty) (no description set)
Parent commit (@-) : mzvwutvl 447d6d8a c | (no description set)
[EOF]
");
insta::assert_snapshot!(get_log(&work_dir), @r"
@ Commit ID: ebd66676fa9e0cd2c9f560bc0dc343b8809e4dfe
│ Change ID: yostqsxwqrltovqlrlzszywzslusmuup
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:15.000 +07:00)
│ Committer: Ove Ridder <ove.ridder@example.com> (2001-02-03 04:05:16.000 +07:00)
│
│ (no description set)
│
○ Commit ID: 447d6d8a12d90ff0f10bbefc552f9272694389d6
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Ove Ridder <ove.ridder@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Ove Ridder <ove.ridder@example.com> (2001-02-03 04:05:16.000 +07:00)
│
│ (no description set)
│
○ Commit ID: d84add5150537e89db428790c0f9413320127f00
│ Change ID: kkmpptxzrspxrzommnulwmwkkqwworpl
│ Bookmarks: b
│ Author : Ove Ridder <ove.ridder@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Ove Ridder <ove.ridder@example.com> (2001-02-03 04:05:16.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
}
#[test]
fn test_new_change_id() {
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");
let output = work_dir.run_jj(["metaedit", "--update-change-id", "kkmpptxzrspx"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Modified 1 commits:
yqosqzyt 01d6741e b | (no description set)
Rebased 1 descendant commits
Working copy (@) now at: mzvwutvl 0c3fe2d8 c | (no description set)
Parent commit (@-) : yqosqzyt 01d6741e b | (no description set)
[EOF]
");
insta::assert_snapshot!(get_log(&work_dir), @r"
@ Commit ID: 0c3fe2d854b2b492a053156a505d6c40fe783138
│ Change ID: mzvwutvlkqwtuzoztpszkqxkqmqyqyxo
│ Bookmarks: c
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│
│ (no description set)
│
○ Commit ID: 01d6741ed708318bcd5911320237066db4b63b53
│ Change ID: yqosqzytrlswkspswpqrmlplxylrzsnz
│ Bookmarks: b
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:11.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:13.000 +07:00)
│
│ (no description set)
│
○ Commit ID: e6086990958c236d72030f0a2651806aa629f5dd
│ Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
│ Bookmarks: a
│ Author : Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│ Committer: Test User <test.user@example.com> (2001-02-03 04:05:09.000 +07:00)
│
│ (no description set)
│
◆ Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
Committer: (no name set) <(no email set)> (1970-01-01 00:00:00.000 +00:00)
(no description set)
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["evolog", "-r", "yqosqzytrlswkspswpqrmlplxylrzsnz"]), @r"
○ yqosqzyt test.user@example.com 2001-02-03 08:05:13 b 01d6741e
│ (no description set)
│ -- operation adf0af78a0fd edit commit metadata for commit 75591b1896b4990e7695701fd7cdbb32dba3ff50
○ kkmpptxz/0 test.user@example.com 2001-02-03 08:05:11 75591b18 (hidden)
│ (no description set)
│ -- operation 4b33c26502f8 snapshot working copy
○ kkmpptxz/1 test.user@example.com 2001-02-03 08:05:09 acebf2bd (hidden)
(empty) (no description set)
-- operation 686c6e44c08d new empty commit
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["evolog", "-r", "mzvwut"]), @r"
@ mzvwutvl test.user@example.com 2001-02-03 08:05:13 c 0c3fe2d8
│ (no description set)
│ -- operation adf0af78a0fd edit commit metadata for commit 75591b1896b4990e7695701fd7cdbb32dba3ff50
○ mzvwutvl/1 test.user@example.com 2001-02-03 08:05:13 22be6c4e (hidden)
│ (no description set)
│ -- operation 92fee3ece32c snapshot working copy
○ mzvwutvl/2 test.user@example.com 2001-02-03 08:05:11 b9f5490a (hidden)
(empty) (no description set)
-- operation e3fbc5040416 new empty commit
[EOF]
");
}
#[test]
fn test_metaedit_option_mutual_exclusion() {
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=a"]).success();
work_dir.run_jj(["describe", "-m=b"]).success();
insta::assert_snapshot!(work_dir.run_jj([
"metaedit",
"--author=Alice <alice@example.com>",
"--update-author",
]), @r"
------- stderr -------
error: the argument '--author <AUTHOR>' cannot be used with '--update-author'
Usage: jj metaedit --author <AUTHOR> [REVSETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
insta::assert_snapshot!(work_dir.run_jj([
"metaedit",
"--update-committer-timestamp",
"--force-rewrite",
]), @r"
------- stderr -------
error: the argument '--update-committer-timestamp' cannot be used with '--force-rewrite'
Usage: jj metaedit [OPTIONS] [REVSETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_update_empty_author_or_email() {
let mut test_env = TestEnvironment::default();
// get rid of test author config
test_env.add_env_var("JJ_USER", "");
test_env.add_env_var("JJ_EMAIL", "");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
// show that commit has no author set
insta::assert_snapshot!(test_env.work_dir("repo").run_jj(["show"]), @r"
Commit ID: 42c91a3e183efb4499038d0d9aa3d14b5deafde0
Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
Author : (no name set) <(no email set)> (2001-02-03 08:05:07)
Committer: (no name set) <(no email set)> (2001-02-03 08:05:07)
(no description set)
[EOF]
");
// restore test author config, exercise --quiet
test_env.add_env_var("JJ_USER", "Test User");
test_env.add_env_var("JJ_EMAIL", "test.user@example.com");
let work_dir = test_env.work_dir("repo");
// update existing commit with restored test author config
insta::assert_snapshot!(work_dir.run_jj(["metaedit", "--update-author", "--quiet"]), @"");
insta::assert_snapshot!(work_dir.run_jj(["show"]), @r"
Commit ID: 0f13b5f2ea7fad147c133c81b87d31e7b1b8c564
Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
(no description set)
[EOF]
");
// confirm user / email can be cleared/restored separately
// leave verbose to see no-email warning + hint
test_env.add_env_var("JJ_EMAIL", "");
let work_dir = test_env.work_dir("repo");
insta::assert_snapshot!(work_dir.run_jj(["metaedit", "--update-author"]), @r#"
------- stderr -------
Modified 1 commits:
qpvuntsm 234908d4 (empty) (no description set)
Working copy (@) now at: qpvuntsm 234908d4 (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Warning: Email not configured. Until configured, your commits will be created with the empty identity, and can't be pushed to remotes.
Hint: To configure, run:
jj config set --user user.email "someone@example.com"
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["show"]), @r"
Commit ID: 234908d4748ff3224a87888d8b52a4923e1a89a5
Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
Author : Test User <(no email set)> (2001-02-03 08:05:09)
Committer: Test User <(no email set)> (2001-02-03 08:05:11)
(no description set)
[EOF]
");
// confirm no-name warning + hint
test_env.add_env_var("JJ_USER", "");
test_env.add_env_var("JJ_EMAIL", "test.user@example.com");
let work_dir = test_env.work_dir("repo");
insta::assert_snapshot!(work_dir.run_jj(["metaedit", "--update-author"]), @r#"
------- stderr -------
Modified 1 commits:
qpvuntsm ac5048cf (empty) (no description set)
Working copy (@) now at: qpvuntsm ac5048cf (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Warning: Name not configured. Until configured, your commits will be created with the empty identity, and can't be pushed to remotes.
Hint: To configure, run:
jj config set --user user.name "Some One"
[EOF]
"#);
insta::assert_snapshot!(work_dir.run_jj(["show"]), @r"
Commit ID: ac5048cf35372ddc30e2590271781a3eab0bcaf8
Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
Author : (no name set) <test.user@example.com> (2001-02-03 08:05:09)
Committer: (no name set) <test.user@example.com> (2001-02-03 08:05:13)
(no description set)
[EOF]
");
}
#[test]
/// Test that setting the same timestamp twice does nothing (issue #7602)
fn test_metaedit_set_same_timestamp_twice() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Set the author-timestamp to the same value twice
// and check that the second time it does nothing
let output = work_dir.run_jj([
"metaedit",
"--author-timestamp",
"2001-02-03 04:05:14.000+07:00",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Modified 1 commits:
qpvuntsm 51b97b23 (empty) (no description set)
Working copy (@) now at: qpvuntsm 51b97b23 (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// Running it again with the same date has no effect
let output = work_dir.run_jj([
"metaedit",
"--author-timestamp",
"2001-02-03 04:05:14.000+07:00",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
}
#[must_use]
fn get_log(work_dir: &TestWorkDir) -> CommandOutput {
work_dir.run_jj([
"--config",
"template-aliases.'format_timestamp(t)'='t'",
"log",
"-T",
"builtin_log_detailed",
])
}
| 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_interdiff_command.rs | cli/tests/test_interdiff_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;
#[test]
fn test_interdiff_basic() {
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", "-madd file2 left"]).success();
work_dir.write_file("file2", "foo\n");
work_dir
.run_jj(["bookmark", "create", "-r@", "left"])
.success();
work_dir.run_jj(["new", "root()"]).success();
work_dir.write_file("file3", "foo\n");
work_dir.run_jj(["new", "-madd file2 right"]).success();
work_dir.write_file("file2", "foo\nbar\n");
work_dir
.run_jj(["bookmark", "create", "-r@", "right"])
.success();
let setup_opid = work_dir.current_operation_id();
// implicit --to
let output = work_dir.run_jj(["interdiff", "--from", "left"]);
insta::assert_snapshot!(output, @r"
Modified commit description:
1 1: add file2 leftright
Modified regular file file2:
1 1: foo
2: bar
[EOF]
");
// explicit --to
work_dir.run_jj(["new", "@-"]).success();
let output = work_dir.run_jj(["interdiff", "--from", "left", "--to", "right"]);
insta::assert_snapshot!(output, @r"
Modified commit description:
1 1: add file2 leftright
Modified regular file file2:
1 1: foo
2: bar
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// formats specifiers
let output = work_dir.run_jj(["interdiff", "--from", "left", "--to", "right", "-s"]);
insta::assert_snapshot!(output, @r"
M file2
[EOF]
");
let output = work_dir.run_jj(["interdiff", "--from", "left", "--to", "right", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/JJ-COMMIT-DESCRIPTION b/JJ-COMMIT-DESCRIPTION
--- JJ-COMMIT-DESCRIPTION
+++ JJ-COMMIT-DESCRIPTION
@@ -1,1 +1,1 @@
-add file2 left
+add file2 right
diff --git a/file2 b/file2
index 257cc5642c..3bd1f0e297 100644
--- a/file2
+++ b/file2
@@ -1,1 +1,2 @@
foo
+bar
[EOF]
");
}
#[test]
fn test_interdiff_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", "foo\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "bar\n");
work_dir.write_file("file2", "bar\n");
work_dir
.run_jj(["bookmark", "create", "-r@", "left"])
.success();
work_dir.run_jj(["new", "root()"]).success();
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "foo\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "baz\n");
work_dir.write_file("file2", "baz\n");
work_dir
.run_jj(["bookmark", "create", "-r@", "right"])
.success();
let output = work_dir.run_jj(["interdiff", "--from", "left", "--to", "right", "file1"]);
insta::assert_snapshot!(output, @r"
Modified regular file file1:
1 1: barbaz
[EOF]
");
let output = work_dir.run_jj([
"interdiff",
"--from",
"left",
"--to",
"right",
"file1",
"file2",
"nonexistent",
]);
insta::assert_snapshot!(output, @r"
Modified regular file file1:
1 1: barbaz
Modified regular file file2:
1 1: barbaz
[EOF]
------- stderr -------
Warning: No matching entries for paths: nonexistent
[EOF]
");
// Running interdiff on commits with deleted files should not show a warning.
work_dir.run_jj(["edit", "right"]).success();
work_dir.remove_file("file1");
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj([
"interdiff",
"--from",
"left",
"--to",
"right",
"file1",
"file2",
]);
insta::assert_snapshot!(output, @r"
Removed regular file file1:
1 : bar
Modified regular file file2:
1 1: barbaz
[EOF]
");
}
#[test]
fn test_interdiff_conflicting() {
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(["bookmark", "create", "-r@", "left"])
.success();
work_dir.run_jj(["new", "root()"]).success();
work_dir.write_file("file", "abc\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "def\n");
work_dir
.run_jj(["bookmark", "create", "-r@", "right"])
.success();
let output = work_dir.run_jj(["interdiff", "--from", "left", "--to", "right", "--git"]);
insta::assert_snapshot!(output, @r"
diff --git a/file b/file
index 0000000000..24c5735c3e 100644
--- a/file
+++ b/file
@@ -1,8 +1,1 @@
-<<<<<<< conflict 1 of 1
-%%%%%%% diff from: qpvuntsm d0c049cd (original parents)
-\\\\\\\ to: zsuskuln 0b2c304e (new parents)
--foo
-+abc
-+++++++ rlvkpnrz b23f92c3 (original revision)
-bar
->>>>>>> conflict 1 of 1 ends
+def
[EOF]
");
let output = work_dir.run_jj([
"interdiff",
"--config=diff.color-words.conflict=pair",
"--color=always",
"--from=left",
"--to=right",
]);
insta::assert_snapshot!(output, @r"
[38;5;3mResolved conflict in file:[39m
[38;5;6m<<<<<<< Resolved conflict[39m
[38;5;6m+++++++ left side #1 to right side #1[39m
[38;5;1m 1[39m [38;5;2m 1[39m: [4m[38;5;1mabc[38;5;2mdef[24m[39m
[38;5;6m------- left base #1 to right side #1[39m
[38;5;2m 1[39m [38;5;1m 1[39m: [4m[38;5;2mfoo[38;5;1mdef[24m[39m
[38;5;6m+++++++ left side #2 to right side #1[39m
[38;5;1m 1[39m [38;5;2m 1[39m: [4m[38;5;1mbar[38;5;2mdef[24m[39m
[38;5;6m>>>>>>> Conflict ends[39m
[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_undo_redo_commands.rs | cli/tests/test_undo_redo_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_undo_root_operation() {
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(["undo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Restored to operation: 000000000000 root()
[EOF]
");
let output = work_dir.run_jj(["undo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Cannot undo root operation
[EOF]
[exit status: 1]
");
}
#[test]
fn test_undo_merge_operation() {
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", "--at-op=@-"]).success();
let output = work_dir.run_jj(["undo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Concurrent modification detected, resolving automatically.
Error: Cannot undo a merge operation
Hint: Consider using `jj op restore` instead
[EOF]
[exit status: 1]
");
}
#[test]
fn test_undo_push_operation() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "origin"])
.success();
test_env
.run_jj_in(".", ["git", "clone", "origin", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("foo", "foo");
work_dir.run_jj(["commit", "-mfoo"]).success();
work_dir.run_jj(["git", "push", "-c@-"]).success();
let output = work_dir.run_jj(["undo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Undoing a push operation often leads to conflicted bookmarks.
Hint: To avoid this, run `jj redo` now.
Restored to operation: f9fd582ef03c (2001-02-03 08:05:09) commit 3850397cf31988d0657948307ad5bbe873d76a38
[EOF]
");
}
#[test]
fn test_undo_jump_old_undo_stack() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// create a few normal operations
for state in 'A'..='D' {
work_dir.write_file("state", state.to_string());
work_dir.run_jj(["debug", "snapshot"]).success();
}
assert_eq!(work_dir.read_file("state"), "D");
// undo operations D and C, restoring the state of B
work_dir.run_jj(["undo"]).success();
assert_eq!(work_dir.read_file("state"), "C");
work_dir.run_jj(["undo"]).success();
assert_eq!(work_dir.read_file("state"), "B");
// create operations E and F
work_dir.write_file("state", "E");
work_dir.run_jj(["debug", "snapshot"]).success();
work_dir.write_file("state", "F");
work_dir.run_jj(["debug", "snapshot"]).success();
assert_eq!(work_dir.read_file("state"), "F");
// undo operations F, E and B, restoring the state of A while skipping the
// undo-stack of C and D in the op log
work_dir.run_jj(["undo"]).success();
assert_eq!(work_dir.read_file("state"), "E");
work_dir.run_jj(["undo"]).success();
assert_eq!(work_dir.read_file("state"), "B");
work_dir.run_jj(["undo"]).success();
assert_eq!(work_dir.read_file("state"), "A");
}
#[test]
fn test_op_revert_is_ignored() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// create a few normal operations
work_dir.write_file("state", "A");
work_dir.run_jj(["debug", "snapshot"]).success();
work_dir.write_file("state", "B");
work_dir.run_jj(["debug", "snapshot"]).success();
assert_eq!(work_dir.read_file("state"), "B");
// `op revert` works the same way as `undo` initially, but running `undo`
// afterwards will result in a no-op. `undo` does not recognize operations
// created by `op revert` as undo-operations on which an undo-stack can
// be grown.
work_dir.run_jj(["op", "revert"]).success();
assert_eq!(work_dir.read_file("state"), "A");
work_dir.run_jj(["undo"]).success();
assert_eq!(work_dir.read_file("state"), "B");
}
#[test]
fn test_undo_with_rev_arg_falls_back_to_revert() {
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();
let output = work_dir.run_jj(["undo", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: `jj undo <operation>` is deprecated; use `jj op revert <operation>` instead
Reverted operation: 8f47435a3990 (2001-02-03 08:05:07) add workspace 'default'
Rebased 1 descendant commits
[EOF]
");
let output = work_dir.run_jj(["op", "log", "-n1"]);
insta::assert_snapshot!(output, @r"
@ 20c0ef5cef23 test-username@host.example.com 2001-02-03 04:05:09.000 +07:00 - 2001-02-03 04:05:09.000 +07:00
│ revert operation 8f47435a3990362feaf967ca6de2eb0a31c8b883dfcb66fba5c22200d12bbe61e3dc8bc855f1f6879285fcafaf85ac792f9a43bcc36e57d28737d18347d5e752
│ args: jj undo @-
[EOF]
");
}
#[test]
fn test_can_only_redo_undo_operation() {
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(["redo"]), @r"
------- stderr -------
Error: Nothing to redo
[EOF]
[exit status: 1]
");
}
#[test]
fn test_jump_over_old_redo_stack() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// create a few normal operations
for state in 'A'..='D' {
work_dir.write_file("state", state.to_string());
work_dir.run_jj(["debug", "snapshot"]).success();
}
assert_eq!(work_dir.read_file("state"), "D");
insta::assert_snapshot!(work_dir.run_jj(["undo", "--quiet"]), @"");
assert_eq!(work_dir.read_file("state"), "C");
work_dir.run_jj(["undo"]).success();
assert_eq!(work_dir.read_file("state"), "B");
work_dir.run_jj(["undo"]).success();
assert_eq!(work_dir.read_file("state"), "A");
// create two adjacent redo-stacks
insta::assert_snapshot!(work_dir.run_jj(["redo", "--quiet"]), @"");
assert_eq!(work_dir.read_file("state"), "B");
work_dir.run_jj(["redo"]).success();
assert_eq!(work_dir.read_file("state"), "C");
work_dir.run_jj(["undo"]).success();
assert_eq!(work_dir.read_file("state"), "B");
work_dir.run_jj(["redo"]).success();
assert_eq!(work_dir.read_file("state"), "C");
// jump over two adjacent redo-stacks
work_dir.run_jj(["redo"]).success();
assert_eq!(work_dir.read_file("state"), "D");
// nothing left to redo
insta::assert_snapshot!(work_dir.run_jj(["redo"]), @r"
------- stderr -------
Error: Nothing to redo
[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_help_command.rs | cli/tests/test_help_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::TestEnvironment;
#[test]
fn test_help() {
let test_env = TestEnvironment::default();
let help_cmd = test_env.run_jj_in(".", ["help"]).success();
// The help command output should be equal to the long --help flag
let help_flag = test_env.run_jj_in(".", ["--help"]);
// TODO: fix --help to not show COMMAND as required
assert_eq!(
help_cmd.stdout.raw(),
help_flag.stdout.raw().replace("<COMMAND>", "[COMMAND]")
);
assert_eq!(help_cmd.stderr.raw(), help_flag.stderr.raw());
// Help command should work with commands
let help_cmd = test_env.run_jj_in(".", ["help", "log"]).success();
let help_flag = test_env.run_jj_in(".", ["log", "--help"]);
assert_eq!(help_cmd, help_flag);
// Help command should work with subcommands
let help_cmd = test_env
.run_jj_in(".", ["help", "workspace", "root"])
.success();
let help_flag = test_env.run_jj_in(".", ["workspace", "root", "--help"]);
assert_eq!(help_cmd, help_flag);
// Help command should not work recursively
let output = test_env.run_jj_in(".", ["workspace", "help", "root"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: unrecognized subcommand 'help'
Usage: jj workspace [OPTIONS] <COMMAND>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
let output = test_env.run_jj_in(".", ["workspace", "add", "help"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
let output = test_env.run_jj_in(".", ["new", "help", "main"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: There is no jj repo in "."
[EOF]
[exit status: 1]
"#);
// Help command should output the same as --help for nonexistent commands
let help_cmd = test_env.run_jj_in(".", ["help", "nonexistent"]);
let help_flag = test_env.run_jj_in(".", ["nonexistent", "--help"]);
assert_eq!(help_cmd.status.code(), Some(2), "{help_cmd}");
// TODO: fix --help to not show COMMAND as required
assert_eq!(help_cmd.stdout.raw(), help_flag.stdout.raw());
assert_eq!(
help_cmd.stderr.raw(),
help_flag.stderr.raw().replace("<COMMAND>", "[COMMAND]")
);
// Some edge cases
let help_cmd = test_env.run_jj_in(".", ["help", "help"]).success();
let help_flag = test_env.run_jj_in(".", ["help", "--help"]);
assert_eq!(help_cmd, help_flag);
let output = test_env.run_jj_in(".", ["help", "unknown"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: unrecognized subcommand 'unknown'
tip: a similar subcommand exists: 'undo'
Usage: jj [OPTIONS] [COMMAND]
For more information, try '--help'.
[EOF]
[exit status: 2]
");
let output = test_env.run_jj_in(".", ["help", "log", "--", "-r"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Unknown command: log -r
[EOF]
[exit status: 2]
");
}
#[test]
fn test_help_keyword() {
let test_env = TestEnvironment::default();
// It should show help for a certain keyword if the `--keyword` flag is present
let help_cmd = test_env
.run_jj_in(".", ["help", "--keyword", "revsets"])
.success();
// It should be equal to the docs
assert_eq!(help_cmd.stdout.raw(), include_str!("../../docs/revsets.md"));
// It should show help for a certain keyword if the `-k` flag is present
let help_cmd = test_env.run_jj_in(".", ["help", "-k", "revsets"]).success();
// It should be equal to the docs
assert_eq!(help_cmd.stdout.raw(), include_str!("../../docs/revsets.md"));
// It should give hints if a similar keyword is present
let output = test_env.run_jj_in(".", ["help", "-k", "rev"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value 'rev' for '--keyword <KEYWORD>'
[possible values: bookmarks, config, filesets, glossary, revsets, templates, tutorial]
tip: a similar value exists: 'revsets'
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// It should give error with a hint if no similar keyword is found
let output = test_env.run_jj_in(".", ["help", "-k", "<no-similar-keyword>"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value '<no-similar-keyword>' for '--keyword <KEYWORD>'
[possible values: bookmarks, config, filesets, glossary, revsets, templates, tutorial]
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// The keyword flag with no argument should error with a hint
let output = test_env.run_jj_in(".", ["help", "-k"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: a value is required for '--keyword <KEYWORD>' but none was supplied
[possible values: bookmarks, config, filesets, glossary, revsets, templates, tutorial]
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// It shouldn't show help for a certain keyword if the `--keyword` is not
// present
let output = test_env.run_jj_in(".", ["help", "revsets"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: unrecognized subcommand 'revsets'
tip: some similar subcommands exist: 'resolve', 'prev', 'restore', 'rebase', 'revert'
Usage: jj [OPTIONS] [COMMAND]
For more information, try '--help'.
[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_rebase_command.rs | cli/tests/test_rebase_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_rebase_invalid() {
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"]);
// Missing destination
let output = work_dir.run_jj(["rebase"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the following required arguments were not provided:
<--onto <REVSETS>|--insert-after <REVSETS>|--insert-before <REVSETS>>
Usage: jj rebase <--onto <REVSETS>|--insert-after <REVSETS>|--insert-before <REVSETS>>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Both -r and -s
let output = work_dir.run_jj(["rebase", "-r", "a", "-s", "a", "-o", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--revisions <REVSETS>' cannot be used with '--source <REVSETS>'
Usage: jj rebase --revisions <REVSETS> <--onto <REVSETS>|--insert-after <REVSETS>|--insert-before <REVSETS>>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Both -b and -s
let output = work_dir.run_jj(["rebase", "-b", "a", "-s", "a", "-o", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--branch <REVSETS>' cannot be used with '--source <REVSETS>'
Usage: jj rebase --branch <REVSETS> <--onto <REVSETS>|--insert-after <REVSETS>|--insert-before <REVSETS>>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Both -o and --after
let output = work_dir.run_jj(["rebase", "-r", "a", "-o", "b", "--after", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--onto <REVSETS>' cannot be used with '--insert-after <REVSETS>'
Usage: jj rebase --revisions <REVSETS> <--onto <REVSETS>|--insert-after <REVSETS>|--insert-before <REVSETS>>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Both -o and --before
let output = work_dir.run_jj(["rebase", "-r", "a", "-o", "b", "--before", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '--onto <REVSETS>' cannot be used with '--insert-before <REVSETS>'
Usage: jj rebase --revisions <REVSETS> <--onto <REVSETS>|--insert-after <REVSETS>|--insert-before <REVSETS>>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// Rebase onto self with -r
let output = work_dir.run_jj(["rebase", "-r", "a", "-o", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Cannot rebase 7d980be7a1d4 onto itself
[EOF]
[exit status: 1]
");
// Rebase root with -r
let output = work_dir.run_jj(["rebase", "-r", "root()", "-o", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The root commit 000000000000 is immutable
[EOF]
[exit status: 1]
");
// Rebase onto descendant with -s
let output = work_dir.run_jj(["rebase", "-s", "a", "-o", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Cannot rebase 7d980be7a1d4 onto descendant 123b4d91f6e5
[EOF]
[exit status: 1]
");
// Rebase onto itself with -s
let output = work_dir.run_jj(["rebase", "-s", "a", "-o", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Cannot rebase 7d980be7a1d4 onto itself
[EOF]
[exit status: 1]
");
}
#[test]
fn test_rebase_empty_sets() {
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"]);
// TODO: Make all of these say "Nothing changed"?
let output = work_dir.run_jj(["rebase", "-r=none()", "-d=b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["rebase", "-s=none()", "-d=b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Empty revision set
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["rebase", "-b=none()", "-d=b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Empty revision set
[EOF]
[exit status: 1]
");
// Empty because "b..a" is empty
let output = work_dir.run_jj(["rebase", "-b=a", "-d=b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
}
#[test]
fn test_rebase_bookmark() {
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", &["b"]);
create_commit(&work_dir, "d", &["b"]);
create_commit(&work_dir, "e", &["a"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e: a
│ ○ d: b
│ │ ○ c: b
│ ├─╯
│ ○ b: a
├─╯
○ a
◆
[EOF]
");
let setup_opid = work_dir.current_operation_id();
let output = work_dir.run_jj(["rebase", "-b", "c", "-o", "e"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ d: b
│ ○ c: b
├─╯
○ b: e
@ e: a
○ a
◆
[EOF]
");
// Test rebasing multiple bookmarks at once
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["rebase", "-b=e", "-b=d", "-d=b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Skipped rebase of 1 commits that were already in place
Rebased 1 commits to destination
Working copy (@) now at: znkkpsqq bbfb8557 e | e
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"
@ e: b
│ ○ d: b
├─╯
│ ○ c: b
├─╯
○ b: a
○ a
◆
[EOF]
");
// Same test but with more than one revision per argument
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["rebase", "-b=e|d", "-d=b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Skipped rebase of 1 commits that were already in place
Rebased 1 commits to destination
Working copy (@) now at: znkkpsqq 1ffd7890 e | e
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"
@ e: b
│ ○ d: b
├─╯
│ ○ c: b
├─╯
○ b: a
○ a
◆
[EOF]
");
}
#[test]
fn test_rebase_bookmark_with_merge() {
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"
@ e: a d
├─╮
│ ○ d: c
│ ○ c
│ │ ○ b: a
├───╯
○ │ a
├─╯
◆
[EOF]
");
let setup_opid = work_dir.current_operation_id();
let output = work_dir.run_jj(["rebase", "-b", "d", "-o", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: znkkpsqq d5360d09 e | e
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Parent commit (@-) : vruxwmqv 85a741d7 d | d
Added 1 files, modified 0 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e: a d
├─╮
│ ○ d: c
│ ○ c: b
│ ○ b: a
├─╯
○ a
◆
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["rebase", "-o", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: znkkpsqq d3091c0f e | e
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Parent commit (@-) : vruxwmqv 485905a3 d | d
Added 1 files, modified 0 files, removed 0 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e: a d
├─╮
│ ○ d: c
│ ○ c: b
│ ○ b: a
├─╯
○ a
◆
[EOF]
");
}
#[test]
fn test_rebase_single_revision() {
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", &["b", "c"]);
create_commit(&work_dir, "e", &["d"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e: d
○ d: b c
├─╮
│ ○ c: a
○ │ b: a
├─╯
○ a
◆
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// Descendants of the rebased commit "c" should be rebased onto parents. First
// we test with a non-merge commit.
let output = work_dir.run_jj(["rebase", "-r", "c", "-o", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Rebased 2 descendant commits
Working copy (@) now at: znkkpsqq 2baedee4 e | e
Parent commit (@-) : vruxwmqv 45142a83 d | d
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e: d
○ d: b a
├─╮
│ │ ○ c: b
├───╯
○ │ b: a
├─╯
○ a
◆
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Now, let's try moving the merge commit. After, both parents of "d" ("b" and
// "c") should become parents of "e".
let output = work_dir.run_jj(["rebase", "-r", "d", "-o", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Rebased 1 descendant commits
Working copy (@) now at: znkkpsqq b981a2bc e | e
Parent commit (@-) : zsuskuln 123b4d91 b | b
Parent commit (@-) : royxmykx 991a7501 c | c
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ e: b c
├─╮
│ ○ c: a
○ │ b: a
├─╯
│ ○ d: a
├─╯
○ a
◆
[EOF]
");
}
#[test]
fn test_rebase_single_revision_merge_parent() {
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", &["b"]);
create_commit(&work_dir, "d", &["a", "c"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d: a c
├─╮
│ ○ c: b
│ ○ b
○ │ a
├─╯
◆
[EOF]
");
// Descendants of the rebased commit should be rebased onto parents, and if
// the descendant is a merge commit, it shouldn't forget its other parents.
let output = work_dir.run_jj(["rebase", "-r", "c", "-o", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Rebased 1 descendant commits
Working copy (@) now at: vruxwmqv 0bb15a0f d | d
Parent commit (@-) : rlvkpnrz 7d980be7 a | a
Parent commit (@-) : zsuskuln d18ca3e8 b | b
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d: a b
├─╮
│ ○ b
│ │ ○ c: a
├───╯
○ │ a
├─╯
◆
[EOF]
");
}
#[test]
fn test_rebase_multiple_revisions() {
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", &["b"]);
create_commit(&work_dir, "d", &["a"]);
create_commit(&work_dir, "e", &["d"]);
create_commit(&work_dir, "f", &["c", "e"]);
create_commit(&work_dir, "g", &["f"]);
create_commit(&work_dir, "h", &["g"]);
create_commit(&work_dir, "i", &["f"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ i: f
│ ○ h: g
│ ○ g: f
├─╯
○ f: c e
├─╮
│ ○ e: d
│ ○ d: a
○ │ c: b
○ │ b: a
├─╯
○ a
◆
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// Test with two non-related non-merge commits.
let output = work_dir.run_jj(["rebase", "-r", "c", "-r", "e", "-o", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 commits to destination
Rebased 4 descendant commits
Working copy (@) now at: xznxytkn 15078fab i | i
Parent commit (@-) : kmkuslsw d8579ed7 f | f
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ i: f
│ ○ h: g
│ ○ g: f
├─╯
○ f: b d
├─╮
│ ○ d: a
○ │ b: a
├─╯
│ ○ e: a
├─╯
│ ○ c: a
├─╯
○ a
◆
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Test with two related non-merge commits. Since "b" is a parent of "c", when
// rebasing commits "b" and "c", their ancestry relationship should be
// preserved.
let output = work_dir.run_jj(["rebase", "-r", "b", "-r", "c", "-o", "e"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 commits to destination
Rebased 4 descendant commits
Working copy (@) now at: xznxytkn 4dec544d i | i
Parent commit (@-) : kmkuslsw b22816c9 f | f
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ i: f
│ ○ h: g
│ ○ g: f
├─╯
○ f: a e
├─╮
│ │ ○ c: b
│ │ ○ b: e
│ ├─╯
│ ○ e: d
│ ○ d: a
├─╯
○ a
◆
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Test with a subgraph containing a merge commit. Since the merge commit "f"
// was extracted, its descendants which are not part of the subgraph will
// inherit its descendants which are not in the subtree ("c" and "d").
// "f" will retain its parent "c" since "c" is outside the target set, and not
// a descendant of any new children.
let output = work_dir.run_jj(["rebase", "-r", "e::g", "-o", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Rebased 2 descendant commits
Working copy (@) now at: xznxytkn e73a0787 i | i
Parent commit (@-) : royxmykx dffaa0d4 c | c
Parent commit (@-) : vruxwmqv 6354123d d | d
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ i: c d
├─╮
│ │ ○ h: c d
╭─┬─╯
│ ○ d: a
│ │ ○ g: f
│ │ ○ f: c e
╭───┤
│ │ ○ e: a
│ ├─╯
○ │ c: b
○ │ b: a
├─╯
○ a
◆
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Test with commits in a disconnected subgraph. The subgraph has the
// relationship d->e->f->g->h, but only "d", "f" and "h" are in the set of
// rebased commits. "d" should be a new parent of "f", and "f" should be a
// new parent of "h". "f" will retain its parent "c" since "c" is outside the
// target set, and not a descendant of any new children.
let output = work_dir.run_jj(["rebase", "-r", "d", "-r", "f", "-r", "h", "-o", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Rebased 3 descendant commits
Working copy (@) now at: xznxytkn f7c62b49 i | i
Parent commit (@-) : royxmykx dffaa0d4 c | c
Parent commit (@-) : znkkpsqq 1c3676c4 e | e
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ i: c e
├─╮
│ │ ○ g: c e
╭─┬─╯
│ ○ e: a
│ │ ○ h: f
│ │ ○ f: c d
╭───┤
│ │ ○ d: b
○ │ │ c: b
├───╯
○ │ b: a
├─╯
○ a
◆
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Test rebasing a subgraph onto its descendants.
let output = work_dir.run_jj(["rebase", "-r", "d::e", "-o", "i"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 commits to destination
Rebased 4 descendant commits
Working copy (@) now at: xznxytkn b4ece7ad i | i
Parent commit (@-) : kmkuslsw 1a05fe0d f | f
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ e: d
○ d: i
@ i: f
│ ○ h: g
│ ○ g: f
├─╯
○ f: c a
├─╮
○ │ c: b
○ │ b: a
├─╯
○ a
◆
[EOF]
");
}
#[test]
fn test_rebase_revision_onto_descendant() {
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, "base", &[]);
create_commit(&work_dir, "a", &["base"]);
create_commit(&work_dir, "b", &["base"]);
create_commit(&work_dir, "merge", &["b", "a"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ merge: b a
├─╮
│ ○ a: base
○ │ b: base
├─╯
○ base
◆
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// Simpler example
let output = work_dir.run_jj(["rebase", "-r", "base", "-o", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Rebased 3 descendant commits
Working copy (@) now at: vruxwmqv 6a82c6c9 merge | merge
Parent commit (@-) : royxmykx 934eadd8 b | b
Parent commit (@-) : zsuskuln fd4e3113 a | a
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ merge: b a
├─╮
○ │ b
│ │ ○ base: a
│ ├─╯
│ ○ a
├─╯
◆
[EOF]
");
// Now, let's rebase onto the descendant merge
let output = work_dir.run_jj(["op", "restore", &setup_opid]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Restored to operation: cb005d7a588c (2001-02-03 08:05:15) create bookmark merge pointing to commit 08c0951bf69d0362708a5223a78446d664823b50
Working copy (@) now at: vruxwmqv 08c0951b merge | merge
Parent commit (@-) : royxmykx 6a7081ef b | b
Parent commit (@-) : zsuskuln 68fbc443 a | a
Added 1 files, modified 0 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["rebase", "-r", "base", "-o", "merge"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Rebased 3 descendant commits
Working copy (@) now at: vruxwmqv 6091a06e merge | merge
Parent commit (@-) : royxmykx 072bc1fa b | b
Parent commit (@-) : zsuskuln afb318cf a | a
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ base: merge
@ merge: b a
├─╮
│ ○ a
○ │ b
├─╯
◆
[EOF]
");
// TODO(ilyagr): These will be good tests for `jj rebase --insert-after` and
// `--insert-before`, once those are implemented.
}
#[test]
fn test_rebase_multiple_destinations() {
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", &[]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c
│ ○ b
├─╯
│ ○ a
├─╯
◆
[EOF]
");
let output = work_dir.run_jj(["rebase", "-r", "a", "-o", "b", "-o", "c"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ a: b c
├─╮
│ @ c
○ │ b
├─╯
◆
[EOF]
");
let setup_opid2 = work_dir.current_operation_id();
let output = work_dir.run_jj([
"rebase",
"--config=ui.always-allow-large-revsets=false",
"-r",
"a",
"-o",
"b|c",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revset `b|c` resolved to more than one revision
Hint: The revset `b|c` resolved to these revisions:
royxmykx c12952d9 c | c
zsuskuln d18ca3e8 b | b
[EOF]
[exit status: 1]
");
// try with 'all:' and succeed
let output = work_dir.run_jj([
"rebase",
"--config=ui.always-allow-large-revsets=false",
"-r",
"a",
"-o",
"all:b|c",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: In revset expression
--> 1:1
|
1 | all:b|c
| ^-^
|
= Multiple revisions are allowed by default; `all:` is planned for removal
Rebased 1 commits to destination
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ a: c b
├─╮
│ ○ b
@ │ c
├─╯
◆
[EOF]
");
// undo and do it again, but without 'ui.always-allow-large-revsets=false'
work_dir.run_jj(["op", "restore", &setup_opid2]).success();
work_dir.run_jj(["rebase", "-r=a", "-d=b|c"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ a: c b
├─╮
│ ○ b
@ │ c
├─╯
◆
[EOF]
");
let output = work_dir.run_jj(["rebase", "-r", "a", "-o", "b", "-o", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
[EOF]
");
let output = work_dir.run_jj(["rebase", "-r", "a", "-o", "b|c", "-o", "b"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
[EOF]
");
let output = work_dir.run_jj(["rebase", "-r", "a", "-o", "b", "-o", "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_rebase_with_descendants() {
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"]);
create_commit(&work_dir, "d", &["c"]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d: c
○ c: a b
├─╮
│ ○ b
○ │ a
├─╯
◆
[EOF]
");
let setup_opid = work_dir.current_operation_id();
let output = work_dir.run_jj(["rebase", "-s", "b", "-o", "a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: vruxwmqv 7a9837e3 d | d
Parent commit (@-) : royxmykx ee1edcc0 c | c
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d: c
○ c: a b
├─╮
│ ○ b: a
├─╯
○ a
◆
[EOF]
");
// Rebase several subtrees at once.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["rebase", "-s=c", "-s=d", "-d=a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 commits to destination
Working copy (@) now at: vruxwmqv e7720369 d | d
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"
@ d: a
│ ○ c: a
├─╯
○ a
│ ○ b
├─╯
◆
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Reminder of the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ d: c
○ c: a b
├─╮
│ ○ b
○ │ a
├─╯
◆
[EOF]
");
// `d` was a descendant of `b`, and both are moved to be direct descendants of
// `a`. `c` remains a descendant of `b`.
let output = work_dir.run_jj(["rebase", "-s=b", "-s=d", "-d=a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: vruxwmqv 7186427a d | d
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"
@ d: a
│ ○ c: a b
╭─┤
│ ○ b: a
├─╯
○ a
◆
[EOF]
");
// Same test as above, but with multiple commits per argument
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["rebase", "-s=b|d", "-d=a"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: vruxwmqv f6c6224e d | d
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"
@ d: a
│ ○ c: a b
╭─┤
│ ○ b: a
├─╯
○ a
◆
[EOF]
");
}
#[test]
fn test_rebase_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(["bookmark", "create", "-r@", "b-one"])
.success();
work_dir.run_jj(["new", "-r", "@-", "-m", "two"]).success();
let output = work_dir.run_jj(["rebase", "-b", "b-one", "-o", "this"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revision `this` doesn't exist
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["rebase", "-b", "this", "-o", "b-one"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revision `this` doesn't exist
[EOF]
[exit status: 1]
");
}
// This behavior illustrates https://github.com/jj-vcs/jj/issues/2600
#[test]
fn test_rebase_with_child_and_descendant_bug_2600() {
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, "notroot", &[]);
create_commit(&work_dir, "base", &["notroot"]);
create_commit(&work_dir, "a", &["base"]);
create_commit(&work_dir, "b", &["base", "a"]);
create_commit(&work_dir, "c", &["b"]);
let setup_opid = work_dir.current_operation_id();
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c: b
○ b: base a
├─╮
│ ○ a: base
├─╯
○ base: notroot
○ notroot
◆
[EOF]
");
// ===================== rebase -s tests =================
// This should be a no-op
let output = work_dir.run_jj(["rebase", "-s", "base", "-o", "notroot"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Skipped rebase of 4 commits that were already in place
Nothing changed.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c: b
○ b: base a
├─╮
│ ○ a: base
├─╯
○ base: notroot
○ notroot
◆
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// This should be a no-op
let output = work_dir.run_jj(["rebase", "-s", "a", "-o", "base"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Skipped rebase of 3 commits that were already in place
Nothing changed.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c: b
○ b: base a
├─╮
│ ○ a: base
├─╯
○ base: notroot
○ notroot
◆
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["rebase", "-s", "a", "-o", "root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: znkkpsqq b65f55fb c | c
Parent commit (@-) : vruxwmqv c90d30a4 b | b
[EOF]
");
// Commit "a" should be rebased onto the root commit. Commit "b" should have
// "base" and "a" as parents as before.
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c: b
○ b: base a
├─╮
│ ○ a
○ │ base: notroot
○ │ notroot
├─╯
◆
[EOF]
");
// ===================== rebase -b tests =================
// ====== Reminder of the setup =========
work_dir.run_jj(["op", "restore", &setup_opid]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ c: b
○ b: base a
├─╮
│ ○ a: base
├─╯
○ base: notroot
○ notroot
◆
[EOF]
");
// The commits in roots(base..c), i.e. commit "a" should be rebased onto "base",
// which is a no-op
let output = work_dir.run_jj(["rebase", "-b", "c", "-o", "base"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Skipped rebase of 3 commits that were already in place
Nothing changed.
[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_tag_command.rs | cli/tests/test_tag_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_tag_set_delete() {
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();
let output = work_dir.run_jj(["tag", "set", "-r@-", "foo", "bar"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Created 2 tags pointing to qpvuntsm b876c5f4 (empty) commit1
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bbc749308d7f
◆ b876c5f49546 bar foo
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["tag", "set", "foo", "baz"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Refusing to move tag: foo
Hint: Use --allow-move to update existing tags.
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bbc749308d7f
◆ b876c5f49546 bar foo
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["tag", "set", "--allow-move", "foo", "baz"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Created 1 tags pointing to rlvkpnrz bbc74930 (empty) (no description set)
Moved 1 tags to rlvkpnrz bbc74930 (empty) (no description set)
Warning: The working-copy commit in workspace 'default' became immutable, so a new commit has been created on top of it.
Working copy (@) now at: yqosqzyt 13cbd515 (empty) (no description set)
Parent commit (@-) : rlvkpnrz bbc74930 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 13cbd51558a6
◆ bbc749308d7f baz foo
◆ b876c5f49546 bar
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["tag", "delete", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Deleted 1 tags.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 13cbd51558a6
◆ bbc749308d7f baz
◆ b876c5f49546 bar
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["tag", "set", "--allow-move", "-r@-", "baz"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Nothing changed.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 13cbd51558a6
◆ bbc749308d7f baz
◆ b876c5f49546 bar
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["tag", "delete", "b*"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Deleted 2 tags.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 13cbd51558a6
○ bbc749308d7f
○ b876c5f49546
◆ 000000000000
[EOF]
");
}
#[test]
fn test_tag_at_root() {
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(["tag", "set", "-rroot()", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Created 1 tags pointing to zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["git", "export"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
Warning: Failed to export some tags:
foo@git: Ref cannot point to the root commit in Git
[EOF]
");
}
#[test]
fn test_tag_bad_name() {
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();
let output = work_dir.run_jj(["tag", "set", ""]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value '' for '<NAMES>...': Failed to parse tag name: Syntax error
For more information, try '--help'.
Caused by: --> 1:1
|
1 |
| ^---
|
= expected <identifier>, <string_literal>, or <raw_string_literal>
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for how to quote symbols.
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["tag", "set", "''"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value '''' for '<NAMES>...': Failed to parse tag name: Expected non-empty string
For more information, try '--help'.
Caused by: --> 1:1
|
1 | ''
| ^^
|
= Expected non-empty string
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for how to quote symbols.
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["tag", "set", "foo@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value 'foo@' for '<NAMES>...': Failed to parse tag name: Syntax error
For more information, try '--help'.
Caused by: --> 1:4
|
1 | foo@
| ^---
|
= expected <EOI>
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for how to quote symbols.
[EOF]
[exit status: 2]
");
// quoted name works
let output = work_dir.run_jj(["tag", "set", "-r@-", "'foo@'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Created 1 tags pointing to qpvuntsm b876c5f4 (empty) commit1
[EOF]
");
}
#[test]
fn test_tag_unknown() {
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(["tag", "delete", "unknown"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching tags for names: unknown
No tags to delete.
[EOF]
");
let output = work_dir.run_jj(["tag", "delete", "unknown*"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No tags to delete.
[EOF]
");
}
#[test]
fn test_tag_list() {
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()", "-mcommit1"]).success();
work_dir.run_jj(["tag", "set", "-r@", "test_tag"]).success();
work_dir.run_jj(["new", "root()", "-mcommit2"]).success();
work_dir
.run_jj(["tag", "set", "-r@", "test_tag2"])
.success();
work_dir.run_jj(["new", "root()", "-mcommit3"]).success();
work_dir
.run_jj(["tag", "set", "-rtest_tag", "conflicted_tag"])
.success();
work_dir
.run_jj([
"tag",
"set",
"--allow-move",
"-rtest_tag2",
"conflicted_tag",
])
.success();
work_dir
.run_jj([
"tag",
"set",
"--at-op=@-",
"--allow-move",
"-r@",
"conflicted_tag",
])
.success();
insta::assert_snapshot!(work_dir.run_jj(["tag", "list"]), @r"
conflicted_tag (conflicted):
- rlvkpnrz 893e67dc (empty) commit1
+ zsuskuln 76abdd20 (empty) commit2
+ royxmykx 13c4e819 (empty) commit3
test_tag: rlvkpnrz 893e67dc (empty) commit1
test_tag2: zsuskuln 76abdd20 (empty) commit2
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["tag", "list", "--color=always"]), @r"
[38;5;5mconflicted_tag[39m [38;5;1m(conflicted)[39m:
- [1m[38;5;5mrl[0m[38;5;8mvkpnrz[39m [1m[38;5;4m8[0m[38;5;8m93e67dc[39m [38;5;2m(empty)[39m commit1
+ [1m[38;5;5mzs[0m[38;5;8muskuln[39m [1m[38;5;4m7[0m[38;5;8m6abdd20[39m [38;5;2m(empty)[39m commit2
+ [1m[38;5;5mr[0m[38;5;8moyxmykx[39m [1m[38;5;4m1[0m[38;5;8m3c4e819[39m [38;5;2m(empty)[39m commit3
[38;5;5mtest_tag[39m: [1m[38;5;5mrl[0m[38;5;8mvkpnrz[39m [1m[38;5;4m8[0m[38;5;8m93e67dc[39m [38;5;2m(empty)[39m commit1
[38;5;5mtest_tag2[39m: [1m[38;5;5mzs[0m[38;5;8muskuln[39m [1m[38;5;4m7[0m[38;5;8m6abdd20[39m [38;5;2m(empty)[39m commit2
[EOF]
");
// Test pattern matching.
insta::assert_snapshot!(work_dir.run_jj(["tag", "list", "test_tag2"]), @r"
test_tag2: zsuskuln 76abdd20 (empty) commit2
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["tag", "list", "'test_tag?'"]), @r"
test_tag2: zsuskuln 76abdd20 (empty) commit2
[EOF]
");
// Unmatched exact name pattern should be warned. "test_tag2" exists, but
// isn't included in the match.
insta::assert_snapshot!(
work_dir.run_jj(["tag", "list", "test* & ~*2", "unknown ~ test_tag2"]), @r"
test_tag: rlvkpnrz 893e67dc (empty) commit1
[EOF]
------- stderr -------
Warning: No matching tags for names: unknown
[EOF]
");
let template = r#"
concat(
"[" ++ name ++ "]\n",
separate(" ", "present:", present) ++ "\n",
separate(" ", "conflict:", conflict) ++ "\n",
separate(" ", "normal_target:", normal_target.description().first_line()) ++ "\n",
separate(" ", "removed_targets:", removed_targets.map(|c| c.description().first_line())) ++ "\n",
separate(" ", "added_targets:", added_targets.map(|c| c.description().first_line())) ++ "\n",
)
"#;
insta::assert_snapshot!(work_dir.run_jj(["tag", "list", "-T", template]), @r"
[conflicted_tag]
present: true
conflict: true
normal_target: <Error: No Commit available>
removed_targets: commit1
added_targets: commit2 commit3
[test_tag]
present: true
conflict: false
normal_target: commit1
removed_targets:
added_targets: commit1
[test_tag2]
present: true
conflict: false
normal_target: commit2
removed_targets:
added_targets: commit2
[EOF]
");
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"separate(" ", commit_id.short(), tags) ++ "\n""#;
work_dir.run_jj(["log", "-rall()", "-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_import_export.rs | cli/tests/test_git_import_export.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 jj_lib::backend::CommitId;
use testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_resolution_of_git_tracking_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(["bookmark", "create", "-r@", "main"])
.success();
work_dir
.run_jj(["describe", "-r", "main", "-m", "old_message"])
.success();
// Create local-git tracking bookmark
let output = work_dir.run_jj(["git", "export"]);
insta::assert_snapshot!(output, @"");
// Move the local bookmark somewhere else
work_dir
.run_jj(["describe", "-r", "main", "-m", "new_message"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm 384a1421 (empty) new_message
@git (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 a7f9930b (hidden) (empty) old_message
[EOF]
");
// Test that we can address both revisions
let query = |expr| {
let template = r#"commit_id ++ " " ++ description"#;
work_dir.run_jj(["log", "-r", expr, "-T", template, "--no-graph"])
};
insta::assert_snapshot!(query("main"), @r"
384a14213707d776d0517f65cdcf954d07d88c40 new_message
[EOF]
");
insta::assert_snapshot!(query("main@git"), @r"
a7f9930bb6d54ba39e6c254135b9bfe32041fea4 old_message
[EOF]
");
insta::assert_snapshot!(query(r#"remote_bookmarks("main", "git")"#), @r"
a7f9930bb6d54ba39e6c254135b9bfe32041fea4 old_message
[EOF]
");
}
#[test]
fn test_git_export_conflicting_git_refs() {
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(["bookmark", "create", "-r@", "main/sub"])
.success();
let output = work_dir.run_jj(["git", "export"]);
insta::with_settings!({filters => vec![("Failed to set: .*", "Failed to set: ...")]}, {
insta::assert_snapshot!(output, @r#"
------- stderr -------
Warning: Failed to export some bookmarks:
main/sub@git: Failed to set: ...
Hint: Git doesn't allow a branch/tag name that looks like a parent directory of
another (e.g. `foo` and `foo/bar`). Try to rename the bookmarks/tags that failed
to export or their "parent" bookmarks/tags.
[EOF]
"#);
});
}
#[test]
fn test_git_export_undo() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let git_repo = git::open(work_dir.root().join(".jj/repo/store/git"));
work_dir
.run_jj(["bookmark", "create", "-r@", "a"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
a: qpvuntsm e8849ae1 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["git", "export"]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(work_dir.run_jj(["log", "-ra@git"]), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:07 a e8849ae1
│ (empty) (no description set)
~
[EOF]
");
// Exported refs won't be removed by undoing the export, but the git-tracking
// bookmark is. This is the same as remote-tracking bookmarks.
let output = work_dir.run_jj(["undo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Restored to operation: 503f3c779aff (2001-02-03 08:05:08) create bookmark a pointing to commit e8849ae12c709f2321908879bc724fdb2ab8a781
[EOF]
");
insta::assert_debug_snapshot!(get_git_repo_refs(&git_repo), @r#"
[
(
"refs/heads/a",
CommitId(
"e8849ae12c709f2321908879bc724fdb2ab8a781",
),
),
]
"#);
insta::assert_snapshot!(work_dir.run_jj(["log", "-ra@git"]), @r"
------- stderr -------
Error: Revision `a@git` doesn't exist
Hint: Did you mean `a`?
[EOF]
[exit status: 1]
");
// This would re-export bookmark "a" and create git-tracking bookmark.
let output = work_dir.run_jj(["git", "export"]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(work_dir.run_jj(["log", "-ra@git"]), @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:07 a e8849ae1
│ (empty) (no description set)
~
[EOF]
");
}
#[test]
fn test_git_import_undo() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let git_repo = git::open(work_dir.root().join(".jj/repo/store/git"));
// Create bookmark "a" in git repo
let commit_id = work_dir
.run_jj(&["log", "-Tcommit_id", "--no-graph", "-r@"])
.success()
.stdout
.into_raw();
let commit_id = gix::ObjectId::from_hex(commit_id.as_bytes()).unwrap();
git_repo
.reference(
"refs/heads/a",
commit_id,
gix::refs::transaction::PreviousValue::Any,
"",
)
.unwrap();
// Initial state we will return to after `undo`. There are no bookmarks.
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
let base_operation_id = work_dir.current_operation_id();
let output = work_dir.run_jj(["git", "import"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: a@git [new] tracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
a: qpvuntsm e8849ae1 (empty) (no description set)
@git: qpvuntsm e8849ae1 (empty) (no description set)
[EOF]
");
// "git import" can be undone by default.
let output = work_dir.run_jj(["op", "restore", &base_operation_id]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Restored to operation: 8f47435a3990 (2001-02-03 08:05:07) add workspace 'default'
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
// Try "git import" again, which should re-import the bookmark "a".
let output = work_dir.run_jj(["git", "import"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: a@git [new] tracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
a: qpvuntsm e8849ae1 (empty) (no description set)
@git: qpvuntsm e8849ae1 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_git_import_move_export_with_default_undo() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let git_repo = git::open(work_dir.root().join(".jj/repo/store/git"));
// Create bookmark "a" in git repo
let commit_id = work_dir
.run_jj(&["log", "-Tcommit_id", "--no-graph", "-r@"])
.success()
.stdout
.into_raw();
let commit_id = gix::ObjectId::from_hex(commit_id.as_bytes()).unwrap();
git_repo
.reference(
"refs/heads/a",
commit_id,
gix::refs::transaction::PreviousValue::Any,
"",
)
.unwrap();
// Initial state we will try to return to after `op restore`. There are no
// bookmarks.
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
let base_operation_id = work_dir.current_operation_id();
let output = work_dir.run_jj(["git", "import"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: a@git [new] tracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
a: qpvuntsm e8849ae1 (empty) (no description set)
@git: qpvuntsm e8849ae1 (empty) (no description set)
[EOF]
");
// Move bookmark "a" and export to git repo
work_dir.run_jj(["new"]).success();
work_dir
.run_jj(["bookmark", "set", "a", "--to=@"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
a: royxmykx e7d0d5fd (empty) (no description set)
@git (behind by 1 commits): qpvuntsm e8849ae1 (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["git", "export"]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
a: royxmykx e7d0d5fd (empty) (no description set)
@git: royxmykx e7d0d5fd (empty) (no description set)
[EOF]
");
// "git import" can be undone with the default `restore` behavior, as shown in
// the previous test. However, "git export" can't: the bookmarks in the git
// repo stay where they were.
let output = work_dir.run_jj(["op", "restore", &base_operation_id]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Restored to operation: 8f47435a3990 (2001-02-03 08:05:07) add workspace 'default'
Working copy (@) now at: qpvuntsm e8849ae1 (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
insta::assert_debug_snapshot!(get_git_repo_refs(&git_repo), @r#"
[
(
"refs/heads/a",
CommitId(
"e7d0d5fdaf96051d0dacec1e74d9413d64a15822",
),
),
]
"#);
// The last bookmark "a" state is imported from git. No idea what's the most
// intuitive result here.
let output = work_dir.run_jj(["git", "import"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: a@git [new] tracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
a: royxmykx e7d0d5fd (empty) (no description set)
@git: royxmykx e7d0d5fd (empty) (no description set)
[EOF]
");
}
#[test]
fn test_git_import_export_stats_color() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let git_repo = git::open(work_dir.root().join(".jj/repo/store/git"));
work_dir.run_jj(["bookmark", "set", "-r@", "foo"]).success();
work_dir
.run_jj(["bookmark", "set", "-r@", "'un:exportable'"])
.success();
work_dir.run_jj(["new", "--no-edit", "root()"]).success();
let other_commit_id = work_dir
.run_jj(&["log", "-Tcommit_id", "--no-graph", "-rvisible_heads() ~ @"])
.success()
.stdout
.into_raw();
let output = work_dir
.run_jj(["git", "export", "--color=always"])
.success();
insta::assert_snapshot!(output, @r#"
------- stderr -------
[1m[38;5;3mWarning: [39mFailed to export some bookmarks:[0m
[38;5;5m"un:exportable"@git[39m: Failed to set: The ref name or path is not a valid ref name: A reference must be a valid tag name as well: A ref must not contain invalid bytes or ascii control characters: ":"
[1m[38;5;6mHint: [0m[39mGit doesn't allow a branch/tag name that looks like a parent directory of[39m
[39manother (e.g. `foo` and `foo/bar`). Try to rename the bookmarks/tags that failed[39m
[39mto export or their "parent" bookmarks/tags.[39m
[EOF]
"#);
let other_commit_id = gix::ObjectId::from_hex(other_commit_id.as_bytes()).unwrap();
for name in ["refs/heads/foo", "refs/heads/bar", "refs/tags/baz"] {
git_repo
.reference(
name,
other_commit_id,
gix::refs::transaction::PreviousValue::Any,
"",
)
.unwrap();
}
let output = work_dir
.run_jj(["git", "import", "--color=always"])
.success();
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: [38;5;5mbar@git[39m [new] tracked
bookmark: [38;5;5mfoo@git[39m [updated] tracked
tag: [38;5;5mbaz@git[39m [new]
[EOF]
");
}
#[must_use]
fn get_bookmark_output(work_dir: &TestWorkDir) -> CommandOutput {
work_dir.run_jj(["bookmark", "list", "--all-remotes"])
}
fn get_git_repo_refs(git_repo: &gix::Repository) -> Vec<(bstr::BString, CommitId)> {
let mut refs: Vec<_> = git_repo
.references()
.unwrap()
.all()
.unwrap()
.filter_ok(|git_ref| {
matches!(
git_ref.name().category(),
Some(gix::reference::Category::Tag)
| Some(gix::reference::Category::LocalBranch)
| Some(gix::reference::Category::RemoteBranch),
)
})
.filter_map_ok(|mut git_ref| {
let full_name = git_ref.name().as_bstr().to_owned();
let git_commit = git_ref.peel_to_commit().ok()?;
let commit_id = CommitId::from_bytes(git_commit.id().as_bytes());
Some((full_name, commit_id))
})
.try_collect()
.unwrap();
refs.sort();
refs
}
| 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_schema.rs | cli/tests/test_config_schema.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 itertools::Itertools as _;
use crate::common::default_config_from_schema;
#[test]
fn test_config_schema_default_values_are_consistent_with_schema() {
let schema = serde_json::from_str(include_str!("../src/config-schema.json"))
.expect("`config-schema.json` to be valid JSON");
let validator =
jsonschema::validator_for(&schema).expect("`config-schema.json` to be a valid schema");
let schema_defaults = default_config_from_schema();
let evaluation = validator.evaluate(&schema_defaults);
if !evaluation.flag().valid {
panic!(
"Failed to validate the schema defaults:\n{}",
evaluation
.iter_errors()
.map(|err| format!("* {}: {}", err.instance_location, err.error))
.join("\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_git_fetch.rs | cli/tests/test_git_fetch.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::io::Write as _;
use indoc::indoc;
use testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit;
fn add_commit_to_branch(git_repo: &gix::Repository, branch: &str, message: &str) -> gix::ObjectId {
// Get current commit ID of the branch if it exists
let parents = git_repo
.find_reference(&format!("refs/heads/{branch}"))
.ok()
.and_then(|mut r| r.peel_to_commit().ok())
.map(|c| vec![c.id().detach()])
.unwrap_or_default();
git::add_commit(
git_repo,
&format!("refs/heads/{branch}"),
branch, // filename
branch.as_bytes(), // content
message,
&parents,
)
.commit_id
}
/// Creates a remote Git repo containing a bookmark with the same name
fn init_git_remote(test_env: &TestEnvironment, remote: &str) -> gix::Repository {
let git_repo_path = test_env.env_root().join(remote);
let git_repo = git::init(git_repo_path);
add_commit_to_branch(&git_repo, remote, "message");
git_repo
}
/// Add a remote containing a bookmark with the same name
fn add_git_remote(
test_env: &TestEnvironment,
work_dir: &TestWorkDir,
remote: &str,
) -> gix::Repository {
let repo = init_git_remote(test_env, remote);
work_dir
.run_jj(["git", "remote", "add", remote, &format!("../{remote}")])
.success();
repo
}
#[must_use]
fn get_bookmark_output(work_dir: &TestWorkDir) -> CommandOutput {
// --quiet to suppress deleted bookmarks hint
work_dir.run_jj(["bookmark", "list", "--all-remotes", "--quiet"])
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = indoc! {r#"
separate(" ",
commit_id.short(),
'"' ++ description.first_line() ++ '"',
bookmarks,
tags,
) ++ "\n"
"#};
work_dir.run_jj(["log", "-T", template, "-r", "all()"])
}
fn clone_git_remote_into(
test_env: &TestEnvironment,
upstream: &str,
fork: &str,
) -> gix::Repository {
let upstream_path = test_env.env_root().join(upstream);
let fork_path = test_env.env_root().join(fork);
let fork_repo = git::clone(&fork_path, upstream_path.to_str().unwrap(), Some(upstream));
// create local branch mirroring the upstream
let upstream_head = fork_repo
.find_reference(&format!("refs/remotes/{upstream}/{upstream}"))
.unwrap()
.peel_to_id()
.unwrap()
.detach();
fork_repo
.reference(
format!("refs/heads/{upstream}"),
upstream_head,
gix::refs::transaction::PreviousValue::MustNotExist,
"create tracking head",
)
.unwrap();
fork_repo
}
#[test]
fn test_git_fetch_with_default_config() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "origin");
work_dir.run_jj(["git", "fetch"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
origin@origin: qmyrypzk ab8b299e message
[EOF]
");
}
#[test]
fn test_git_fetch_default_remote() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "origin");
work_dir.run_jj(["git", "fetch"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
origin: qmyrypzk ab8b299e message
@origin: qmyrypzk ab8b299e message
[EOF]
");
}
#[test]
fn test_git_fetch_single_remote() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.rem1.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
let output = work_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Hint: Fetching from the only existing remote: rem1
bookmark: rem1@rem1 [new] tracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1: ppspxspk 4acd0343 message
@rem1: ppspxspk 4acd0343 message
[EOF]
");
}
#[test]
fn test_git_fetch_single_remote_all_remotes_flag() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.rem1.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
work_dir.run_jj(["git", "fetch", "--all-remotes"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1: ppspxspk 4acd0343 message
@rem1: ppspxspk 4acd0343 message
[EOF]
");
}
#[test]
fn test_git_fetch_single_remote_from_arg() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.rem1.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
work_dir
.run_jj(["git", "fetch", "--remote", "rem1"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1: ppspxspk 4acd0343 message
@rem1: ppspxspk 4acd0343 message
[EOF]
");
}
#[test]
fn test_git_fetch_single_remote_from_config() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.rem1.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
test_env.add_config(r#"git.fetch = "rem1""#);
work_dir.run_jj(["git", "fetch"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1: ppspxspk 4acd0343 message
@rem1: ppspxspk 4acd0343 message
[EOF]
");
}
#[test]
fn test_git_fetch_multiple_remotes() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.rem1.auto-track-bookmarks = '*'");
test_env.add_config("remotes.rem2.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
add_git_remote(&test_env, &work_dir, "rem2");
work_dir
.run_jj(["git", "fetch", "--remote", "rem1", "--remote", "rem2"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1: ppspxspk 4acd0343 message
@rem1: ppspxspk 4acd0343 message
rem2: pzqqpnpo 44c57802 message
@rem2: pzqqpnpo 44c57802 message
[EOF]
");
}
#[test]
fn test_git_fetch_with_ignored_refspecs() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let source_repo = init_git_remote(&test_env, "origin");
for branch in [
"main", "foo", "foobar", "foobaz", "bar", "sub/yes", "sub/no",
] {
add_commit_to_branch(&source_repo, branch, branch);
}
let work_dir = test_env.work_dir("repo");
std::fs::OpenOptions::new()
.append(true)
.open(work_dir.root().join(".jj/repo/store/git/config"))
.expect("failed to open config file")
.write_all(
br#"
[remote "origin"]
url = ../origin/.git
fetch = +refs/heads/main:refs/remotes/origin/main
fetch = +refs/heads/sub/*:refs/remotes/origin/sub/*
fetch = +refs/heads/foo*:refs/remotes/origin/baz*
fetch = +refs/heads/bar*:refs/tags/bar*
fetch = refs/heads/bar
fetch = ^refs/heads/sub/no
"#,
)
.expect("failed to update config file");
// Should fetch "main" and "sub/yes" by default
let output = work_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Ignored refspec `refs/heads/bar` from `origin`: fetch-only refspecs are not supported
Warning: Ignored refspec `+refs/heads/bar*:refs/tags/bar*` from `origin`: only refs/remotes/ is supported for fetch destinations
Warning: Ignored refspec `+refs/heads/foo*:refs/remotes/origin/baz*` from `origin`: renaming is not supported
bookmark: main@origin [new] untracked
bookmark: sub/yes@origin [new] untracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main@origin: wlltxvop a437242b main
sub/yes@origin: xwxtqxvy 6b64b005 sub/yes
[EOF]
");
// Can fetch ignored "sub/no" explicitly
let output = work_dir.run_jj(["git", "fetch", "--branch=sub/no"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: sub/no@origin [new] untracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main@origin: wlltxvop a437242b main
sub/no@origin: tknwmolt f7d8b914 sub/no
sub/yes@origin: xwxtqxvy 6b64b005 sub/yes
[EOF]
");
// Forget "sub/no" without exporting the change to Git
work_dir
.run_jj(["bookmark", "forget", "--include-remotes", "sub/no"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main@origin: wlltxvop a437242b main
sub/yes@origin: xwxtqxvy 6b64b005 sub/yes
[EOF]
");
// Should not import "sub/no" because it is ignored by default
let output = work_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Ignored refspec `refs/heads/bar` from `origin`: fetch-only refspecs are not supported
Warning: Ignored refspec `+refs/heads/bar*:refs/tags/bar*` from `origin`: only refs/remotes/ is supported for fetch destinations
Warning: Ignored refspec `+refs/heads/foo*:refs/remotes/origin/baz*` from `origin`: renaming is not supported
Nothing changed.
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main@origin: wlltxvop a437242b main
sub/yes@origin: xwxtqxvy 6b64b005 sub/yes
[EOF]
");
}
#[test]
fn test_git_fetch_with_glob() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
add_git_remote(&test_env, &work_dir, "rem2");
let output = work_dir.run_jj(["git", "fetch", "--remote", "*"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: rem1@rem1 [new] untracked
bookmark: rem2@rem2 [new] untracked
[EOF]
");
}
#[test]
fn test_git_fetch_with_glob_and_exact_match() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
add_git_remote(&test_env, &work_dir, "rem2");
add_git_remote(&test_env, &work_dir, "upstream1");
add_git_remote(&test_env, &work_dir, "upstream2");
add_git_remote(&test_env, &work_dir, "origin");
let output = work_dir.run_jj(["git", "fetch", "--remote=rem*", "--remote=origin"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: origin@origin [new] untracked
bookmark: rem1@rem1 [new] untracked
bookmark: rem2@rem2 [new] untracked
[EOF]
");
}
#[test]
fn test_git_fetch_with_glob_from_config() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"git.fetch = "rem*""#);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
add_git_remote(&test_env, &work_dir, "rem2");
add_git_remote(&test_env, &work_dir, "upstream");
let output = work_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: rem1@rem1 [new] untracked
bookmark: rem2@rem2 [new] untracked
[EOF]
");
}
#[test]
fn test_git_fetch_with_glob_with_no_matching_remotes() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "upstream");
let output = work_dir.run_jj(["git", "fetch", "--remote=rem*"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No git remotes to fetch from
[EOF]
[exit status: 1]
");
// No remote should have been fetched as part of the failing transaction
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
}
#[test]
fn test_git_fetch_all_remotes() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.rem1.auto-track-bookmarks = '*'");
test_env.add_config("remotes.rem2.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
add_git_remote(&test_env, &work_dir, "rem2");
// add empty [remote "rem3"] section to .git/config, which should be ignored
work_dir
.run_jj(["git", "remote", "add", "rem3", "../unknown"])
.success();
work_dir
.run_jj(["git", "remote", "remove", "rem3"])
.success();
work_dir.run_jj(["git", "fetch", "--all-remotes"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1: ppspxspk 4acd0343 message
@rem1: ppspxspk 4acd0343 message
rem2: pzqqpnpo 44c57802 message
@rem2: pzqqpnpo 44c57802 message
[EOF]
");
}
#[test]
fn test_git_fetch_multiple_remotes_from_config() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.rem1.auto-track-bookmarks = '*'");
test_env.add_config("remotes.rem2.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
add_git_remote(&test_env, &work_dir, "rem2");
test_env.add_config(r#"git.fetch = ["rem1", "rem2"]"#);
work_dir.run_jj(["git", "fetch"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1: ppspxspk 4acd0343 message
@rem1: ppspxspk 4acd0343 message
rem2: pzqqpnpo 44c57802 message
@rem2: pzqqpnpo 44c57802 message
[EOF]
");
}
#[test]
fn test_git_fetch_no_matching_remote() {
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(["git", "fetch", "--remote", "rem1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching remotes for names: rem1
Error: No git remotes to fetch from
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["git", "fetch", "--remote=rem1", "--remote=rem2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching remotes for names: rem1, rem2
Error: No git remotes to fetch from
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
}
#[test]
fn test_git_fetch_nonexistent_remote() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
let output = work_dir.run_jj(["git", "fetch", "--remote", "rem1", "--remote", "rem2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching remotes for names: rem2
bookmark: rem1@rem1 [new] untracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1@rem1: ppspxspk 4acd0343 message
[EOF]
");
}
#[test]
fn test_git_fetch_nonexistent_remote_from_config() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
test_env.add_config(r#"git.fetch = ["rem1", "rem2"]"#);
let output = work_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching remotes for names: rem2
bookmark: rem1@rem1 [new] untracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1@rem1: ppspxspk 4acd0343 message
[EOF]
");
}
#[test]
fn test_git_fetch_from_remote_named_git() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.bar.auto-track-bookmarks = '*'");
let work_dir = test_env.work_dir("repo");
init_git_remote(&test_env, "git");
git::init(work_dir.root());
git::add_remote(work_dir.root(), "git", "../git");
// Existing remote named 'git' shouldn't block the repo initialization.
work_dir.run_jj(["git", "init", "--git-repo=."]).success();
// Try fetching from the remote named 'git'.
let output = work_dir.run_jj(["git", "fetch", "--remote=git"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remote named 'git' is reserved for local Git repository
Hint: Run `jj git remote rename` to give a different name.
[EOF]
[exit status: 1]
");
// Fetch remote refs by using the git CLI.
git::fetch(work_dir.root(), "git");
// Implicit import shouldn't fail because of the remote ref.
let output = work_dir.run_jj(["bookmark", "list", "--all-remotes"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Failed to import some Git refs:
refs/remotes/git/git
Hint: Git remote named 'git' is reserved for local Git repository.
Use `jj git remote rename` to give a different name.
[EOF]
");
// Explicit import also works. Warnings are printed twice because this is a
// colocated workspace. That should be fine since "jj git import" wouldn't
// be used in colocated environment.
insta::assert_snapshot!(work_dir.run_jj(["git", "import"]), @r"
------- stderr -------
Warning: Failed to import some Git refs:
refs/remotes/git/git
Hint: Git remote named 'git' is reserved for local Git repository.
Use `jj git remote rename` to give a different name.
Warning: Failed to import some Git refs:
refs/remotes/git/git
Hint: Git remote named 'git' is reserved for local Git repository.
Use `jj git remote rename` to give a different name.
Nothing changed.
[EOF]
");
// The remote can be renamed, and the ref can be imported.
work_dir
.run_jj(["git", "remote", "rename", "git", "bar"])
.success();
let output = work_dir.run_jj(["bookmark", "list", "--all-remotes"]);
insta::assert_snapshot!(output, @r"
git: vkponlun 400c483d message
@bar: vkponlun 400c483d message
@git: vkponlun 400c483d message
[EOF]
------- stderr -------
Done importing changes from the underlying Git repo.
[EOF]
");
}
#[test]
fn test_git_fetch_from_remote_with_slashes() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
let work_dir = test_env.work_dir("repo");
init_git_remote(&test_env, "source");
git::init(work_dir.root());
git::add_remote(work_dir.root(), "slash/origin", "../source");
// Existing remote with slash shouldn't block the repo initialization.
work_dir.run_jj(["git", "init", "--git-repo=."]).success();
// Try fetching from the remote named 'git'.
let output = work_dir.run_jj(["git", "fetch", "--remote=slash/origin"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remotes with slashes are incompatible with jj: slash/origin
Hint: Run `jj git remote rename` to give a different name.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_fetch_prune_before_updating_tips() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let git_repo = add_git_remote(&test_env, &work_dir, "origin");
work_dir.run_jj(["git", "fetch"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
origin: qmyrypzk ab8b299e message
@origin: qmyrypzk ab8b299e message
[EOF]
");
// Remove origin bookmark in git repo and create origin/subname
let mut origin_reference = git_repo.find_reference("refs/heads/origin").unwrap();
let commit_id = origin_reference.peel_to_commit().unwrap().id().detach();
origin_reference.delete().unwrap();
git_repo
.reference(
"refs/heads/origin/subname",
commit_id,
gix::refs::transaction::PreviousValue::MustNotExist,
"create new reference",
)
.unwrap();
work_dir.run_jj(["git", "fetch"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
origin/subname: qmyrypzk ab8b299e message
@origin: qmyrypzk ab8b299e message
[EOF]
");
}
#[test]
fn test_git_fetch_conflicting_bookmarks() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.rem1.auto-track-bookmarks = '*'");
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
add_git_remote(&test_env, &work_dir, "rem1");
// Create a rem1 bookmark locally
work_dir.run_jj(["new", "root()"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "rem1"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1: kkmpptxz 2b17ac71 (empty) (no description set)
@rem1 (not created yet)
[EOF]
");
work_dir
.run_jj(["git", "fetch", "--remote", "rem1", "--branch", "*"])
.success();
// This should result in a CONFLICTED bookmark
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1 (conflicted):
+ kkmpptxz 2b17ac71 (empty) (no description set)
+ ppspxspk 4acd0343 message
@rem1 (behind by 1 commits): ppspxspk 4acd0343 message
[EOF]
");
}
#[test]
fn test_git_fetch_conflicting_bookmarks_colocated() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.rem1.auto-track-bookmarks = '*'");
let work_dir = test_env.work_dir("repo");
git::init(work_dir.root());
// create_colocated_repo_and_bookmarks_from_trunk1(&test_env, &repo_path);
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
add_git_remote(&test_env, &work_dir, "rem1");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
// Create a rem1 bookmark locally
work_dir.run_jj(["new", "root()"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "rem1"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1: zsuskuln c2934cfb (empty) (no description set)
@git: zsuskuln c2934cfb (empty) (no description set)
@rem1 (not created yet)
[EOF]
");
work_dir
.run_jj(["git", "fetch", "--remote", "rem1", "--branch", "rem1"])
.success();
// This should result in a CONFLICTED bookmark
// See https://github.com/jj-vcs/jj/pull/1146#discussion_r1112372340 for the bug this tests for.
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
rem1 (conflicted):
+ zsuskuln c2934cfb (empty) (no description set)
+ ppspxspk 4acd0343 message
@git (behind by 1 commits): zsuskuln c2934cfb (empty) (no description set)
@rem1 (behind by 1 commits): ppspxspk 4acd0343 message
[EOF]
");
}
// Helper functions to test obtaining multiple bookmarks at once and changed
// bookmarks
fn create_colocated_repo_and_bookmarks_from_trunk1(work_dir: &TestWorkDir) -> String {
// Create a colocated workspace in `source` to populate it more easily
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
create_commit(work_dir, "trunk1", &[]);
create_commit(work_dir, "a1", &["trunk1"]);
create_commit(work_dir, "a2", &["trunk1"]);
create_commit(work_dir, "b", &["trunk1"]);
format!(
" ===== Source git repo contents =====\n{}",
get_log_output(work_dir)
)
}
fn create_trunk2_and_rebase_bookmarks(work_dir: &TestWorkDir) -> String {
create_commit(work_dir, "trunk2", &["trunk1"]);
for br in ["a1", "a2", "b"] {
work_dir
.run_jj(["rebase", "-b", br, "-o", "trunk2"])
.success();
}
format!(
" ===== Source git repo contents =====\n{}",
get_log_output(work_dir)
)
}
#[test]
fn test_git_fetch_all() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
let source_dir = test_env.work_dir("source");
git::init(source_dir.root());
// Clone an empty repo. The target repo is a normal `jj` repo, *not* colocated
let output = test_env.run_jj_in(".", ["git", "clone", "source", "target"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/target"
Nothing changed.
[EOF]
"#);
let target_dir = test_env.work_dir("target");
let source_log = create_colocated_repo_and_bookmarks_from_trunk1(&source_dir);
insta::assert_snapshot!(source_log, @r#"
===== Source git repo contents =====
@ bc83465a3090 "b" b
│ ○ d4d535f1d579 "a2" a2
├─╯
│ ○ c8303692b8e2 "a1" a1
├─╯
○ 382881770501 "trunk1" trunk1
◆ 000000000000 ""
[EOF]
"#);
// Nothing in our repo before the fetch
insta::assert_snapshot!(get_log_output(&target_dir), @r#"
@ e8849ae12c70 ""
◆ 000000000000 ""
[EOF]
"#);
insta::assert_snapshot!(get_bookmark_output(&target_dir), @"");
let output = target_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: a1@origin [new] tracked
bookmark: a2@origin [new] tracked
bookmark: b@origin [new] tracked
bookmark: trunk1@origin [new] tracked
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&target_dir), @r"
a1: mzvwutvl c8303692 a1
@origin: mzvwutvl c8303692 a1
a2: yqosqzyt d4d535f1 a2
@origin: yqosqzyt d4d535f1 a2
b: yostqsxw bc83465a b
@origin: yostqsxw bc83465a b
trunk1: kkmpptxz 38288177 trunk1
@origin: kkmpptxz 38288177 trunk1
[EOF]
");
insta::assert_snapshot!(get_log_output(&target_dir), @r#"
@ e8849ae12c70 ""
│ ○ bc83465a3090 "b" b
│ │ ○ d4d535f1d579 "a2" a2
│ ├─╯
│ │ ○ c8303692b8e2 "a1" a1
│ ├─╯
│ ○ 382881770501 "trunk1" trunk1
├─╯
◆ 000000000000 ""
[EOF]
"#);
// ==== Change both repos ====
// First, change the target repo:
let source_log = create_trunk2_and_rebase_bookmarks(&source_dir);
insta::assert_snapshot!(source_log, @r#"
===== Source git repo contents =====
○ 6fc6fe17dbee "b" b
│ ○ baad96fead6c "a2" a2
├─╯
│ ○ 798c5e2435e1 "a1" a1
├─╯
@ e80d998ab04b "trunk2" trunk2
○ 382881770501 "trunk1" trunk1
◆ 000000000000 ""
[EOF]
"#);
// Change a bookmark in the source repo as well, so that it becomes conflicted.
target_dir
.run_jj(["describe", "b", "-m=new_descr_for_b_to_create_conflict"])
.success();
// Our repo before and after fetch
insta::assert_snapshot!(get_log_output(&target_dir), @r#"
@ e8849ae12c70 ""
│ ○ 0fbbc495357c "new_descr_for_b_to_create_conflict" b*
│ │ ○ d4d535f1d579 "a2" a2
│ ├─╯
│ │ ○ c8303692b8e2 "a1" a1
│ ├─╯
│ ○ 382881770501 "trunk1" trunk1
├─╯
◆ 000000000000 ""
[EOF]
"#);
insta::assert_snapshot!(get_bookmark_output(&target_dir), @r"
a1: mzvwutvl c8303692 a1
@origin: mzvwutvl c8303692 a1
a2: yqosqzyt d4d535f1 a2
@origin: yqosqzyt d4d535f1 a2
b: yostqsxw 0fbbc495 new_descr_for_b_to_create_conflict
@origin (ahead by 1 commits, behind by 1 commits): yostqsxw/1 bc83465a (hidden) b
trunk1: kkmpptxz 38288177 trunk1
@origin: kkmpptxz 38288177 trunk1
[EOF]
");
let output = target_dir.run_jj(["git", "fetch"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
bookmark: a1@origin [updated] tracked
bookmark: a2@origin [updated] tracked
bookmark: b@origin [updated] tracked
bookmark: trunk2@origin [new] tracked
Abandoned 2 commits that are no longer reachable.
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&target_dir), @r"
a1: mzvwutvl 798c5e24 a1
@origin: mzvwutvl 798c5e24 a1
a2: yqosqzyt baad96fe a2
@origin: yqosqzyt baad96fe a2
b (conflicted):
- yostqsxw/2 bc83465a (hidden) b
+ yostqsxw/1 0fbbc495 (divergent) new_descr_for_b_to_create_conflict
+ yostqsxw/0 6fc6fe17 (divergent) b
@origin (behind by 1 commits): yostqsxw/0 6fc6fe17 (divergent) b
trunk1: kkmpptxz 38288177 trunk1
@origin: kkmpptxz 38288177 trunk1
trunk2: uyznsvlq e80d998a trunk2
@origin: uyznsvlq e80d998a trunk2
[EOF]
");
insta::assert_snapshot!(get_log_output(&target_dir), @r#"
@ e8849ae12c70 ""
│ ○ 6fc6fe17dbee "b" b?? b@origin
│ │ ○ baad96fead6c "a2" a2
│ ├─╯
│ │ ○ 798c5e2435e1 "a1" a1
│ ├─╯
│ ○ e80d998ab04b "trunk2" trunk2
│ │ ○ 0fbbc495357c "new_descr_for_b_to_create_conflict" b??
│ ├─╯
│ ○ 382881770501 "trunk1" trunk1
├─╯
◆ 000000000000 ""
[EOF]
"#);
}
#[test]
fn test_git_fetch_some_of_many_bookmarks() {
let test_env = TestEnvironment::default();
test_env.add_config("remotes.origin.auto-track-bookmarks = '*'");
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
let source_dir = test_env.work_dir("source");
git::init(source_dir.root());
// Clone an empty repo. The target repo is a normal `jj` repo, *not* colocated
let output = test_env.run_jj_in(".", ["git", "clone", "source", "target"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Fetching into new repo in "$TEST_ENV/target"
Nothing changed.
[EOF]
"#);
let target_dir = test_env.work_dir("target");
let source_log = create_colocated_repo_and_bookmarks_from_trunk1(&source_dir);
insta::assert_snapshot!(source_log, @r#"
===== Source git repo contents =====
@ bc83465a3090 "b" b
│ ○ d4d535f1d579 "a2" a2
├─╯
│ ○ c8303692b8e2 "a1" a1
├─╯
○ 382881770501 "trunk1" trunk1
◆ 000000000000 ""
[EOF]
"#);
// Test an error message
let output = target_dir.run_jj(["git", "fetch", "--branch", "'^:a*'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Invalid branch pattern provided. When fetching, branch names and globs may not contain the characters `:`, `^`, `?`, `[`, `]`
[EOF]
[exit status: 1]
");
let output = target_dir.run_jj(["git", "fetch", "--branch", "exact:a*"]);
insta::assert_snapshot!(output, @r"
| 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_gitignores.rs | cli/tests/test_gitignores.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 testutils::git;
use crate::common::TestEnvironment;
#[test]
fn test_gitignores() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
git::init(work_dir.root());
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
// Say in core.excludesFiles that we don't want file1, file2, or file3
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(work_dir.root().join(".git").join("config"))
.unwrap();
// Put the file in "~/my-ignores" so we also test that "~" expands to "$HOME"
file.write_all(b"[core]\nexcludesFile=~/my-ignores\n")
.unwrap();
drop(file);
std::fs::write(
test_env.home_dir().join("my-ignores"),
"file1\nfile2\nfile3",
)
.unwrap();
// Say in .git/info/exclude that we actually do want file2 and file3
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(work_dir.root().join(".git").join("info").join("exclude"))
.unwrap();
file.write_all(b"!file2\n!file3").unwrap();
drop(file);
// Say in .gitignore (in the working copy) that we actually do not want file2
// (again)
work_dir.write_file(".gitignore", "file2");
// Writes some files to the working copy
work_dir.write_file("file0", "contents");
work_dir.write_file("file1", "contents");
work_dir.write_file("file2", "contents");
work_dir.write_file("file3", "contents");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
A .gitignore
A file0
A file3
[EOF]
");
}
#[test]
fn test_gitignores_relative_excludes_file_path() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
test_env
.run_jj_in(".", ["git", "init", "--colocate", "repo"])
.success();
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(work_dir.root().join(".git").join("config"))
.unwrap();
file.write_all(b"[core]\nexcludesFile=../my-ignores\n")
.unwrap();
drop(file);
std::fs::write(test_env.env_root().join("my-ignores"), "ignored\n").unwrap();
work_dir.write_file("ignored", "");
work_dir.write_file("not-ignored", "");
// core.excludesFile should be resolved relative to the workspace root, not
// to the cwd.
let sub_dir = work_dir.create_dir("sub");
let output = sub_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
A ../not-ignored
[EOF]
");
let output = test_env.run_jj_in(".", ["-Rrepo", "diff", "-s"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
A repo/not-ignored
[EOF]
");
}
#[test]
fn test_gitignores_ignored_file_in_target_commit() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("repo");
git::init(work_dir.root());
work_dir
.run_jj(["git", "init", "--git-repo", "."])
.success();
// Create a commit with file "ignored" in it
work_dir.write_file("ignored", "committed contents\n");
work_dir
.run_jj(["bookmark", "create", "-r@", "with-file"])
.success();
let target_commit_id = work_dir
.run_jj(["log", "--no-graph", "-T=commit_id", "-r=@"])
.success()
.stdout
.into_raw();
// Create another commit where we ignore that path
work_dir.run_jj(["new", "root()"]).success();
work_dir.write_file("ignored", "contents in working copy\n");
work_dir.write_file(".gitignore", ".gitignore\nignored\n");
// Update to the commit with the "ignored" file
let output = work_dir.run_jj(["edit", "with-file"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 3cf51c1a with-file | (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 1 files, modified 0 files, removed 0 files
Warning: 1 of those updates were skipped because there were conflicting changes in the working copy.
Hint: Inspect the changes compared to the intended target with `jj diff --from 3cf51c1acf24`.
Discard the conflicting changes with `jj restore --from 3cf51c1acf24`.
[EOF]
");
let output = work_dir.run_jj(["diff", "--git", "--from", &target_commit_id]);
insta::assert_snapshot!(output, @r"
diff --git a/ignored b/ignored
index 8a69467466..4d9be5127b 100644
--- a/ignored
+++ b/ignored
@@ -1,1 +1,1 @@
-committed contents
+contents in 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_git_private_commits.rs | cli/tests/test_git_private_commits.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::TestEnvironment;
use crate::common::TestWorkDir;
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 = origin_dir
.root()
.join(".jj")
.join("repo")
.join("store")
.join("git");
origin_dir.run_jj(["describe", "-m=public 1"]).success();
origin_dir.run_jj(["new", "-m=public 2"]).success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.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();
}
fn set_up_remote_at_main(test_env: &TestEnvironment, work_dir: &TestWorkDir, remote_name: &str) {
test_env
.run_jj_in(".", ["git", "init", remote_name])
.success();
let other_path = test_env.env_root().join(remote_name);
let other_git_repo_path = other_path
.join(".jj")
.join("repo")
.join("store")
.join("git");
work_dir
.run_jj([
"git",
"remote",
"add",
remote_name,
other_git_repo_path.to_str().unwrap(),
])
.success();
work_dir
.run_jj([
"git",
"push",
"--allow-new",
"--remote",
remote_name,
"-b=main",
])
.success();
}
#[test]
fn test_git_private_commits_block_pushing() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
work_dir.run_jj(["new", "main", "-m=private 1"]).success();
work_dir
.run_jj(["bookmark", "set", "main", "-r@"])
.success();
// Will not push when a pushed commit is contained in git.private-commits
test_env.add_config(r#"git.private-commits = "description('private*')""#);
let output = work_dir.run_jj(["git", "push", "--all"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Won't push commit 7f665ca27d4e since it is private
Hint: Rejected commit: yqosqzyt 7f665ca2 main* | (empty) private 1
Hint: Configured git.private-commits: 'description('private*')'
[EOF]
[exit status: 1]
");
// May push when the commit is removed from git.private-commits
test_env.add_config(r#"git.private-commits = "none()""#);
let output = work_dir.run_jj(["git", "push", "--all"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move forward bookmark main from 95cc152cd086 to 7f665ca27d4e
Warning: The working-copy commit in workspace 'default' became immutable, so a new commit has been created on top of it.
Working copy (@) now at: znkkpsqq 8227d51b (empty) (no description set)
Parent commit (@-) : yqosqzyt 7f665ca2 main | (empty) private 1
[EOF]
");
}
#[test]
fn test_git_private_commits_can_be_overridden() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
work_dir.run_jj(["new", "main", "-m=private 1"]).success();
work_dir
.run_jj(["bookmark", "set", "main", "-r@"])
.success();
// Will not push when a pushed commit is contained in git.private-commits
test_env.add_config(r#"git.private-commits = "description('private*')""#);
let output = work_dir.run_jj(["git", "push", "--all"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Won't push commit 7f665ca27d4e since it is private
Hint: Rejected commit: yqosqzyt 7f665ca2 main* | (empty) private 1
Hint: Configured git.private-commits: 'description('private*')'
[EOF]
[exit status: 1]
");
// May push when the commit is removed from git.private-commits
let output = work_dir.run_jj(["git", "push", "--all", "--allow-private"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move forward bookmark main from 95cc152cd086 to 7f665ca27d4e
Warning: The working-copy commit in workspace 'default' became immutable, so a new commit has been created on top of it.
Working copy (@) now at: znkkpsqq 8227d51b (empty) (no description set)
Parent commit (@-) : yqosqzyt 7f665ca2 main | (empty) private 1
[EOF]
");
}
#[test]
fn test_git_private_commits_are_not_checked_if_immutable() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
work_dir.run_jj(["new", "main", "-m=private 1"]).success();
work_dir
.run_jj(["bookmark", "set", "main", "-r@"])
.success();
test_env.add_config(r#"git.private-commits = "description('private*')""#);
test_env.add_config(r#"revset-aliases."immutable_heads()" = "all()""#);
let output = work_dir.run_jj(["git", "push", "--all"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move forward bookmark main from 95cc152cd086 to 7f665ca27d4e
Warning: The working-copy commit in workspace 'default' became immutable, so a new commit has been created on top of it.
Working copy (@) now at: yostqsxw 17947f20 (empty) (no description set)
Parent commit (@-) : yqosqzyt 7f665ca2 main | (empty) private 1
[EOF]
");
}
#[test]
fn test_git_private_commits_not_directly_in_line_block_pushing() {
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");
// New private commit descended from root()
work_dir.run_jj(["new", "root()", "-m=private 1"]).success();
work_dir
.run_jj(["new", "main", "@", "-m=public 3"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "bookmark1"])
.success();
test_env.add_config(r#"git.private-commits = "description('private*')""#);
let output = work_dir.run_jj(["git", "push", "-b=bookmark1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Won't push commit 613114f44bdd since it is private
Hint: Rejected commit: yqosqzyt 613114f4 (empty) private 1
Hint: Configured git.private-commits: 'description('private*')'
[EOF]
[exit status: 1]
");
}
#[test]
fn test_git_private_commits_descending_from_commits_pushed_do_not_block_pushing() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
work_dir.run_jj(["new", "main", "-m=public 3"]).success();
work_dir
.run_jj(["bookmark", "move", "main", "--to=@"])
.success();
work_dir.run_jj(["new", "-m=private 1"]).success();
test_env.add_config(r#"git.private-commits = "description('private*')""#);
let output = work_dir.run_jj(["git", "push", "-b=main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move forward bookmark main from 95cc152cd086 to f0291dea729d
[EOF]
");
}
#[test]
fn test_git_private_commits_already_on_the_remote_do_not_block_push() {
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");
// Start a bookmark before a "private" commit lands in main
work_dir
.run_jj(["bookmark", "create", "bookmark1", "-r=main"])
.success();
// Push a commit that would become a private_root if it weren't already on
// the remote
work_dir.run_jj(["new", "main", "-m=private 1"]).success();
work_dir.run_jj(["new", "-m=public 3"]).success();
work_dir
.run_jj(["bookmark", "set", "main", "-r@"])
.success();
let output = work_dir.run_jj(["git", "push", "-b=main", "-b=bookmark1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Add bookmark bookmark1 to 95cc152cd086
Move forward bookmark main from 95cc152cd086 to 03bc2bf271e0
Warning: The working-copy commit in workspace 'default' became immutable, so a new commit has been created on top of it.
Working copy (@) now at: kpqxywon 5308110d (empty) (no description set)
Parent commit (@-) : yostqsxw 03bc2bf2 main | (empty) public 3
[EOF]
");
test_env.add_config(r#"git.private-commits = "subject('private*')""#);
// Since "private 1" is already on the remote, pushing it should be allowed
work_dir
.run_jj(["bookmark", "set", "bookmark1", "-r=main"])
.success();
let output = work_dir.run_jj(["git", "push", "--all"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move forward bookmark bookmark1 from 95cc152cd086 to 03bc2bf271e0
[EOF]
");
// Ensure that the already-pushed commit doesn't block a new bookmark from
// being pushed
work_dir
.run_jj(["new", "subject('private 1')", "-m=public 4"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "bookmark2"])
.success();
let output = work_dir.run_jj(["git", "push", "-b=bookmark2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Add bookmark bookmark2 to 987ee765174d
[EOF]
");
}
#[test]
fn test_git_private_commits_are_evaluated_separately_for_each_remote() {
let test_env = TestEnvironment::default();
set_up(&test_env);
let work_dir = test_env.work_dir("local");
set_up_remote_at_main(&test_env, &work_dir, "other");
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
// Push a commit that would become a private_root if it weren't already on
// the remote
work_dir.run_jj(["new", "main", "-m=private 1"]).success();
work_dir.run_jj(["new", "-m=public 3"]).success();
work_dir
.run_jj(["bookmark", "set", "main", "-r@"])
.success();
let output = work_dir.run_jj(["git", "push", "-b=main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Move forward bookmark main from 95cc152cd086 to 7eb69d0eaf71
[EOF]
");
test_env.add_config(r#"git.private-commits = "description('private*')""#);
// But pushing to a repo that doesn't have the private commit yet is still
// blocked
let output = work_dir.run_jj(["git", "push", "--remote=other", "-b=main"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Won't push commit 469f044473ed since it is private
Hint: Rejected commit: znkkpsqq 469f0444 (empty) private 1
Hint: Configured git.private-commits: 'description('private*')'
[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_alias.rs | cli/tests/test_alias.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_alias_basic() {
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#"aliases.bk = ["log", "-r", "@", "-T", "bookmarks"]"#);
work_dir
.run_jj(["bookmark", "create", "my-bookmark", "-r", "@"])
.success();
let output = work_dir.run_jj(["bk"]);
insta::assert_snapshot!(output, @r"
@ my-bookmark
│
~
[EOF]
");
}
#[test]
fn test_alias_bad_name() {
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(["foo."]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: unrecognized subcommand 'foo.'
Usage: jj [OPTIONS] <COMMAND>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_alias_calls_empty_command() {
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#"
aliases.empty = []
aliases.empty_command_with_opts = ["--no-pager"]
"#,
);
let output = work_dir.run_jj(["empty"]);
insta::assert_snapshot!(
output.normalize_stderr_with(|s| s.split_inclusive('\n').take(3).collect()), @r"
------- stderr -------
Jujutsu (An experimental VCS)
Usage: jj [OPTIONS] <COMMAND>
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["empty", "--no-pager"]);
insta::assert_snapshot!(
output.normalize_stderr_with(|s| s.split_inclusive('\n').take(1).collect()), @r"
------- stderr -------
error: 'jj' requires a subcommand but one was not provided
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["empty_command_with_opts"]);
insta::assert_snapshot!(
output.normalize_stderr_with(|s| s.split_inclusive('\n').take(1).collect()), @r"
------- stderr -------
error: 'jj' requires a subcommand but one was not provided
[EOF]
[exit status: 2]
");
}
#[test]
fn test_alias_calls_unknown_command() {
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#"aliases.foo = ["nonexistent"]"#);
let output = work_dir.run_jj(["foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: unrecognized subcommand 'nonexistent'
tip: a similar subcommand exists: 'next'
Usage: jj [OPTIONS] <COMMAND>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_alias_calls_command_with_invalid_option() {
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#"aliases.foo = ["log", "--nonexistent"]"#);
let output = work_dir.run_jj(["foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: unexpected argument '--nonexistent' found
tip: to pass '--nonexistent' as a value, use '-- --nonexistent'
Usage: jj log [OPTIONS] [FILESETS]...
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_alias_calls_help() {
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#"aliases.h = ["--help"]"#);
let output = work_dir.run_jj(&["h"]);
insta::assert_snapshot!(
output.normalize_stdout_with(|s| s.split_inclusive('\n').take(7).collect()), @r"
Jujutsu (An experimental VCS)
To get started, see the tutorial [`jj help -k tutorial`].
[`jj help -k tutorial`]: https://docs.jj-vcs.dev/latest/tutorial/
Usage: jj [OPTIONS] <COMMAND>
[EOF]
");
}
#[test]
fn test_alias_cannot_override_builtin() {
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#"aliases.log = ["rebase"]"#);
// Alias should give a warning
let output = work_dir.run_jj(["log", "-r", "root()"]);
insta::assert_snapshot!(output, @r"
◆ zzzzzzzz root() 00000000
[EOF]
------- stderr -------
Warning: Cannot define an alias that overrides the built-in command 'log'
[EOF]
");
}
#[test]
fn test_alias_recursive() {
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#"[aliases]
foo = ["foo"]
bar = ["baz"]
baz = ["bar"]
"#,
);
// Alias should not cause infinite recursion or hang
let output = work_dir.run_jj(["foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Recursive alias definition involving `foo`
[EOF]
[exit status: 1]
");
// Also test with mutual recursion
let output = work_dir.run_jj(["bar"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Recursive alias definition involving `bar`
[EOF]
[exit status: 1]
");
}
#[test]
fn test_alias_global_args_before_and_after() {
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#"aliases.l = ["log", "-T", "commit_id", "-r", "all()"]"#);
// Test the setup
let output = work_dir.run_jj(["l"]);
insta::assert_snapshot!(output, @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
◆ 0000000000000000000000000000000000000000
[EOF]
");
// Can pass global args before
let output = work_dir.run_jj(["l", "--at-op", "@-"]);
insta::assert_snapshot!(output, @r"
◆ 0000000000000000000000000000000000000000
[EOF]
");
// Can pass global args after
let output = work_dir.run_jj(["--at-op", "@-", "l"]);
insta::assert_snapshot!(output, @r"
◆ 0000000000000000000000000000000000000000
[EOF]
");
// Test passing global args both before and after
let output = work_dir.run_jj(["--at-op", "abc123", "l", "--at-op", "@-"]);
insta::assert_snapshot!(output, @r"
◆ 0000000000000000000000000000000000000000
[EOF]
");
let output = work_dir.run_jj(["-R", "../nonexistent", "l", "-R", "."]);
insta::assert_snapshot!(output, @r"
@ e8849ae12c709f2321908879bc724fdb2ab8a781
◆ 0000000000000000000000000000000000000000
[EOF]
");
}
#[test]
fn test_alias_global_args_in_definition() {
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#"aliases.l = ["log", "-T", "commit_id", "--at-op", "@-", "-r", "all()", "--color=always"]"#,
);
// The global argument in the alias is respected
let output = work_dir.run_jj(["l"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;14m◆[0m [38;5;4m0000000000000000000000000000000000000000[39m
[EOF]
");
}
#[test]
fn test_alias_invalid_definition() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"[aliases]
non-list = 5
non-string-list = [0]
"#,
);
let output = test_env.run_jj_in(".", ["non-list"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
------- stderr -------
Config error: Invalid type or value for aliases.non-list
Caused by: invalid type: integer `5`, expected a sequence
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 = test_env.run_jj_in(".", ["non-string-list"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Invalid type or value for aliases.non-string-list
Caused by: invalid type: integer `0`, expected a string
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_alias_in_repo_config() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo1"]).success();
let work_dir1 = test_env.work_dir("repo1");
work_dir1.create_dir("sub");
test_env.run_jj_in(".", ["git", "init", "repo2"]).success();
let work_dir2 = test_env.work_dir("repo2");
work_dir2.create_dir("sub");
test_env.add_config(r#"aliases.l = ['log', '-r@', '--no-graph', '-T"user alias\n"']"#);
work_dir1.write_file(
".jj/repo/config.toml",
r#"aliases.l = ['log', '-r@', '--no-graph', '-T"repo1 alias\n"']"#,
);
// In repo1 sub directory, aliases can be loaded from the repo1 config.
let output = test_env.run_jj_in(work_dir1.root().join("sub"), ["l"]);
insta::assert_snapshot!(output, @r"
repo1 alias
[EOF]
");
// In repo2 directory, no repo-local aliases exist.
let output = work_dir2.run_jj(["l"]);
insta::assert_snapshot!(output, @r"
user alias
[EOF]
");
// Aliases can't be loaded from the -R path due to chicken and egg problem.
let output = work_dir2.run_jj(["l", "-R", work_dir1.root().to_str().unwrap()]);
insta::assert_snapshot!(output, @r"
user alias
[EOF]
------- stderr -------
Warning: Command aliases cannot be loaded from -R/--repository path or --config/--config-file arguments.
[EOF]
");
// Aliases are loaded from the cwd-relative workspace even with -R.
let output = work_dir1.run_jj(["l", "-R", work_dir2.root().to_str().unwrap()]);
insta::assert_snapshot!(output, @r"
repo1 alias
[EOF]
------- stderr -------
Warning: Command aliases cannot be loaded from -R/--repository path or --config/--config-file arguments.
[EOF]
");
// No warning if the expanded command is identical.
let output = work_dir1.run_jj(["file", "list", "-R", work_dir2.root().to_str().unwrap()]);
insta::assert_snapshot!(output, @"");
// Config loaded from the cwd-relative workspace shouldn't persist. It's
// used only for command arguments expansion.
let output = work_dir1.run_jj([
"config",
"list",
"aliases",
"-R",
work_dir2.root().to_str().unwrap(),
]);
insta::assert_snapshot!(output, @r#"
aliases.l = ['log', '-r@', '--no-graph', '-T"user alias\n"']
[EOF]
"#);
}
#[test]
fn test_alias_in_config_arg() {
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#"aliases.l = ['log', '-r@', '--no-graph', '-T"user alias\n"']"#);
let output = work_dir.run_jj(["l"]);
insta::assert_snapshot!(output, @r"
user alias
[EOF]
");
let alias_arg = r#"--config=aliases.l=['log', '-r@', '--no-graph', '-T"arg alias\n"']"#;
let output = work_dir.run_jj([alias_arg, "l"]);
insta::assert_snapshot!(output, @r"
user alias
[EOF]
------- stderr -------
Warning: Command aliases cannot be loaded from -R/--repository path or --config/--config-file arguments.
[EOF]
");
// should print warning about aliases even if cli parsing fails
let alias_arg = r#"--config=aliases.this-command-not-exist=['log', '-r@', '--no-graph', '-T"arg alias\n"']"#;
let output = work_dir.run_jj([alias_arg, "this-command-not-exist"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Command aliases cannot be loaded from -R/--repository path or --config/--config-file arguments.
error: unrecognized subcommand 'this-command-not-exist'
Usage: jj [OPTIONS] <COMMAND>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_aliases_overriding_friendly_errors() {
let test_env = TestEnvironment::default();
// Test with color
let output = test_env.run_jj_in(".", ["--color=always", "init", "repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
[1m[31merror:[0m unrecognized subcommand '[33minit[0m'
For more information, try '[1m[32m--help[0m'.
[1m[38;5;6mHint: [0m[39mYou probably want `jj git init`. See also `jj help git`.[39m
[1m[38;5;6mHint: [0m[39mYou can configure `aliases.init = ["git", "init"]` if you want `jj init` to work and always use the Git backend.[39m
[EOF]
[exit status: 2]
"#);
let output = test_env.run_jj_in(".", ["init", "repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
error: unrecognized subcommand 'init'
For more information, try '--help'.
Hint: You probably want `jj git init`. See also `jj help git`.
Hint: You can configure `aliases.init = ["git", "init"]` if you want `jj init` to work and always use the Git backend.
[EOF]
[exit status: 2]
"#);
let output = test_env.run_jj_in(".", ["clone", "https://example.org/repo"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
error: unrecognized subcommand 'clone'
For more information, try '--help'.
Hint: You probably want `jj git clone`. See also `jj help git`.
Hint: You can configure `aliases.clone = ["git", "clone"]` if you want `jj clone` to work and always use the Git backend.
[EOF]
[exit status: 2]
"#);
let output = test_env.run_jj_in(".", ["init", "--help"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
error: unrecognized subcommand 'init'
For more information, try '--help'.
Hint: You probably want `jj git init`. See also `jj help git`.
Hint: You can configure `aliases.init = ["git", "init"]` if you want `jj init` to work and always use the Git backend.
[EOF]
[exit status: 2]
"#);
// Test that `init` can be overridden as an alias. (We use `jj config get`
// as a command with a predictable output)
test_env.add_config(r#"aliases.init=["config", "get", "user.name"]"#);
let output = test_env.run_jj_in(".", ["init"]);
insta::assert_snapshot!(output, @r"
Test User
[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_working_copy.rs | cli/tests/test_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 indoc::indoc;
use regex::Regex;
use crate::common::TestEnvironment;
#[test]
fn test_snapshot_large_file() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// test a small file using raw-integer-literal syntax, which is interpreted
// in bytes
test_env.add_config(r#"snapshot.max-new-file-size = 10"#);
work_dir.write_file("empty", "");
work_dir.write_file("large", "a lot of text");
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
empty
[EOF]
------- stderr -------
Warning: Refused to snapshot some files:
large: 13.0B (13 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 13`
This will increase the maximum file size allowed for new files, in this repository only.
- Run `jj --config snapshot.max-new-file-size=13 st`
This will increase the maximum file size allowed for new files, for this command only.
[EOF]
");
// test with a larger file using 'KB' human-readable syntax
test_env.add_config(r#"snapshot.max-new-file-size = "10KB""#);
let big_string = vec![0; 1024 * 11];
work_dir.write_file("large", &big_string);
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
empty
[EOF]
------- stderr -------
Warning: Refused to snapshot some files:
large: 11.0KiB (11264 bytes); the maximum size allowed is 10.0KiB (10240 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 11264`
This will increase the maximum file size allowed for new files, in this repository only.
- Run `jj --config snapshot.max-new-file-size=11264 st`
This will increase the maximum file size allowed for new files, for this command only.
[EOF]
");
// test with file track for hint formatting, both files should appear in
// warnings even though they were snapshotted separately
work_dir.write_file("large2", big_string);
let output = work_dir.run_jj([
"file",
"--config=snapshot.auto-track='large'",
"track",
"large2",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Refused to snapshot some files:
large: 11.0KiB (11264 bytes); the maximum size allowed is 10.0KiB (10240 bytes)
large2: 11.0KiB (11264 bytes); the maximum size allowed is 10.0KiB (10240 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 11264`
This will increase the maximum file size allowed for new files, in this repository only.
- Run `jj --config snapshot.max-new-file-size=11264 file track large large2`
This will increase the maximum file size allowed for new files, for this command only.
- Run `jj file track --include-ignored large large2`
This will track the files even though they exceed the size limit.
[EOF]
");
// test invalid configuration
let output = work_dir.run_jj(["file", "list", "--config=snapshot.max-new-file-size=[]"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Config error: Invalid type or value for snapshot.max-new-file-size
Caused by: Expected a positive integer or a string in '<number><unit>' form
For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
[EOF]
[exit status: 1]
");
// No error if we disable auto-tracking of the path
let output = work_dir.run_jj(["file", "list", "--config=snapshot.auto-track='none()'"]);
insta::assert_snapshot!(output, @r"
empty
[EOF]
");
// max-new-file-size=0 means no limit
let output = work_dir.run_jj(["file", "list", "--config=snapshot.max-new-file-size=0"]);
insta::assert_snapshot!(output, @r"
empty
large
large2
[EOF]
");
}
#[test]
fn test_snapshot_large_file_restore() {
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("snapshot.max-new-file-size = 10");
work_dir.run_jj(["describe", "-mcommitted"]).success();
work_dir.write_file("file", "small");
// Write a large file in the working copy, restore it from a commit. The
// working-copy content shouldn't be overwritten.
work_dir.run_jj(["new", "root()"]).success();
work_dir.write_file("file", "a lot of text");
let output = work_dir.run_jj(["restore", "--from=subject(committed)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Refused to snapshot some files:
file: 13.0B (13 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 13`
This will increase the maximum file size allowed for new files, in this repository only.
- Run `jj --config snapshot.max-new-file-size=13 st`
This will increase the maximum file size allowed for new files, for this command only.
Working copy (@) now at: kkmpptxz 119f5156 (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 1 files, modified 0 files, removed 0 files
Warning: 1 of those updates were skipped because there were conflicting changes in the working copy.
Hint: Inspect the changes compared to the intended target with `jj diff --from 119f5156d330`.
Discard the conflicting changes with `jj restore --from 119f5156d330`.
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @"a lot of text");
// However, the next command will snapshot the large file because it is now
// tracked. TODO: Should we remember the untracked state?
let output = work_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
A file
Working copy (@) : kkmpptxz 09eba65e (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_materialize_and_snapshot_different_conflict_markers() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Configure to use Git-style conflict markers
test_env.add_config(r#"ui.conflict-marker-style = "git""#);
// Create a conflict in the working copy
work_dir.write_file(
"file",
indoc! {"
line 1
line 2
line 3
"},
);
work_dir.run_jj(["commit", "-m", "base"]).success();
work_dir.write_file(
"file",
indoc! {"
line 1
line 2 - a
line 3
"},
);
work_dir.run_jj(["commit", "-m", "side-a"]).success();
work_dir
.run_jj(["new", "subject(base)", "-m", "side-b"])
.success();
work_dir.write_file(
"file",
indoc! {"
line 1
line 2 - b
line 3 - b
"},
);
work_dir
.run_jj(["new", "subject(side-a)", "subject(side-b)"])
.success();
// File should have Git-style conflict markers
insta::assert_snapshot!(work_dir.read_file("file"), @r#"
line 1
<<<<<<< rlvkpnrz df1cdd77 "side-a"
line 2 - a
line 3
||||||| qpvuntsm 2205b3ac "base"
line 2
line 3
=======
line 2 - b
line 3 - b
>>>>>>> zsuskuln 68dcce1b "side-b"
"#);
// Configure to use JJ-style "snapshot" conflict markers
test_env.add_config(r#"ui.conflict-marker-style = "snapshot""#);
// Update the conflict, still using Git-style conflict markers
work_dir.write_file(
"file",
indoc! {"
line 1
<<<<<<<
line 2 - a
line 3 - a
|||||||
line 2
line 3
=======
line 2 - b
line 3 - b
>>>>>>>
"},
);
// Git-style markers should be parsed, then rendered with new config
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @r#"
diff --git a/file b/file
--- a/file
+++ b/file
@@ -2,7 +2,7 @@
<<<<<<< conflict 1 of 1
+++++++ rlvkpnrz df1cdd77 "side-a"
line 2 - a
-line 3
+line 3 - a
------- qpvuntsm 2205b3ac "base"
line 2
line 3
[EOF]
"#);
}
#[test]
fn test_snapshot_invalid_ignore_pattern() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Test invalid pattern in .gitignore
work_dir.write_file(".gitignore", " []\n");
insta::assert_snapshot!(work_dir.run_jj(["st"]), @r"
Working copy changes:
A .gitignore
Working copy (@) : qpvuntsm c9cf4826 (no description set)
Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
// Test invalid UTF-8 in .gitignore
work_dir.write_file(".gitignore", b"\xff\n");
insta::assert_snapshot!(work_dir.run_jj(["st"]), @r"
------- stderr -------
Internal error: Failed to snapshot the working copy
Caused by:
1: Invalid UTF-8 for ignore pattern in $TEST_ENV/repo/.gitignore on line #1: �
2: invalid utf-8 sequence of 1 bytes from index 0
[EOF]
[exit status: 255]
");
}
#[test]
fn test_conflict_marker_length_stored_in_working_copy() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Create a conflict in the working copy with long markers on one side
work_dir.write_file(
"file",
indoc! {"
line 1
line 2
line 3
"},
);
work_dir.run_jj(["commit", "-m", "base"]).success();
work_dir.write_file(
"file",
indoc! {"
line 1
line 2 - left
line 3 - left
"},
);
work_dir.run_jj(["commit", "-m", "side-a"]).success();
work_dir
.run_jj(["new", "subject(base)", "-m", "side-b"])
.success();
work_dir.write_file(
"file",
indoc! {"
line 1
======= fake marker
line 2 - right
======= fake marker
line 3
"},
);
work_dir
.run_jj(["new", "subject(side-a)", "subject(side-b)"])
.success();
// File should be materialized with long conflict markers
insta::assert_snapshot!(work_dir.read_file("file"), @r#"
line 1
<<<<<<<<<<< conflict 1 of 1
%%%%%%%%%%% diff from: qpvuntsm 2205b3ac "base"
\\\\\\\\\\\ to: rlvkpnrz ccf9527c "side-a"
-line 2
-line 3
+line 2 - left
+line 3 - left
+++++++++++ zsuskuln d7acaf48 "side-b"
======= fake marker
line 2 - right
======= fake marker
line 3
>>>>>>>>>>> conflict 1 of 1 ends
"#);
// The timestamps in the `jj debug local-working-copy` output change, so we want
// to remove them before asserting the snapshot
let timestamp_regex = Regex::new(r"\b\d{10,}\b").unwrap();
let redact_output = |output: String| {
let output = timestamp_regex.replace_all(&output, "<timestamp>");
output.into_owned()
};
// Working copy should contain conflict marker length
let output = work_dir.run_jj(["debug", "local-working-copy"]);
insta::assert_snapshot!(output.normalize_stdout_with(redact_output), @r#"
Current operation: OperationId("5d919506f1cbd90a43ce93d739d84c0d7de34bc6eeb934befad2c3a16e2fe635c548ced178e42dde1041e140d7296a7000bc38530f1cfd7ed93a23cfc1e81699")
Current tree: MergedTree { tree_ids: Conflicted([TreeId("381273b50cf73f8c81b3f1502ee89e9bbd6c1518"), TreeId("771f3d31c4588ea40a8864b2a981749888e596c2"), TreeId("f56b8223da0dab22b03b8323ced4946329aeb4e0")]), labels: Labeled(["rlvkpnrz ccf9527c \"side-a\"", "qpvuntsm 2205b3ac \"base\"", "zsuskuln d7acaf48 \"side-b\""]), .. }
Normal { exec_bit: ExecBit(false) } 313 <timestamp> Some(MaterializedConflictData { conflict_marker_len: 11 }) "file"
[EOF]
"#);
// Update the conflict with more fake markers, and it should still parse
// correctly (the markers should be ignored)
work_dir.write_file(
"file",
indoc! {"
line 1
<<<<<<<<<<< conflict 1 of 1
%%%%%%%%%%% diff from base to side #1
-line 2
-line 3
+line 2 - left
+line 3 - left
+++++++++++ side #2
<<<<<<< fake marker
||||||| fake marker
line 2 - right
======= fake marker
line 3
>>>>>>> fake marker
>>>>>>>>>>> conflict 1 of 1 ends
"},
);
// The file should still be conflicted, and the new content should be saved
let output = work_dir.run_jj(["st"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
M file
Working copy (@) : mzvwutvl 0e1653f0 (conflict) (no description set)
Parent commit (@-): rlvkpnrz ccf9527c side-a
Parent commit (@-): zsuskuln d7acaf48 side-b
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["diff", "--git"]), @r#"
diff --git a/file b/file
--- a/file
+++ b/file
@@ -7,8 +7,10 @@
+line 2 - left
+line 3 - left
+++++++++++ zsuskuln d7acaf48 "side-b"
-======= fake marker
+<<<<<<< fake marker
+||||||| fake marker
line 2 - right
======= fake marker
line 3
+>>>>>>> fake marker
>>>>>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
// Working copy should still contain conflict marker length
let output = work_dir.run_jj(["debug", "local-working-copy"]);
insta::assert_snapshot!(output.normalize_stdout_with(redact_output), @r#"
Current operation: OperationId("519e354ba030d15583d3e62196b84337d5c446b632b5f92e98c6af246978ca8b166185a2526c48f51b4c2ca423503d3a8636fccefe7eec5ac0a8ab44061ae4a3")
Current tree: MergedTree { tree_ids: Conflicted([TreeId("381273b50cf73f8c81b3f1502ee89e9bbd6c1518"), TreeId("771f3d31c4588ea40a8864b2a981749888e596c2"), TreeId("3329c18c95f7b7a55c278c2259e9c4ce711fae59")]), labels: Labeled(["rlvkpnrz ccf9527c \"side-a\"", "qpvuntsm 2205b3ac \"base\"", "zsuskuln d7acaf48 \"side-b\""]), .. }
Normal { exec_bit: ExecBit(false) } 274 <timestamp> Some(MaterializedConflictData { conflict_marker_len: 11 }) "file"
[EOF]
"#);
// Resolve the conflict
work_dir.write_file(
"file",
indoc! {"
line 1
<<<<<<< fake marker
||||||| fake marker
line 2 - left
line 2 - right
======= fake marker
line 3 - left
>>>>>>> fake marker
"},
);
let output = work_dir.run_jj(["st"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
M file
Working copy (@) : mzvwutvl 469d479f (no description set)
Parent commit (@-): rlvkpnrz ccf9527c side-a
Parent commit (@-): zsuskuln d7acaf48 side-b
[EOF]
");
// When the file is resolved, the conflict marker length is removed from the
// working copy
let output = work_dir.run_jj(["debug", "local-working-copy"]);
insta::assert_snapshot!(output.normalize_stdout_with(redact_output), @r#"
Current operation: OperationId("20e0a52b5cb37d14c675e24cf1325cbe2d145b8369ef17b78b7ae5b0a77177c03585d840469732c98d6b1d528309db873f0a52b3b42e67b7440d9a8c644f5667")
Current tree: MergedTree { tree_ids: Resolved(TreeId("6120567b3cb2472d549753ed3e4b84183d52a650")), labels: Unlabeled, .. }
Normal { exec_bit: ExecBit(false) } 130 <timestamp> None "file"
[EOF]
"#);
}
#[test]
fn test_submodule_ignored() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "submodule"])
.success();
let submodule_dir = test_env.work_dir("submodule");
submodule_dir.write_file("sub", "sub");
submodule_dir
.run_jj(["commit", "-m", "Submodule commit"])
.success();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
// There's no particular reason to run this with jj util exec, it's just that
// the infra makes it easier to run this way.
let output = work_dir.run_jj([
"util",
"exec",
"--",
"git",
"-c",
// Git normally doesn't allow file:// in submodules.
"protocol.file.allow=always",
"submodule",
"add",
&format!("{}/submodule", test_env.env_root().display()),
"sub",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Cloning into '$TEST_ENV/repo/sub'...
done.
[EOF]
");
// Use git to commit since jj won't play nice with the submodule.
work_dir
.run_jj([
"util",
"exec",
"--",
"git",
"-c",
"user.email=test@example.com",
"-c",
"user.name=Test user",
"commit",
"-m",
"Add submodule",
])
.success();
// This should be empty. We shouldn't track the submodule itself.
let output = work_dir.run_jj(["diff", "--summary"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
ignoring git submodule at "sub"
Done importing changes from the underlying Git repo.
[EOF]
"#);
// Switch to a historical commit before the submodule was checked in.
work_dir.run_jj(["prev"]).success();
// jj new (or equivalently prev) should always leave you with an empty working
// copy.
let output = work_dir.run_jj(["diff", "--summary"]);
insta::assert_snapshot!(output, @"");
}
| 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_split_command.rs | cli/tests/test_split_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 test_case::test_case;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"separate(" ", change_id.short(), empty, local_bookmarks, description)"#;
work_dir.run_jj(["log", "-T", template])
}
#[must_use]
fn get_log_with_summary(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"separate(" ", change_id.short(), local_bookmarks, description)"#;
work_dir.run_jj(["log", "-T", template, "--summary"])
}
#[must_use]
fn get_workspace_log_output(work_dir: &TestWorkDir) -> CommandOutput {
let template = r#"separate(" ", change_id.short(), working_copies, description)"#;
work_dir.run_jj(["log", "-T", template, "-r", "all()"])
}
#[must_use]
fn get_recorded_dates(work_dir: &TestWorkDir, revset: &str) -> CommandOutput {
let template = r#"separate("\n", "Author date: " ++ author.timestamp(), "Committer date: " ++ committer.timestamp())"#;
work_dir.run_jj(["log", "--no-graph", "-T", template, "-r", revset])
}
#[test]
fn test_split_by_paths() {
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");
work_dir.write_file("file2", "foo");
work_dir.write_file("file3", "foo");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ qpvuntsmwlqt false
◆ zzzzzzzzzzzz true
[EOF]
");
insta::assert_snapshot!(get_recorded_dates(&work_dir, "@"), @r"
Author date: 2001-02-03 04:05:08.000 +07:00
Committer date: 2001-02-03 04:05:08.000 +07:00[EOF]
");
std::fs::write(
&edit_script,
["dump editor0", "next invocation\n", "dump editor1"].join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["split", "file2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Selected changes : qpvuntsm 6dbc7747 (no description set)
Remaining changes: zsuskuln 42cbbc02 (no description set)
Working copy (@) now at: zsuskuln 42cbbc02 (no description set)
Parent commit (@-) : qpvuntsm 6dbc7747 (no description set)
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor0")).unwrap(), @r#"
JJ: Enter a description for the selected changes.
JJ: Change ID: qpvuntsm
JJ: This commit contains the following changes:
JJ: A file2
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
assert!(!test_env.env_root().join("editor1").exists());
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr false
○ qpvuntsmwlqt false
◆ zzzzzzzzzzzz true
[EOF]
");
// The author dates of the new commits should be inherited from the commit being
// split. The committer dates should be newer.
insta::assert_snapshot!(get_recorded_dates(&work_dir, "@"), @r"
Author date: 2001-02-03 04:05:08.000 +07:00
Committer date: 2001-02-03 04:05:10.000 +07:00[EOF]
");
insta::assert_snapshot!(get_recorded_dates(&work_dir, "@-"), @r"
Author date: 2001-02-03 04:05:08.000 +07:00
Committer date: 2001-02-03 04:05:10.000 +07:00[EOF]
");
let output = work_dir.run_jj(["diff", "-s", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
A file2
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
A file1
A file3
[EOF]
");
// Insert an empty commit after @- with "split ."
std::fs::write(&edit_script, "").unwrap();
let output = work_dir.run_jj(["split", "-r", "@-", "."]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: All changes have been selected, so the original revision will become empty
Rebased 1 descendant commits
Selected changes : qpvuntsm 9fd1c9e1 (no description set)
Remaining changes: znkkpsqq 41e0da21 (empty) (no description set)
Working copy (@) now at: zsuskuln a06e40b8 (no description set)
Parent commit (@-) : znkkpsqq 41e0da21 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr false
○ znkkpsqqskkl true
○ qpvuntsmwlqt false
◆ zzzzzzzzzzzz true
[EOF]
");
let output = work_dir.run_jj(["diff", "-s", "-r", "@--"]);
insta::assert_snapshot!(output, @r"
A file2
[EOF]
");
// Remove newly created empty commit
work_dir.run_jj(["abandon", "@-"]).success();
// Insert an empty commit before @- with "split nonexistent"
std::fs::write(&edit_script, "").unwrap();
let output = work_dir.run_jj(["split", "-r", "@-", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
Warning: No changes have been selected, so the new revision will be empty
Rebased 1 descendant commits
Selected changes : qpvuntsm 49416632 (empty) (no description set)
Remaining changes: lylxulpl 718afbf5 (no description set)
Working copy (@) now at: zsuskuln 0ed53ee6 (no description set)
Parent commit (@-) : lylxulpl 718afbf5 (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr false
○ lylxulplsnyw false
○ qpvuntsmwlqt true
◆ zzzzzzzzzzzz true
[EOF]
");
let output = work_dir.run_jj(["diff", "-s", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
A file2
[EOF]
");
work_dir.run_jj(["new"]).success();
// Splitting a commit with deleted files should not show a warning.
work_dir.remove_file("file1");
let output = work_dir.run_jj(["split", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: All changes have been selected, so the original revision will become empty
Selected changes : uyznsvlq 971ccc0b (no description set)
Remaining changes: xznxytkn a267cd96 (empty) (no description set)
Working copy (@) now at: smwtzssm 6715dc2c (empty) (no description set)
Parent commit (@-) : uyznsvlq 971ccc0b (no description set)
[EOF]
");
}
#[test]
fn test_split_with_non_empty_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");
work_dir.run_jj(["describe", "-m", "test"]).success();
std::fs::write(
edit_script,
[
"dump editor1",
"write\npart 1",
"next invocation\n",
"dump editor2",
"write\npart 2",
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["split", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Selected changes : qpvuntsm c7f7b14b part 1
Remaining changes: kkmpptxz ac33a5a9 part 2
Working copy (@) now at: kkmpptxz ac33a5a9 part 2
Parent commit (@-) : qpvuntsm c7f7b14b part 1
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor1")).unwrap(), @r#"
JJ: Enter a description for the selected changes.
test
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!(
std::fs::read_to_string(test_env.env_root().join("editor2")).unwrap(), @r#"
JJ: Enter a description for the remaining changes.
test
JJ: Change ID: kkmpptxz
JJ: This commit contains the following changes:
JJ: A file2
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ kkmpptxzrspx false part 2
○ qpvuntsmwlqt false part 1
◆ zzzzzzzzzzzz true
[EOF]
");
}
#[test]
fn test_split_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 editor1", "next invocation\n", "dump editor2"].join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["split", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Selected changes : qpvuntsm ff633dcc TESTED=TODO
Remaining changes: rlvkpnrz b1d20b7e (no description set)
Working copy (@) now at: rlvkpnrz b1d20b7e (no description set)
Parent commit (@-) : qpvuntsm ff633dcc TESTED=TODO
[EOF]
");
// Since the commit being split has no description, the user will only be
// prompted to add a description to the first commit, which will use the
// default value we set. The second commit will inherit the empty
// description from the commit being split.
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor1")).unwrap(), @r#"
JJ: Enter a description for the selected changes.
TESTED=TODO
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.
"#);
assert!(!test_env.env_root().join("editor2").exists());
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ rlvkpnrzqnoo false
○ qpvuntsmwlqt false TESTED=TODO
◆ zzzzzzzzzzzz true
[EOF]
");
}
#[test]
fn test_split_with_descendants() {
// Configure the environment and make the initial 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");
// First commit. This is the one we will split later.
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
work_dir
.run_jj(["commit", "-m", "Add file1 & file2"])
.success();
// Second commit.
work_dir.write_file("file3", "baz\n");
work_dir.run_jj(["commit", "-m", "Add file3"]).success();
// Third commit.
work_dir.write_file("file4", "foobarbaz\n");
work_dir.run_jj(["describe", "-m", "Add file4"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ kkmpptxzrspx false Add file4
○ rlvkpnrzqnoo false Add file3
○ qpvuntsmwlqt false Add file1 & file2
◆ zzzzzzzzzzzz true
[EOF]
");
// Set up the editor and do the split.
std::fs::write(
edit_script,
[
"dump editor1",
"write\nAdd file1",
"next invocation\n",
"dump editor2",
"write\nAdd file2",
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["split", "file1", "-r", "qpvu"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 descendant commits
Selected changes : qpvuntsm 74306e35 Add file1
Remaining changes: royxmykx 0a37745e Add file2
Working copy (@) now at: kkmpptxz 7ee84812 Add file4
Parent commit (@-) : rlvkpnrz d335bd94 Add file3
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ kkmpptxzrspx false Add file4
○ rlvkpnrzqnoo false Add file3
○ royxmykxtrkr false Add file2
○ qpvuntsmwlqt false Add file1
◆ zzzzzzzzzzzz true
[EOF]
");
// The commit we're splitting has a description, so the user will be
// prompted to enter a description for each of the commits.
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor1")).unwrap(), @r#"
JJ: Enter a description for the selected changes.
Add file1 & file2
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!(
std::fs::read_to_string(test_env.env_root().join("editor2")).unwrap(), @r#"
JJ: Enter a description for the remaining changes.
Add file1 & file2
JJ: Change ID: royxmykx
JJ: This commit contains the following changes:
JJ: A file2
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
// Check the evolog for the first commit. It shows four entries:
// - The initial empty commit.
// - The rewritten commit from the snapshot after the files were added.
// - The rewritten commit once the description is added during `jj commit`.
// - The rewritten commit after the split.
let evolog_1 = work_dir.run_jj(["evolog", "-r", "qpvun"]);
insta::assert_snapshot!(evolog_1, @r"
○ qpvuntsm test.user@example.com 2001-02-03 08:05:12 74306e35
│ Add file1
│ -- operation 994b490f285d split commit 1d2499e72cefc8a2b87ebb47569140857b96189f
○ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:08 1d2499e7 (hidden)
│ Add file1 & file2
│ -- operation adf4f33386c9 commit f5700f8ef89e290e4e90ae6adc0908707e0d8c85
○ qpvuntsm/2 test.user@example.com 2001-02-03 08:05:08 f5700f8e (hidden)
│ (no description set)
│ -- operation 78ead2155fcc snapshot working copy
○ qpvuntsm/3 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
[EOF]
");
// The evolog for the second commit is the same, except that the change id
// changes after the split.
let evolog_2 = work_dir.run_jj(["evolog", "-r", "royxm"]);
insta::assert_snapshot!(evolog_2, @r"
○ royxmykx test.user@example.com 2001-02-03 08:05:12 0a37745e
│ Add file2
│ -- operation 994b490f285d split commit 1d2499e72cefc8a2b87ebb47569140857b96189f
○ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:08 1d2499e7 (hidden)
│ Add file1 & file2
│ -- operation adf4f33386c9 commit f5700f8ef89e290e4e90ae6adc0908707e0d8c85
○ qpvuntsm/2 test.user@example.com 2001-02-03 08:05:08 f5700f8e (hidden)
│ (no description set)
│ -- operation 78ead2155fcc snapshot working copy
○ qpvuntsm/3 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
[EOF]
");
}
// This test makes sure that the children of the commit being split retain any
// other parents which weren't involved in the split.
#[test]
fn test_split_with_merge_child() {
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=1"]).success();
work_dir.run_jj(["new", "root()", "-m=a"]).success();
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
work_dir
.run_jj(["new", "subject(1)", "subject(a)", "-m=2"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr true 2
├─╮
│ ○ kkmpptxzrspx false a
○ │ qpvuntsmwlqt true 1
├─╯
◆ zzzzzzzzzzzz true
[EOF]
");
// Set up the editor and do the split.
std::fs::write(
edit_script,
["write\nAdd file1", "next invocation\n", "write\nAdd file2"].join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["split", "-rsubject(a)", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Selected changes : kkmpptxz cc199567 Add file1
Remaining changes: royxmykx e488409f Add file2
Working copy (@) now at: zsuskuln ace61421 (empty) 2
Parent commit (@-) : qpvuntsm 884fe9b9 (empty) 1
Parent commit (@-) : royxmykx e488409f Add file2
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr true 2
├─╮
│ ○ royxmykxtrkr false Add file2
│ ○ kkmpptxzrspx false Add file1
○ │ qpvuntsmwlqt true 1
├─╯
◆ zzzzzzzzzzzz true
[EOF]
");
}
#[test]
// Split a commit with no descendants into siblings. Also tests that the default
// description is set correctly on the first commit.
fn test_split_parallel_no_descendants() {
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");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ qpvuntsmwlqt false
◆ zzzzzzzzzzzz true
[EOF]
");
std::fs::write(
edit_script,
["dump editor1", "next invocation\n", "dump editor2"].join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["split", "--parallel", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Selected changes : qpvuntsm 7bcd474c TESTED=TODO
Remaining changes: kkmpptxz 431886f6 (no description set)
Working copy (@) now at: kkmpptxz 431886f6 (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ kkmpptxzrspx false
│ ○ qpvuntsmwlqt false TESTED=TODO
├─╯
◆ zzzzzzzzzzzz true
[EOF]
");
// Since the commit being split has no description, the user will only be
// prompted to add a description to the first commit, which will use the
// default value we set. The second commit will inherit the empty
// description from the commit being split.
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor1")).unwrap(), @r#"
JJ: Enter a description for the selected changes.
TESTED=TODO
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.
"#);
assert!(!test_env.env_root().join("editor2").exists());
// Check the evolog for the first commit. It shows three entries:
// - The initial empty commit.
// - The rewritten commit from the snapshot after the files were added.
// - The rewritten commit after the split.
let evolog_1 = work_dir.run_jj(["evolog", "-r", "qpvun"]);
insta::assert_snapshot!(evolog_1, @r"
○ qpvuntsm test.user@example.com 2001-02-03 08:05:09 7bcd474c
│ TESTED=TODO
│ -- operation 2b21c33e1596 split commit f5700f8ef89e290e4e90ae6adc0908707e0d8c85
○ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:08 f5700f8e (hidden)
│ (no description set)
│ -- operation 1663cd1cc445 snapshot working copy
○ qpvuntsm/2 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
[EOF]
");
// The evolog for the second commit is the same, except that the change id
// changes after the split.
let evolog_2 = work_dir.run_jj(["evolog", "-r", "kkmpp"]);
insta::assert_snapshot!(evolog_2, @r"
@ kkmpptxz test.user@example.com 2001-02-03 08:05:09 431886f6
│ (no description set)
│ -- operation 2b21c33e1596 split commit f5700f8ef89e290e4e90ae6adc0908707e0d8c85
○ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:08 f5700f8e (hidden)
│ (no description set)
│ -- operation 1663cd1cc445 snapshot working copy
○ qpvuntsm/2 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_split_parallel_with_descendants() {
// Configure the environment and make the initial 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");
// First commit. This is the one we will split later.
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
work_dir
.run_jj(["commit", "-m", "Add file1 & file2"])
.success();
// Second commit. This will be the child of the sibling commits after the split.
work_dir.write_file("file3", "baz\n");
work_dir.run_jj(["commit", "-m", "Add file3"]).success();
// Third commit.
work_dir.write_file("file4", "foobarbaz\n");
work_dir.run_jj(["describe", "-m", "Add file4"]).success();
// Move back to the previous commit so that we don't have to pass a revision
// to the split command.
work_dir.run_jj(["prev", "--edit"]).success();
work_dir.run_jj(["prev", "--edit"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ kkmpptxzrspx false Add file4
○ rlvkpnrzqnoo false Add file3
@ qpvuntsmwlqt false Add file1 & file2
◆ zzzzzzzzzzzz true
[EOF]
");
// Set up the editor and do the split.
std::fs::write(
edit_script,
[
"dump editor1",
"write\nAdd file1",
"next invocation\n",
"dump editor2",
"write\nAdd file2",
]
.join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["split", "--parallel", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 2 descendant commits
Selected changes : qpvuntsm 18c85f56 Add file1
Remaining changes: vruxwmqv cbdfd9cf Add file2
Working copy (@) now at: vruxwmqv cbdfd9cf Add file2
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ kkmpptxzrspx false Add file4
○ rlvkpnrzqnoo false Add file3
├─╮
│ @ vruxwmqvtpmx false Add file2
○ │ qpvuntsmwlqt false Add file1
├─╯
◆ zzzzzzzzzzzz true
[EOF]
");
// The commit we're splitting has a description, so the user will be
// prompted to enter a description for each of the sibling commits.
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("editor1")).unwrap(), @r#"
JJ: Enter a description for the selected changes.
Add file1 & file2
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!(
std::fs::read_to_string(test_env.env_root().join("editor2")).unwrap(), @r#"
JJ: Enter a description for the remaining changes.
Add file1 & file2
JJ: Change ID: vruxwmqv
JJ: This commit contains the following changes:
JJ: A file2
JJ:
JJ: Lines starting with "JJ:" (like this one) will be removed.
"#);
}
// This test makes sure that the children of the commit being split retain any
// other parents which weren't involved in the split.
#[test]
fn test_split_parallel_with_merge_child() {
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=1"]).success();
work_dir.run_jj(["new", "root()", "-m=a"]).success();
work_dir.write_file("file1", "foo\n");
work_dir.write_file("file2", "bar\n");
work_dir
.run_jj(["new", "subject(1)", "subject(a)", "-m=2"])
.success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr true 2
├─╮
│ ○ kkmpptxzrspx false a
○ │ qpvuntsmwlqt true 1
├─╯
◆ zzzzzzzzzzzz true
[EOF]
");
// Set up the editor and do the split.
std::fs::write(
edit_script,
["write\nAdd file1", "next invocation\n", "write\nAdd file2"].join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["split", "-rsubject(a)", "--parallel", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Selected changes : kkmpptxz cc199567 Add file1
Remaining changes: royxmykx 82a5c527 Add file2
Working copy (@) now at: zsuskuln b7cdcdec (empty) 2
Parent commit (@-) : qpvuntsm 884fe9b9 (empty) 1
Parent commit (@-) : kkmpptxz cc199567 Add file1
Parent commit (@-) : royxmykx 82a5c527 Add file2
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr true 2
├─┬─╮
│ │ ○ royxmykxtrkr false Add file2
│ ○ │ kkmpptxzrspx false Add file1
│ ├─╯
○ │ qpvuntsmwlqt true 1
├─╯
◆ zzzzzzzzzzzz true
[EOF]
");
}
#[test]
fn test_split_parallel_with_conflict() {
let mut test_env = TestEnvironment::default();
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("file", "line 1\nline 2\nline 3\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "line 1\nline 2.1\nline 2.2\nline 3\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "line 1\nline 3\n");
work_dir.run_jj(["prev", "--edit"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ kkmpptxzrspx false
@ rlvkpnrzqnoo false
○ qpvuntsmwlqt false
◆ zzzzzzzzzzzz true
[EOF]
");
// Create a conflict by splitting two consecutive lines into parallel commits.
std::fs::write(
diff_editor,
["write file\nline 1\nline 2.1\nline 3\n"].join("\0"),
)
.unwrap();
let output = work_dir.run_jj(["split", "--parallel", "-i", "-m="]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Selected changes : rlvkpnrz abe15fea (no description set)
Remaining changes: royxmykx ec55f25f (conflict) (no description set)
Working copy (@) now at: royxmykx ec55f25f (conflict) (no description set)
Parent commit (@-) : qpvuntsm ee8e9376 (no description set)
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:
royxmykx ec55f25f (conflict) (no description set)
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new royxmykx
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"
○ kkmpptxzrspx false
├─╮
│ @ royxmykxtrkr false
○ │ rlvkpnrzqnoo false
├─╯
○ qpvuntsmwlqt false
◆ zzzzzzzzzzzz true
[EOF]
");
// The new commit should be conflicted.
insta::assert_snapshot!(work_dir.read_file("file"), @r"
line 1
<<<<<<< conflict 1 of 1
%%%%%%% diff from: selected changes for split (from rlvkpnrz 35382813)
\\\\\\\ to: split revision (rlvkpnrz 35382813)
line 2.1
+line 2.2
+++++++ qpvuntsm ee8e9376 (parents of split revision)
line 2
>>>>>>> conflict 1 of 1 ends
line 3
");
// The old commit shouldn't be conflicted, since it matches the selection from
// the editor.
insta::assert_snapshot!(work_dir.run_jj(["file", "show", "-r=@+-~@", "file"]), @r"
line 1
line 2.1
line 3
[EOF]
");
// The child merge commit should keep the same contents.
insta::assert_snapshot!(work_dir.run_jj(["file", "show", "-r=@+", "file"]), @r"
line 1
line 3
[EOF]
");
}
// Make sure `jj split` would refuse to split an empty commit.
#[test]
fn test_split_empty() {
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", "--message", "abc"]).success();
let output = work_dir.run_jj(["split"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Refusing to split empty commit 64eaeeb3e846248efc8b599a2b583b708104fc01.
Hint: Use `jj new` if you want to create another empty commit.
[EOF]
[exit status: 1]
");
}
#[test]
fn test_split_message_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");
work_dir.write_file("file1", "foo");
work_dir.write_file("file2", "foo");
std::fs::write(edit_script, "dump-path path").unwrap();
work_dir.run_jj(["split", "file2"]).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_split_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");
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();
// Split the working commit interactively and select only file1
let output = work_dir.run_jj(["split"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Selected changes : qpvuntsm c664a51b (no description set)
Remaining changes: rlvkpnrz 7e5d65b1 (no description set)
Working copy (@) now at: rlvkpnrz 7e5d65b1 (no description set)
Parent commit (@-) : qpvuntsm c664a51b (no description set)
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("instrs")).unwrap(), @r"
You are splitting a commit into two: qpvuntsm f5700f8e (no description set)
The diff initially shows the changes in the commit you're splitting.
| 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_root.rs | cli/tests/test_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 testutils::git;
use crate::common::TestEnvironment;
#[test]
fn test_git_root_git_backend_noncolocated() {
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(["git", "root"]);
insta::assert_snapshot!(output, @r"
$TEST_ENV/repo/.jj/repo/store/git
[EOF]
");
}
#[test]
fn test_git_root_git_backend_colocated() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "--colocate", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["git", "root"]);
insta::assert_snapshot!(output, @r"
$TEST_ENV/repo/.git
[EOF]
");
}
#[test]
fn test_git_root_git_backend_external_git_dir() {
let test_env = TestEnvironment::default();
let work_dir = test_env.work_dir("").create_dir("repo");
let git_repo_work_dir = test_env.work_dir("git-repo");
let git_repo = git::init(git_repo_work_dir.root());
// Create an initial commit in Git
let tree_id = git::add_commit(
&git_repo,
"refs/heads/master",
"file",
b"contents",
"initial",
&[],
)
.tree_id;
git::checkout_tree_index(&git_repo, tree_id);
assert_eq!(git_repo_work_dir.read_file("file"), b"contents");
insta::assert_snapshot!(
git_repo.head_id().unwrap().to_string(),
@"97358f54806c7cd005ed5ade68a779595efbae7e"
);
work_dir
.run_jj([
"git",
"init",
"--git-repo",
git_repo_work_dir.root().to_str().unwrap(),
])
.success();
let output = work_dir.run_jj(["git", "root"]);
insta::assert_snapshot!(output, @r"
$TEST_ENV/git-repo/.git
[EOF]
");
}
#[test]
fn test_git_root_simple_backend() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["debug", "init-simple", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["git", "root"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The repo is not backed by a Git repo
[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_show_command.rs | cli/tests/test_show_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 regex::Regex;
use crate::common::TestEnvironment;
#[test]
fn test_show() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Show @ by default
let output = work_dir.run_jj(["show"]);
let output = output.normalize_stdout_with(|s| s.split_inclusive('\n').skip(2).collect());
insta::assert_snapshot!(output, @r"
Author : Test User <test.user@example.com> (2001-02-03 08:05:07)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:07)
(no description set)
[EOF]
");
// Specify revision with -r
let output = work_dir.run_jj(["show", "-r@-"]);
insta::assert_snapshot!(output, @r"
Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 11:00:00)
Committer: (no name set) <(no email set)> (1970-01-01 11:00:00)
(no description set)
[EOF]
");
// Specify both positional and -r args
let output = work_dir.run_jj(["show", "@", "-r@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '[REVSET]' cannot be used with '-r <REVSET>'
Usage: jj show <REVSET>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_show_basic() {
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", "foo\nbaz qux\n");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.write_file("file2", "foo\nbar\nbaz quux\n");
work_dir.write_file("file3", "foo\n");
let output = work_dir.run_jj(["show"]);
insta::assert_snapshot!(output, @r"
Commit ID: 92e687faa4e5b681937f5a9c47feaa33e6b4892c
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
(no description set)
Modified regular file file2:
1 1: foo
2: bar
2 3: baz quxquux
Modified regular file file3 (file1 => file3):
[EOF]
");
let output = work_dir.run_jj(["show", "--context=0"]);
insta::assert_snapshot!(output, @r"
Commit ID: 92e687faa4e5b681937f5a9c47feaa33e6b4892c
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
(no description set)
Modified regular file file2:
1 1: foo
2: bar
2 3: baz quxquux
Modified regular file file3 (file1 => file3):
[EOF]
");
let output = work_dir.run_jj(["show", "--color=debug"]);
insta::assert_snapshot!(output, @r"
<<show commit::Commit ID: >>[38;5;4m<<show commit commit_id::92e687faa4e5b681937f5a9c47feaa33e6b4892c>>[39m<<show commit::>>
<<show commit::Change ID: >>[38;5;5m<<show commit change_id::rlvkpnrzqnoowoytxnquwvuryrwnrmlp>>[39m<<show commit::>>
<<show commit::Author : >>[38;5;3m<<show commit author name::Test User>>[39m<<show commit:: <>>[38;5;3m<<show commit author email local::test.user>><<show commit author email::@>><<show commit author email domain::example.com>>[39m<<show commit::> (>>[38;5;6m<<show commit author timestamp local format::2001-02-03 08:05:09>>[39m<<show commit::)>>
<<show commit::Committer: >>[38;5;3m<<show commit committer name::Test User>>[39m<<show commit:: <>>[38;5;3m<<show commit committer email local::test.user>><<show commit committer email::@>><<show commit committer email domain::example.com>>[39m<<show commit::> (>>[38;5;6m<<show commit committer timestamp local format::2001-02-03 08:05:09>>[39m<<show commit::)>>
<<show commit::>>
[38;5;3m<<show commit description placeholder:: (no description set)>>[39m<<show commit::>>
<<show commit::>>
[38;5;3m<<diff header::Modified regular file file2:>>[39m
[2m[38;5;1m<<diff context removed line_number:: 1>>[0m<<diff context:: >>[2m[38;5;2m<<diff context added line_number:: 1>>[0m<<diff context::: foo>>
<<diff:: >>[38;5;2m<<diff added line_number:: 2>>[39m<<diff::: >>[4m[38;5;2m<<diff added token::bar>>[24m[39m
[38;5;1m<<diff removed line_number:: 2>>[39m<<diff:: >>[38;5;2m<<diff added line_number:: 3>>[39m<<diff::: baz >>[4m[38;5;1m<<diff removed token::qux>>[38;5;2m<<diff added token::quux>>[24m[39m<<diff::>>
[38;5;3m<<diff header::Modified regular file file3 (file1 => file3):>>[39m
[EOF]
");
let output = work_dir.run_jj(["show", "-s"]);
insta::assert_snapshot!(output, @r"
Commit ID: 92e687faa4e5b681937f5a9c47feaa33e6b4892c
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
(no description set)
M file2
R {file1 => file3}
[EOF]
");
let output = work_dir.run_jj(["show", "--types"]);
insta::assert_snapshot!(output, @r"
Commit ID: 92e687faa4e5b681937f5a9c47feaa33e6b4892c
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
(no description set)
FF file2
FF {file1 => file3}
[EOF]
");
let output = work_dir.run_jj(["show", "--git"]);
insta::assert_snapshot!(output, @r"
Commit ID: 92e687faa4e5b681937f5a9c47feaa33e6b4892c
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
(no description set)
diff --git a/file2 b/file2
index 523a4a9de8..485b56a572 100644
--- a/file2
+++ b/file2
@@ -1,2 +1,3 @@
foo
-baz qux
+bar
+baz quux
diff --git a/file1 b/file3
rename from file1
rename to file3
[EOF]
");
let output = work_dir.run_jj(["show", "--git", "--context=0"]);
insta::assert_snapshot!(output, @r"
Commit ID: 92e687faa4e5b681937f5a9c47feaa33e6b4892c
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
(no description set)
diff --git a/file2 b/file2
index 523a4a9de8..485b56a572 100644
--- a/file2
+++ b/file2
@@ -2,1 +2,2 @@
-baz qux
+bar
+baz quux
diff --git a/file1 b/file3
rename from file1
rename to file3
[EOF]
");
let output = work_dir.run_jj(["show", "--git", "--color=debug"]);
insta::assert_snapshot!(output, @r"
<<show commit::Commit ID: >>[38;5;4m<<show commit commit_id::92e687faa4e5b681937f5a9c47feaa33e6b4892c>>[39m<<show commit::>>
<<show commit::Change ID: >>[38;5;5m<<show commit change_id::rlvkpnrzqnoowoytxnquwvuryrwnrmlp>>[39m<<show commit::>>
<<show commit::Author : >>[38;5;3m<<show commit author name::Test User>>[39m<<show commit:: <>>[38;5;3m<<show commit author email local::test.user>><<show commit author email::@>><<show commit author email domain::example.com>>[39m<<show commit::> (>>[38;5;6m<<show commit author timestamp local format::2001-02-03 08:05:09>>[39m<<show commit::)>>
<<show commit::Committer: >>[38;5;3m<<show commit committer name::Test User>>[39m<<show commit:: <>>[38;5;3m<<show commit committer email local::test.user>><<show commit committer email::@>><<show commit committer email domain::example.com>>[39m<<show commit::> (>>[38;5;6m<<show commit committer timestamp local format::2001-02-03 08:05:09>>[39m<<show commit::)>>
<<show commit::>>
[38;5;3m<<show commit description placeholder:: (no description set)>>[39m<<show commit::>>
<<show commit::>>
[1m<<diff file_header::diff --git a/file2 b/file2>>[0m
[1m<<diff file_header::index 523a4a9de8..485b56a572 100644>>[0m
[1m<<diff file_header::--- a/file2>>[0m
[1m<<diff file_header::+++ b/file2>>[0m
[38;5;6m<<diff hunk_header::@@ -1,2 +1,3 @@>>[39m
<<diff context:: foo>>
[38;5;1m<<diff removed::-baz >>[4m<<diff removed token::qux>>[24m<<diff removed::>>[39m
[38;5;2m<<diff added::+>>[4m<<diff added token::bar>>[24m[39m
[38;5;2m<<diff added::+baz >>[4m<<diff added token::quux>>[24m<<diff added::>>[39m
[1m<<diff file_header::diff --git a/file1 b/file3>>[0m
[1m<<diff file_header::rename from file1>>[0m
[1m<<diff file_header::rename to file3>>[0m
[EOF]
");
let output = work_dir.run_jj(["show", "-s", "--git"]);
insta::assert_snapshot!(output, @r"
Commit ID: 92e687faa4e5b681937f5a9c47feaa33e6b4892c
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
(no description set)
M file2
R {file1 => file3}
diff --git a/file2 b/file2
index 523a4a9de8..485b56a572 100644
--- a/file2
+++ b/file2
@@ -1,2 +1,3 @@
foo
-baz qux
+bar
+baz quux
diff --git a/file1 b/file3
rename from file1
rename to file3
[EOF]
");
let output = work_dir.run_jj(["show", "--stat"]);
insta::assert_snapshot!(output, @r"
Commit ID: 92e687faa4e5b681937f5a9c47feaa33e6b4892c
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:09)
(no description set)
file2 | 3 ++-
{file1 => file3} | 0
2 files changed, 2 insertions(+), 1 deletion(-)
[EOF]
");
}
#[test]
fn test_show_with_template() {
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", "a new commit"]).success();
let output = work_dir.run_jj(["show", "-T", "description"]);
insta::assert_snapshot!(output, @r"
a new commit
[EOF]
");
}
#[test]
fn test_show_with_template_no_patch() {
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", "a new commit"]).success();
work_dir.write_file("file1", "foo\n");
let output = work_dir.run_jj(["show", "--no-patch", "-T", "description"]);
insta::assert_snapshot!(output, @r"
a new commit
[EOF]
");
}
#[test]
fn test_show_with_no_patch() {
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", "a new commit"]).success();
work_dir.write_file("file1", "foo\n");
let output = work_dir.run_jj(["show", "--no-patch"]);
insta::assert_snapshot!(output, @r"
Commit ID: 86d5fa72f4ecc6d51478941ee9160db9c52b842e
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
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:09)
a new commit
[EOF]
");
}
#[test]
fn test_show_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(["show", "-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_show_relative_timestamps() {
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_timestamp(timestamp)' = 'timestamp.ago()'
"#,
);
let output = work_dir.run_jj(["show"]);
let timestamp_re = Regex::new(r"\([0-9]+ years ago\)").unwrap();
let output = output.normalize_stdout_with(|s| {
s.split_inclusive('\n')
.skip(2)
.map(|x| timestamp_re.replace_all(x, "(...timestamp...)"))
.collect()
});
insta::assert_snapshot!(output, @r"
Author : Test User <test.user@example.com> (...timestamp...)
Committer: Test User <test.user@example.com> (...timestamp...)
(no description set)
[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_util_command.rs | cli/tests/test_util_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 std::fs;
use insta::assert_snapshot;
use crate::common::TestEnvironment;
#[test]
fn test_util_config_schema() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["util", "config-schema"]);
// Validate partial snapshot, redacting any lines nested 2+ indent levels.
insta::with_settings!({filters => vec![(r"(?m)(^ .*$\r?\n)+", " [...]\n")]}, {
assert_snapshot!(output, @r#"
{
"$schema": "http://json-schema.org/draft-04/schema",
"$comment": "`taplo` and the corresponding VS Code plugins only support version draft-04 of JSON Schema, see <https://taplo.tamasfe.dev/configuration/developing-schemas.html>. draft-07 is mostly compatible with it, newer versions may not be.",
"title": "Jujutsu config",
"type": "object",
"description": "User configuration for Jujutsu VCS. See https://docs.jj-vcs.dev/latest/config/ for details",
"properties": {
[...]
}
}
[EOF]
"#);
});
}
#[test]
fn test_gc_args() {
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(["util", "gc"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["util", "gc", "--at-op=@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Cannot garbage collect from a non-head operation
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["util", "gc", "--expire=foobar"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: --expire only accepts 'now'
[EOF]
[exit status: 1]
");
}
#[test]
fn test_gc_operation_log() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Create an operation.
work_dir.write_file("file", "a change\n");
work_dir.run_jj(["commit", "-m", "a change"]).success();
let op_to_remove = work_dir.current_operation_id();
// Make another operation the head.
work_dir.write_file("file", "another change\n");
work_dir
.run_jj(["commit", "-m", "another change"])
.success();
// This works before the operation is removed.
work_dir
.run_jj(["debug", "object", "operation", &op_to_remove])
.success();
// Remove some operations.
work_dir.run_jj(["operation", "abandon", "..@-"]).success();
work_dir.run_jj(["util", "gc", "--expire=now"]).success();
// Now this doesn't work.
let output = work_dir.run_jj(["debug", "object", "operation", &op_to_remove]);
insta::assert_snapshot!(output.strip_stderr_last_line(), @r"
------- stderr -------
Internal error: Failed to load an operation
Caused by:
1: Object b50d0a8f111a9d30d45d429d62c8e54016cc7c891706921a6493756c8074e883671cf3dac0ac9f94ef0fa8c79738a3dfe38c3e1f6c5e1a4a4d0857d266ef2040 of type operation not found
2: Cannot access $TEST_ENV/repo/.jj/repo/op_store/operations/b50d0a8f111a9d30d45d429d62c8e54016cc7c891706921a6493756c8074e883671cf3dac0ac9f94ef0fa8c79738a3dfe38c3e1f6c5e1a4a4d0857d266ef2040
[EOF]
[exit status: 255]
");
}
#[test]
fn test_shell_completions() {
#[track_caller]
fn test(shell: &str) {
let test_env = TestEnvironment::default();
// Use the local backend because GitBackend::gc() depends on the git CLI.
let output = test_env
.run_jj_in(".", ["util", "completion", shell])
.success();
// Ensures only stdout contains text
assert!(
!output.stdout.is_empty() && output.stderr.is_empty(),
"{output}"
);
}
test("bash");
test("elvish");
test("fish");
test("nushell");
test("power-shell");
test("zsh");
}
#[test]
fn test_util_exec() {
let test_env = TestEnvironment::default();
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
let output = test_env.run_jj_in(
".",
[
"util",
"exec",
"--",
formatter_path.to_str().unwrap(),
"--append",
"hello",
],
);
// Ensures only stdout contains text
insta::assert_snapshot!(output, @"hello[EOF]");
}
#[test]
fn test_util_exec_fail() {
let test_env = TestEnvironment::default();
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
let output = test_env.run_jj_in(
".",
[
"util",
"exec",
"--",
formatter_path.to_str().unwrap(),
"--badopt",
],
);
// Ensures only stdout contains text
insta::assert_snapshot!(output.normalize_stderr_with(|s| s.replace(".exe", "")), @r"
------- stderr -------
error: unexpected argument '--badopt' found
tip: a similar argument exists: '--abort'
Usage: fake-formatter --abort
For more information, try '--help'.
[EOF]
[exit status: 2]
");
}
#[test]
fn test_util_exec_not_found() {
let test_env = TestEnvironment::default();
let output = test_env.run_jj_in(".", ["util", "exec", "--", "jj-test-missing-program"]);
insta::assert_snapshot!(output.strip_stderr_last_line(), @r"
------- stderr -------
Error: Failed to execute external command 'jj-test-missing-program'
[EOF]
[exit status: 1]
");
}
#[test]
fn test_util_exec_crash() {
let test_env = TestEnvironment::default();
let formatter_path = assert_cmd::cargo::cargo_bin!("fake-formatter");
let output = test_env.run_jj_in(
".",
[
"util",
"exec",
"--",
formatter_path.to_str().unwrap(),
"--abort",
],
);
if cfg!(unix) {
// abort produces SIGABRT; strip any "(core dumped)" string
let output = output.normalize_stderr_with(|s| s.replacen(" (core dumped)", "", 1));
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: External command was terminated by signal: 6 (SIGABRT)
[EOF]
[exit status: 1]
");
} else if cfg!(windows) {
// abort produces STATUS_STACK_BUFFER_OVERRUN (0xc0000409)
insta::assert_snapshot!(output, @r"
[exit status: -1073740791]
");
}
}
#[cfg(unix)]
#[test]
fn test_util_exec_sets_env() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let output = test_env.run_jj_in(
".",
[
"-R",
"repo",
"util",
"exec",
"--",
"/bin/sh",
"-c",
r#"echo "$JJ_WORKSPACE_ROOT""#,
],
);
insta::assert_snapshot!(output, @r"
$TEST_ENV/repo
[EOF]
");
}
#[test]
fn test_install_man_pages() {
let test_env = TestEnvironment::default();
// no man pages present
let man_dir = test_env.env_root().join("man1");
assert!(!man_dir.exists());
// install man pages
let output = test_env.run_jj_in(".", ["util", "install-man-pages", "."]);
insta::assert_snapshot!(output, @"");
// confirm something is now present
assert!(man_dir.is_dir());
assert!(fs::read_dir(man_dir).unwrap().next().is_some());
}
| 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_sign_unsign_commands.rs | cli/tests/test_sign_unsign_commands.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::TestEnvironment;
#[test]
fn test_sign() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[ui]
show-cryptographic-signatures = true
[signing]
behavior = "keep"
backend = "test"
"#,
);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "one"]).success();
work_dir.run_jj(["commit", "-m", "two"]).success();
work_dir.run_jj(["commit", "-m", "three"]).success();
let output = work_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:10 fbef508b
│ (empty) (no description set)
○ kkmpptxz test.user@example.com 2001-02-03 08:05:10 8c63f712
│ (empty) three
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 26a2c4cb
│ (empty) two
○ qpvuntsm test.user@example.com 2001-02-03 08:05:08 401ea16f
│ (empty) one
◆ zzzzzzzz root() 00000000
[EOF]
");
let output = work_dir.run_jj(["sign", "-r", "..@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Signed 4 commits:
qpvuntsm 7fb98da0 (empty) one
rlvkpnrz 062a3c5a (empty) two
kkmpptxz d2174a79 (empty) three
zsuskuln 8d7bc037 (empty) (no description set)
Working copy (@) now at: zsuskuln 8d7bc037 (empty) (no description set)
Parent commit (@-) : kkmpptxz d2174a79 (empty) three
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:12 8d7bc037 [✓︎]
│ (empty) (no description set)
○ kkmpptxz test.user@example.com 2001-02-03 08:05:12 d2174a79 [✓︎]
│ (empty) three
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:12 062a3c5a [✓︎]
│ (empty) two
○ qpvuntsm test.user@example.com 2001-02-03 08:05:12 7fb98da0 [✓︎]
│ (empty) one
◆ zzzzzzzz root() 00000000
[EOF]
");
// Commits already always signed, even if they are already signed by me.
// https://github.com/jj-vcs/jj/issues/5786
let output = work_dir.run_jj(["sign", "-r", "..@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Signed 4 commits:
qpvuntsm a57217b4 (empty) one
rlvkpnrz e0c0e7ad (empty) two
kkmpptxz fc827eb8 (empty) three
zsuskuln 66574289 (empty) (no description set)
Working copy (@) now at: zsuskuln 66574289 (empty) (no description set)
Parent commit (@-) : kkmpptxz fc827eb8 (empty) three
[EOF]
");
// Signing nothing is a valid no-op.
let output = work_dir.run_jj(["sign", "-r", "none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
}
#[test]
fn test_sign_default_revset() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[ui]
show-cryptographic-signatures = true
[signing]
behavior = "keep"
backend = "test"
"#,
);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "one"]).success();
test_env.add_config("revsets.sign = '@'");
work_dir.run_jj(["sign"]).success();
let output = work_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r"
@ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 72a53d81 [✓︎]
│ (empty) (no description set)
○ qpvuntsm test.user@example.com 2001-02-03 08:05:08 401ea16f
│ (empty) one
◆ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_sign_with_key() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[ui]
show-cryptographic-signatures = true
[signing]
behavior = "keep"
backend = "test"
key = "some-key"
"#,
);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "one"]).success();
work_dir.run_jj(["commit", "-m", "two"]).success();
work_dir.run_jj(["sign", "-r", "@-"]).success();
work_dir
.run_jj(["sign", "-r", "@--", "--key", "another-key"])
.success();
let output = work_dir.run_jj(["log", "-r", "@-|@--", "-Tbuiltin_log_detailed"]);
insta::assert_snapshot!(output, @r"
○ Commit ID: 810ff318afe002ce54260260e4d4f7071eb476ed
│ Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
│ Author : Test User <test.user@example.com> (2001-02-03 08:05:09)
│ Committer: Test User <test.user@example.com> (2001-02-03 08:05:11)
│ Signature: good signature by test-display some-key
│
│ two
│
○ Commit ID: eec44cafe0dc853b67cc7e14ca4fe3b80d3687f1
│ 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:11)
Signature: good signature by test-display another-key
one
[EOF]
");
}
#[test]
fn test_warn_about_signing_commits_not_authored_by_me() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[ui]
show-cryptographic-signatures = true
[signing]
behavior = "keep"
backend = "test"
"#,
);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "one"]).success();
work_dir.run_jj(["commit", "-m", "two"]).success();
work_dir.run_jj(["commit", "-m", "three"]).success();
work_dir
.run_jj(&[
"desc",
"--author",
"Someone Else <someone@else.com>",
"--no-edit",
"..@-",
])
.success();
let output = work_dir.run_jj(["sign", "-r", "..@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Signed 3 commits:
qpvuntsm 2c0b7924 (empty) one
rlvkpnrz 0e054ee0 (empty) two
kkmpptxz ed55e398 (empty) three
Warning: 3 of these commits are not authored by you
Rebased 1 descendant commits
Working copy (@) now at: zsuskuln 1b3596cb (empty) (no description set)
Parent commit (@-) : kkmpptxz ed55e398 (empty) three
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:12 1b3596cb
│ (empty) (no description set)
○ kkmpptxz someone@else.com 2001-02-03 08:05:12 ed55e398 [✓︎]
│ (empty) three
○ rlvkpnrz someone@else.com 2001-02-03 08:05:12 0e054ee0 [✓︎]
│ (empty) two
○ qpvuntsm someone@else.com 2001-02-03 08:05:12 2c0b7924 [✓︎]
│ (empty) one
◆ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_keep_signatures_in_rebased_descendants() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[ui]
show-cryptographic-signatures = true
[signing]
behavior = "drop"
backend = "test"
"#,
);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "A"]).success();
work_dir.run_jj(["commit", "-m", "B"]).success();
work_dir.run_jj(["desc", "-m", "C"]).success();
let output = work_dir.run_jj(["sign", "-r", "@|@--"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Signed 2 commits:
qpvuntsm 0e149d92 (empty) A
kkmpptxz ab7e21e9 (empty) C
Rebased 1 descendant commits
Working copy (@) now at: kkmpptxz ab7e21e9 (empty) C
Parent commit (@-) : rlvkpnrz 3981b3e4 (empty) B
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r"
@ kkmpptxz test.user@example.com 2001-02-03 08:05:11 ab7e21e9 [✓︎]
│ (empty) C
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:11 3981b3e4
│ (empty) B
○ qpvuntsm test.user@example.com 2001-02-03 08:05:11 0e149d92 [✓︎]
│ (empty) A
◆ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_abort_with_error_if_no_signing_backend_is_configured() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[signing]
backend = "none"
"#,
);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["sign", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No signing backend configured
Hint: For configuring a signing backend, see https://docs.jj-vcs.dev/latest/config/#commit-signing
[EOF]
[exit status: 1]
");
}
#[test]
fn test_unsign() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[ui]
show-cryptographic-signatures = true
[signing]
behavior = "keep"
backend = "test"
"#,
);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "one"]).success();
work_dir.run_jj(["commit", "-m", "two"]).success();
work_dir.run_jj(["commit", "-m", "three"]).success();
work_dir.run_jj(["sign", "-r", "..@"]).success();
let output = work_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:11 be4609e2 [✓︎]
│ (empty) (no description set)
○ kkmpptxz test.user@example.com 2001-02-03 08:05:11 7b6ad8e6 [✓︎]
│ (empty) three
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:11 8dc06170 [✓︎]
│ (empty) two
○ qpvuntsm test.user@example.com 2001-02-03 08:05:11 fbef1f02 [✓︎]
│ (empty) one
◆ zzzzzzzz root() 00000000
[EOF]
");
// Unsign a single commit, resigning the descendant
let output = work_dir.run_jj(["unsign", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Unsigned 1 commits:
kkmpptxz 9efcace6 (empty) three
Rebased 1 descendant commits
Working copy (@) now at: zsuskuln 654e12b9 (empty) (no description set)
Parent commit (@-) : kkmpptxz 9efcace6 (empty) three
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:13 654e12b9 [✓︎]
│ (empty) (no description set)
○ kkmpptxz test.user@example.com 2001-02-03 08:05:13 9efcace6
│ (empty) three
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:11 8dc06170 [✓︎]
│ (empty) two
○ qpvuntsm test.user@example.com 2001-02-03 08:05:11 fbef1f02 [✓︎]
│ (empty) one
◆ zzzzzzzz root() 00000000
[EOF]
");
// Unsign multiple commits, with both signed and unsigned descendants
let output = work_dir.run_jj(["unsign", "-r", "..@--"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Unsigned 2 commits:
qpvuntsm d265d645 (empty) one
rlvkpnrz 6e8ced57 (empty) two
Rebased 2 descendant commits
Working copy (@) now at: zsuskuln ad24007a (empty) (no description set)
Parent commit (@-) : kkmpptxz df10e25c (empty) three
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:15 ad24007a [✓︎]
│ (empty) (no description set)
○ kkmpptxz test.user@example.com 2001-02-03 08:05:15 df10e25c
│ (empty) three
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:15 6e8ced57
│ (empty) two
○ qpvuntsm test.user@example.com 2001-02-03 08:05:15 d265d645
│ (empty) one
◆ zzzzzzzz root() 00000000
[EOF]
");
// Unsigning nothing is a valid no-op.
let output = work_dir.run_jj(["unsign", "-r", "none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
}
#[test]
fn test_warn_about_unsigning_commits_not_authored_by_me() {
let test_env = TestEnvironment::default();
test_env.add_config(
r#"
[ui]
show-cryptographic-signatures = true
[signing]
behavior = "keep"
backend = "test"
"#,
);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "one"]).success();
work_dir.run_jj(["commit", "-m", "two"]).success();
work_dir.run_jj(["commit", "-m", "three"]).success();
work_dir.run_jj(["sign", "-r", "..@"]).success();
let run_jj_as_someone_else = |args: &[&str]| {
let output = work_dir.run_jj_with(|cmd| {
cmd.env("JJ_USER", "Someone Else")
.env("JJ_EMAIL", "someone@else.com")
.args(args)
});
(output.stdout, output.stderr)
};
let (_, stderr) = run_jj_as_someone_else(&["unsign", "-r", "..@"]);
insta::assert_snapshot!(stderr, @r"
Unsigned 4 commits:
qpvuntsm 4430b844 (empty) one
rlvkpnrz 65d9cdf7 (empty) two
kkmpptxz f6eb4a7e (empty) three
zsuskuln 0fda7ce2 (empty) (no description set)
Warning: 4 of these commits are not authored by you
Working copy (@) now at: zsuskuln 0fda7ce2 (empty) (no description set)
Parent commit (@-) : kkmpptxz f6eb4a7e (empty) three
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:12 0fda7ce2
│ (empty) (no description set)
○ kkmpptxz test.user@example.com 2001-02-03 08:05:12 f6eb4a7e
│ (empty) three
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:12 65d9cdf7
│ (empty) two
○ qpvuntsm test.user@example.com 2001-02-03 08:05:12 4430b844
│ (empty) one
◆ zzzzzzzz root() 00000000
[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_sparse_command.rs | cli/tests/test_sparse_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::io::Write as _;
use crate::common::TestEnvironment;
#[test]
fn test_sparse_manage_patterns() {
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");
// Write some files to the working copy
work_dir.write_file("file1", "contents");
work_dir.write_file("file2", "contents");
work_dir.write_file("file3", "contents");
// By default, all files are tracked
let output = work_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
.
[EOF]
");
// Can stop tracking all files
let output = work_dir.run_jj(["sparse", "set", "--remove", "."]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Added 0 files, modified 0 files, removed 3 files
[EOF]
");
// The list is now empty
let output = work_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @"");
// They're removed from the working copy
assert!(!work_dir.root().join("file1").exists());
assert!(!work_dir.root().join("file2").exists());
assert!(!work_dir.root().join("file3").exists());
// But they're still in the commit
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output, @r"
file1
file2
file3
[EOF]
");
// Run commands in sub directory to ensure that patterns are parsed as
// workspace-relative paths, not cwd-relative ones.
let sub_dir = work_dir.create_dir("sub");
// Not a workspace-relative path
let output = sub_dir.run_jj(["sparse", "set", "--add=../file2"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
error: invalid value '../file2' for '--add <ADD>': Invalid component ".." in repo-relative path "../file2"
For more information, try '--help'.
[EOF]
[exit status: 2]
"#);
// Can `--add` a few files
let output = sub_dir.run_jj(["sparse", "set", "--add", "file2", "--add", "file3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Added 2 files, modified 0 files, removed 0 files
[EOF]
");
let output = sub_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
file2
file3
[EOF]
");
assert!(!work_dir.root().join("file1").exists());
assert!(work_dir.root().join("file2").exists());
assert!(work_dir.root().join("file3").exists());
// Can combine `--add` and `--remove`
let output = sub_dir.run_jj([
"sparse", "set", "--add", "file1", "--remove", "file2", "--remove", "file3",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Added 1 files, modified 0 files, removed 2 files
[EOF]
");
let output = sub_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
file1
[EOF]
");
assert!(work_dir.root().join("file1").exists());
assert!(!work_dir.root().join("file2").exists());
assert!(!work_dir.root().join("file3").exists());
// Can use `--clear` and `--add`
let output = sub_dir.run_jj(["sparse", "set", "--clear", "--add", "file2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Added 1 files, modified 0 files, removed 1 files
[EOF]
");
let output = sub_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
file2
[EOF]
");
assert!(!work_dir.root().join("file1").exists());
assert!(work_dir.root().join("file2").exists());
assert!(!work_dir.root().join("file3").exists());
// Can reset back to all files
let output = sub_dir.run_jj(["sparse", "reset"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Added 2 files, modified 0 files, removed 0 files
[EOF]
");
let output = sub_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
.
[EOF]
");
assert!(work_dir.root().join("file1").exists());
assert!(work_dir.root().join("file2").exists());
assert!(work_dir.root().join("file3").exists());
// Can edit with editor
let edit_patterns = |patterns: &[&str]| {
let mut file = std::fs::File::create(&edit_script).unwrap();
file.write_all(b"dump patterns0\0write\n").unwrap();
for pattern in patterns {
file.write_all(pattern.as_bytes()).unwrap();
file.write_all(b"\n").unwrap();
}
};
let read_patterns = || std::fs::read_to_string(test_env.env_root().join("patterns0")).unwrap();
edit_patterns(&["file1"]);
let output = sub_dir.run_jj(["sparse", "edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Added 0 files, modified 0 files, removed 2 files
[EOF]
");
insta::assert_snapshot!(read_patterns(), @".");
let output = sub_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
file1
[EOF]
");
// Can edit with multiple files
edit_patterns(&["file3", "file2", "file3"]);
let output = sub_dir.run_jj(["sparse", "edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Added 2 files, modified 0 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(read_patterns(), @"file1");
let output = sub_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
file2
file3
[EOF]
");
// Invalid paths are rejected
edit_patterns(&["./file1"]);
let output = sub_dir.run_jj(["sparse", "edit"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Failed to parse sparse pattern: ./file1
Caused by: Invalid component "." in repo-relative path "./file1"
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_sparse_editor_avoids_unc() {
use std::path::PathBuf;
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(["sparse", "edit"]).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));
}
| 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_simplify_parents_command.rs | cli/tests/test_simplify_parents_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 test_case::test_case;
use crate::common::TestEnvironment;
use crate::common::create_commit;
#[test]
fn test_simplify_parents_no_commits() {
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(["simplify-parents", "-r", "root() ~ root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
}
#[test]
fn test_simplify_parents_immutable() {
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(["simplify-parents", "-r", "root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The root commit 000000000000 is immutable
[EOF]
[exit status: 1]
");
}
#[test]
fn test_simplify_parents_no_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(&work_dir, "a", &["root()"]);
create_commit(&work_dir, "b", &["a"]);
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ b
○ a
◆
[EOF]
");
let output = work_dir.run_jj(["simplify-parents", "-s", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ b
○ a
◆
[EOF]
");
}
#[test]
fn test_simplify_parents_no_change_diamond() {
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", &["root()"]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["a"]);
create_commit(&work_dir, "d", &["b", "c"]);
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ d
├─╮
│ ○ c
○ │ b
├─╯
○ a
◆
[EOF]
");
let output = work_dir.run_jj(["simplify-parents", "-r", "all() ~ root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ d
├─╮
│ ○ c
○ │ b
├─╯
○ a
◆
[EOF]
");
}
#[test_case(&["simplify-parents", "-r", "@", "-r", "@-"] ; "revisions")]
#[test_case(&["simplify-parents", "-s", "@-"] ; "sources")]
fn test_simplify_parents_redundant_parent(args: &[&str]) {
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", &["root()"]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["a", "b"]);
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r"
@ c
├─╮
│ ○ b
├─╯
○ a
◆
[EOF]
");
}
let output = work_dir.run_jj(args);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r"
------- stderr -------
Removed 1 edges from 1 out of 3 commits.
Working copy (@) now at: royxmykx 265f0407 c | c
Parent commit (@-) : zsuskuln 123b4d91 b | b
[EOF]
");
}
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r"
@ c
○ b
○ a
◆
[EOF]
");
}
}
#[test]
fn test_simplify_parents_multiple_redundant_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(&work_dir, "a", &["root()"]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["a", "b"]);
create_commit(&work_dir, "d", &["c"]);
create_commit(&work_dir, "e", &["d"]);
create_commit(&work_dir, "f", &["d", "e"]);
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ f
├─╮
│ ○ e
├─╯
○ d
○ c
├─╮
│ ○ b
├─╯
○ a
◆
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// Test with `-r`.
let output = work_dir.run_jj(["simplify-parents", "-r", "c", "-r", "f"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Removed 2 edges from 2 out of 2 commits.
Rebased 2 descendant commits
Working copy (@) now at: kmkuslsw 5ad764e9 f | f
Parent commit (@-) : znkkpsqq 9102487c e | e
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ f
○ e
○ d
○ c
○ b
○ a
◆
[EOF]
");
// Test with `-s`.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["simplify-parents", "-s", "c"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Removed 2 edges from 2 out of 4 commits.
Rebased 2 descendant commits
Working copy (@) now at: kmkuslsw 2b2c1c63 f | f
Parent commit (@-) : znkkpsqq 9142e3bb e | e
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ f
○ e
○ d
○ c
○ b
○ a
◆
[EOF]
");
}
#[test]
fn test_simplify_parents_no_args() {
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", &["root()"]);
create_commit(&work_dir, "b", &["a"]);
create_commit(&work_dir, "c", &["a", "b"]);
create_commit(&work_dir, "d", &["c"]);
create_commit(&work_dir, "e", &["d"]);
create_commit(&work_dir, "f", &["d", "e"]);
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ f
├─╮
│ ○ e
├─╯
○ d
○ c
├─╮
│ ○ b
├─╯
○ a
◆
[EOF]
");
let setup_opid = work_dir.current_operation_id();
let output = work_dir.run_jj(["simplify-parents"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Removed 2 edges from 2 out of 6 commits.
Rebased 2 descendant commits
Working copy (@) now at: kmkuslsw 5ad764e9 f | f
Parent commit (@-) : znkkpsqq 9102487c e | e
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ f
○ e
○ d
○ c
○ b
○ a
◆
[EOF]
");
// Test with custom `revsets.simplify-parents`.
work_dir.run_jj(["op", "restore", &setup_opid]).success();
test_env.add_config(r#"revsets.simplify-parents = "d::""#);
let output = work_dir.run_jj(["simplify-parents"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Removed 1 edges from 1 out of 3 commits.
Working copy (@) now at: kmkuslsw 1180d0f5 f | f
Parent commit (@-) : znkkpsqq 009aef72 e | e
[EOF]
");
let output = work_dir.run_jj(["log", "-r", "all()", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ f
○ e
○ d
○ c
├─╮
│ ○ b
├─╯
○ a
◆
[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_restore_command.rs | cli/tests/test_restore_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_with_files;
#[test]
fn test_restore() {
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", "a\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file2", "b\n");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.write_file("file2", "c\n");
work_dir.write_file("file3", "c\n");
work_dir.run_jj(["debug", "snapshot"]).success();
let setup_opid = work_dir.current_operation_id();
// There is no `-r` argument
let output = work_dir.run_jj(["restore", "-r=@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: `jj restore` does not have a `--revision`/`-r` option.
Hint: To modify the current revision, use `--from`.
Hint: To undo changes in a revision compared to its parents, use `--changes-in`.
[EOF]
[exit status: 1]
");
// Restores from parent by default
let output = work_dir.run_jj(["restore"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz ff7ef1df (empty) (no description set)
Parent commit (@-) : rlvkpnrz 1d3e40a3 (no description set)
Added 1 files, modified 1 files, removed 1 files
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @"");
// Can restore another revision from its parents
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["diff", "-s", "-r=@-"]);
insta::assert_snapshot!(output, @r"
A file2
[EOF]
");
let output = work_dir.run_jj(["restore", "-c=@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: kkmpptxz 7f135b03 (conflict) (no description set)
Parent commit (@-) : rlvkpnrz 67841e01 (empty) (no description set)
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file2 2-sided conflict including 1 deletion
New conflicts appeared in 1 commits:
kkmpptxz 7f135b03 (conflict) (no description set)
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new kkmpptxz
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(["diff", "-s", "-r=@-"]);
insta::assert_snapshot!(output, @"");
// Can restore this revision from another revision
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["restore", "--from", "@--"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 3beda426 (no description set)
Parent commit (@-) : rlvkpnrz 1d3e40a3 (no description set)
Added 1 files, modified 0 files, removed 2 files
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @r"
D file2
[EOF]
");
// Can restore into other revision
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["restore", "--into", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: kkmpptxz 5edd8125 (empty) (no description set)
Parent commit (@-) : rlvkpnrz e01fe0b9 (no description set)
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["diff", "-s", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
D file1
A file2
A file3
[EOF]
");
// Can combine `--from` and `--into`
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["restore", "--from", "@", "--into", "@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: kkmpptxz 9807d79b (empty) (no description set)
Parent commit (@-) : rlvkpnrz f3774db8 (no description set)
[EOF]
");
let output = work_dir.run_jj(["diff", "-s"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["diff", "-s", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
D file1
A file2
A file3
[EOF]
");
// Can restore only specified paths
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["restore", "file2", "file3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 08b04134 (no description set)
Parent commit (@-) : rlvkpnrz 1d3e40a3 (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]
");
// The output filtered to a non-existent file should display a warning.
let output = work_dir.run_jj(["restore", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
Nothing changed.
[EOF]
");
}
// Much of this test is copied from test_resolve_command
#[test]
fn test_restore_conflicted_merge() {
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, "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.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
"#);
// Overwrite the file...
work_dir.write_file("file", "resolution");
insta::assert_snapshot!(work_dir.run_jj(["diff"]), @r#"
Resolved conflict in file:
1 : <<<<<<< conflict 1 of 1
2 : %%%%%%% diff from: rlvkpnrz 1792382a "base"
3 : \\\\\\\ to: zsuskuln 45537d53 "a"
4 : -base
5 : +a
6 : +++++++ royxmykx 89d1b299 "b"
7 : b
8 : >>>>>>> conflict 1 of 1 ends
1: resolution
[EOF]
"#);
// ...and restore it back again.
let output = work_dir.run_jj(["restore", "file"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 45d86d72 conflict | (conflict) (empty) 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
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @r"
<<<<<<< conflict 1 of 1
%%%%%%% diff from base to side #1
-base
+a
+++++++ side #2
b
>>>>>>> conflict 1 of 1 ends
");
let output = work_dir.run_jj(["diff"]);
insta::assert_snapshot!(output, @"");
// The same, but without the `file` argument. Overwrite the file...
work_dir.write_file("file", "resolution");
insta::assert_snapshot!(work_dir.run_jj(["diff"]), @r#"
Resolved conflict in file:
1 : <<<<<<< conflict 1 of 1
2 : %%%%%%% diff from: rlvkpnrz 1792382a "base"
3 : \\\\\\\ to: zsuskuln 45537d53 "a"
4 : -base
5 : +a
6 : +++++++ royxmykx 89d1b299 "b"
7 : b
8 : >>>>>>> conflict 1 of 1 ends
1: resolution
[EOF]
"#);
// ... and restore it back again.
let output = work_dir.run_jj(["restore"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 60d86a33 conflict | (conflict) (empty) 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
[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
"#);
}
#[test]
fn test_restore_restore_descendants() {
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"), ("file2", "b\n")],
);
create_commit_with_files(&work_dir, "ab", &["a", "b"], &[("file", "ab\n")]);
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ ab
├─╮
│ ○ b
○ │ a
├─╯
○ base
◆
[EOF]
");
insta::assert_snapshot!(work_dir.read_file("file"), @"ab");
// Commit "b" was not supposed to modify "file", restore it from its parent
// while preserving its child commit content.
let output = work_dir.run_jj(["restore", "-c", "b", "file", "--restore-descendants"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits (while preserving their content)
Working copy (@) now at: vruxwmqv 14c0c336 ab | ab
Parent commit (@-) : zsuskuln 45537d53 a | a
Parent commit (@-) : royxmykx 5fd3f8c5 b | b
[EOF]
");
// Check that "a", "b", and "ab" have their expected content by diffing them.
// "ab" must have kept its content.
insta::assert_snapshot!(work_dir.run_jj(["diff", "--from=a", "--to=ab", "--git"]), @r"
diff --git a/file b/file
index 7898192261..81bf396956 100644
--- a/file
+++ b/file
@@ -1,1 +1,1 @@
-a
+ab
diff --git a/file2 b/file2
new file mode 100644
index 0000000000..6178079822
--- /dev/null
+++ b/file2
@@ -0,0 +1,1 @@
+b
[EOF]
");
insta::assert_snapshot!(work_dir.run_jj(["diff", "--from=b", "--to=ab", "--git"]), @r"
diff --git a/file b/file
index df967b96a5..81bf396956 100644
--- a/file
+++ b/file
@@ -1,1 +1,1 @@
-base
+ab
[EOF]
");
}
#[test]
fn test_restore_interactive() {
let mut test_env = TestEnvironment::default();
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");
create_commit_with_files(&work_dir, "a", &[], &[("file1", "a1\n"), ("file2", "a2\n")]);
create_commit_with_files(
&work_dir,
"b",
&["a"],
&[("file1", "b1\n"), ("file2", "b2\n"), ("file3", "b3\n")],
);
let output = work_dir.run_jj(["log", "--summary"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:11 b 38153274
│ b
│ M file1
│ M file2
│ A file3
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a 6c8d5b87
│ a
│ A file1
│ A file2
◆ zzzzzzzz root() 00000000
[EOF]
");
let setup_opid = work_dir.current_operation_id();
let diff_script = [
"files-before file1 file2 file3",
"files-after JJ-INSTRUCTIONS file1 file2",
"reset file2",
"dump JJ-INSTRUCTIONS instrs",
]
.join("\0");
std::fs::write(diff_editor, diff_script).unwrap();
// Restore file1 and file3
let output = work_dir.run_jj(["restore", "-i", "--from=@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: zsuskuln 7cd0a341 b | b
Parent commit (@-) : rlvkpnrz 6c8d5b87 a | a
Added 0 files, modified 1 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("instrs")).unwrap(), @r"
You are restoring changes from: rlvkpnrz 6c8d5b87 a | a
to commit: zsuskuln 38153274 b | b
The diff initially shows all changes restored. Adjust the right side until it
shows the contents you want for the destination commit.
");
let output = work_dir.run_jj(["log", "--summary"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:13 b 7cd0a341
│ b
│ M file2
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a 6c8d5b87
│ a
│ A file1
│ A file2
◆ zzzzzzzz root() 00000000
[EOF]
");
// Try again with --tool, which should imply --interactive
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["restore", "--tool=fake-diff-editor"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: zsuskuln 0f1263f5 b | b
Parent commit (@-) : rlvkpnrz 6c8d5b87 a | a
Added 0 files, modified 1 files, removed 1 files
[EOF]
");
let output = work_dir.run_jj(["log", "--summary"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:16 b 0f1263f5
│ b
│ M file2
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a 6c8d5b87
│ a
│ A file1
│ A file2
◆ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_restore_interactive_merge() {
let mut test_env = TestEnvironment::default();
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");
create_commit_with_files(&work_dir, "a", &[], &[("file1", "a1\n")]);
create_commit_with_files(&work_dir, "b", &[], &[("file2", "b1\n")]);
create_commit_with_files(
&work_dir,
"c",
&["a", "b"],
&[("file1", "c1\n"), ("file2", "c2\n"), ("file3", "c3\n")],
);
let output = work_dir.run_jj(["log", "--summary"]);
insta::assert_snapshot!(output, @r"
@ royxmykx test.user@example.com 2001-02-03 08:05:13 c e37470c3
├─╮ c
│ │ M file1
│ │ M file2
│ │ A file3
│ ○ zsuskuln test.user@example.com 2001-02-03 08:05:11 b ca7e57cd
│ │ b
│ │ A file2
○ │ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a 78059355
├─╯ a
│ A file1
◆ zzzzzzzz root() 00000000
[EOF]
");
let diff_script = [
"files-before file1 file2 file3",
"files-after JJ-INSTRUCTIONS file1 file2",
"reset file2",
"dump JJ-INSTRUCTIONS instrs",
]
.join("\0");
std::fs::write(diff_editor, diff_script).unwrap();
// Restore file1 and file3
let output = work_dir.run_jj(["restore", "-i"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: royxmykx 196af27b c | c
Parent commit (@-) : rlvkpnrz 78059355 a | a
Parent commit (@-) : zsuskuln ca7e57cd b | b
Added 0 files, modified 1 files, removed 1 files
[EOF]
");
insta::assert_snapshot!(
std::fs::read_to_string(test_env.env_root().join("instrs")).unwrap(), @r"
You are restoring changes from: rlvkpnrz 78059355 a | a
zsuskuln ca7e57cd b | b
to commit: royxmykx e37470c3 c | c
The diff initially shows all changes restored. Adjust the right side until it
shows the contents you want for the destination commit.
");
let output = work_dir.run_jj(["log", "--summary"]);
insta::assert_snapshot!(output, @r"
@ royxmykx test.user@example.com 2001-02-03 08:05:15 c 196af27b
├─╮ c
│ │ M file2
│ ○ zsuskuln test.user@example.com 2001-02-03 08:05:11 b ca7e57cd
│ │ b
│ │ A file2
○ │ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a 78059355
├─╯ a
│ A file1
◆ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_restore_interactive_with_paths() {
let mut test_env = TestEnvironment::default();
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");
create_commit_with_files(&work_dir, "a", &[], &[("file1", "a1\n"), ("file2", "a2\n")]);
create_commit_with_files(
&work_dir,
"b",
&["a"],
&[("file1", "b1\n"), ("file2", "b2\n"), ("file3", "b3\n")],
);
let output = work_dir.run_jj(["log", "--summary"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:11 b 38153274
│ b
│ M file1
│ M file2
│ A file3
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a 6c8d5b87
│ a
│ A file1
│ A file2
◆ zzzzzzzz root() 00000000
[EOF]
");
let diff_script = [
"files-before file1 file2",
"files-after JJ-INSTRUCTIONS file1 file2",
"reset file2",
]
.join("\0");
std::fs::write(diff_editor, diff_script).unwrap();
// Restore file1 (file2 is reset by interactive editor)
let output = work_dir.run_jj(["restore", "-i", "file1", "file2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: zsuskuln 8b2f997d b | b
Parent commit (@-) : rlvkpnrz 6c8d5b87 a | a
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
let output = work_dir.run_jj(["log", "--summary"]);
insta::assert_snapshot!(output, @r"
@ zsuskuln test.user@example.com 2001-02-03 08:05:13 b 8b2f997d
│ b
│ M file2
│ A file3
○ rlvkpnrz test.user@example.com 2001-02-03 08:05:09 a 6c8d5b87
│ a
│ A file1
│ A file2
◆ zzzzzzzz root() 00000000
[EOF]
");
}
#[must_use]
fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
work_dir.run_jj(["log", "-T", "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/tests/test_file_list_command.rs | cli/tests/test_file_list_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 indoc::indoc;
use crate::common::TestEnvironment;
#[test]
fn test_file_list() {
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("dir/file", "content1");
work_dir.write_file("exec-file", "content1");
work_dir.write_file("conflict-exec-file", "content1");
work_dir.write_file("conflict-file", "content1");
work_dir
.run_jj(["file", "chmod", "x", "exec-file", "conflict-exec-file"])
.success();
work_dir.run_jj(["new", "root()"]).success();
work_dir.write_file("conflict-exec-file", "content2");
work_dir.write_file("conflict-file", "content2");
work_dir
.run_jj(["file", "chmod", "x", "conflict-exec-file"])
.success();
work_dir.run_jj(["new", "visible_heads()"]).success();
// Lists all files in the current revision by default
let output = work_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output.normalize_backslash(), @"
conflict-exec-file
conflict-file
dir/file
exec-file
[EOF]
");
// Can list with templates
let template = indoc! {r#"
separate(" ",
path,
"[" ++ file_type ++ "]",
"conflict=" ++ conflict,
"executable=" ++ executable,
) ++ "\n"
"#};
let output = work_dir.run_jj(["file", "list", "-T", template]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
conflict-exec-file [conflict] conflict=true executable=true
conflict-file [conflict] conflict=true executable=false
dir/file [file] conflict=false executable=false
exec-file [file] conflict=false executable=true
[EOF]
");
// Can list files in another revision
let output = work_dir.run_jj(["file", "list", "-r=first_parent(@)"]);
insta::assert_snapshot!(output.normalize_backslash(), @"
conflict-exec-file
conflict-file
[EOF]
");
// Can filter by path
let output = work_dir.run_jj(["file", "list", "dir"]);
insta::assert_snapshot!(output.normalize_backslash(), @"
dir/file
[EOF]
");
// Warning if path doesn't exist
let output = work_dir.run_jj(["file", "list", "dir", "file3"]);
insta::assert_snapshot!(output.normalize_backslash(), @"
dir/file
[EOF]
------- stderr -------
Warning: No matching entries for paths: file3
[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_repo_change_report.rs | cli/tests/test_repo_change_report.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::TestEnvironment;
#[test]
fn test_report_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("file", "A\n");
work_dir.run_jj(["commit", "-m=A"]).success();
work_dir.write_file("file", "B\n");
work_dir.run_jj(["commit", "-m=B"]).success();
work_dir.write_file("file", "C\n");
work_dir.run_jj(["commit", "-m=C"]).success();
let output = work_dir.run_jj(["rebase", "-s=subject(B)", "-d=root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: zsuskuln 0798f940 (conflict) (empty) (no description set)
Parent commit (@-) : kkmpptxz f18bc634 (conflict) C
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict including 1 deletion
New conflicts appeared in 2 commits:
kkmpptxz f18bc634 (conflict) C
rlvkpnrz 3ec72c59 (conflict) B
Hint: To resolve the conflicts, start by creating a commit on top of
the first conflicted commit:
jj new rlvkpnrz
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(["rebase", "-d=subject(A)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: zsuskuln bad741db (empty) (no description set)
Parent commit (@-) : kkmpptxz cec3d034 C
Added 0 files, modified 1 files, removed 0 files
Existing conflicts were resolved or abandoned from 2 commits.
[EOF]
");
// Can get hint about multiple root commits
let output = work_dir.run_jj(["rebase", "-r=subject(B)", "-d=root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Rebased 2 descendant commits
Working copy (@) now at: zsuskuln 33a4249e (conflict) (empty) (no description set)
Parent commit (@-) : kkmpptxz b7d2d9ac (conflict) C
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 2 commits:
kkmpptxz b7d2d9ac (conflict) C
rlvkpnrz d4d3dc60 (conflict) B
Hint: To resolve the conflicts, start by creating a commit on top of
one of the first conflicted commits:
jj new kkmpptxz
jj new rlvkpnrz
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]
");
// Resolve one of the conflicts by (mostly) following the instructions
let output = work_dir.run_jj(["new", "rlvkpnrzqnoo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv bd3920e6 (conflict) (empty) (no description set)
Parent commit (@-) : rlvkpnrz d4d3dc60 (conflict) B
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict including 1 deletion
[EOF]
");
work_dir.write_file("file", "resolved\n");
let output = work_dir.run_jj(["squash"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: yostqsxw 350a6e50 (empty) (no description set)
Parent commit (@-) : rlvkpnrz 1aa1004b B
Existing conflicts were resolved or abandoned from 1 commits.
[EOF]
");
}
#[test]
fn test_report_conflicts_with_divergent_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(["describe", "-m=A"]).success();
work_dir.write_file("file", "A\n");
work_dir.run_jj(["new", "-m=B"]).success();
work_dir.write_file("file", "B\n");
work_dir.run_jj(["new", "-m=C"]).success();
work_dir.write_file("file", "C\n");
work_dir.run_jj(["describe", "-m=C2"]).success();
work_dir
.run_jj(["describe", "-m=C3", "--at-op=@-"])
.success();
let output = work_dir.run_jj(["rebase", "-s=subject(B)", "-d=root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Concurrent modification detected, resolving automatically.
Rebased 3 commits to destination
Working copy (@) now at: zsuskuln/1 8d399a54 (divergent) (conflict) C2
Parent commit (@-) : kkmpptxz 1c19b9e0 (conflict) B
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict including 1 deletion
New conflicts appeared in 3 commits:
zsuskuln/0 b04ca335 (divergent) (conflict) C3
zsuskuln/1 8d399a54 (divergent) (conflict) C2
kkmpptxz 1c19b9e0 (conflict) B
Hint: To resolve the conflicts, start by creating a commit on top of
the first conflicted commit:
jj new kkmpptxz
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(["rebase", "-d=subject(A)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: zsuskuln/1 27ef05d9 (divergent) C2
Parent commit (@-) : kkmpptxz 9039ed49 B
Added 0 files, modified 1 files, removed 0 files
Existing conflicts were resolved or abandoned from 3 commits.
[EOF]
");
// Same thing when rebasing the divergent commits one at a time
let output = work_dir.run_jj(["rebase", "-s=subject(C2)", "-d=root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Working copy (@) now at: zsuskuln/0 b536e208 (divergent) (conflict) C2
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict including 1 deletion
New conflicts appeared in 1 commits:
zsuskuln/0 b536e208 (divergent) (conflict) C2
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new zsuskuln/0
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(["rebase", "-s=subject(C3)", "-d=root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
New conflicts appeared in 1 commits:
zsuskuln/0 2015a3ed (divergent) (conflict) C3
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new zsuskuln/0
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(["rebase", "-s=subject(C2)", "-d=subject(B)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Working copy (@) now at: zsuskuln/0 3fcf2fd2 (divergent) C2
Parent commit (@-) : kkmpptxz 9039ed49 B
Added 0 files, modified 1 files, removed 0 files
Existing conflicts were resolved or abandoned from 1 commits.
[EOF]
");
let output = work_dir.run_jj(["rebase", "-s=subject(C3)", "-d=subject(B)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Existing conflicts were resolved or abandoned from 1 commits.
[EOF]
");
}
#[test]
fn test_report_conflicts_with_resolving_conflicts_hint_disabled() {
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", "A\n");
work_dir.run_jj(["commit", "-m=A"]).success();
work_dir.write_file("file", "B\n");
work_dir.run_jj(["commit", "-m=B"]).success();
work_dir.write_file("file", "C\n");
work_dir.run_jj(["commit", "-m=C"]).success();
let output = work_dir.run_jj([
"rebase",
"-s=subject(B)",
"-d=root()",
"--config=hints.resolving-conflicts=false",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 3 commits to destination
Working copy (@) now at: zsuskuln 0798f940 (conflict) (empty) (no description set)
Parent commit (@-) : kkmpptxz f18bc634 (conflict) C
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file 2-sided conflict including 1 deletion
New conflicts appeared in 2 commits:
kkmpptxz f18bc634 (conflict) C
rlvkpnrz 3ec72c59 (conflict) B
[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_next_prev_commands.rs | cli/tests/test_next_prev_commands.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::force_interactive;
#[test]
fn test_next_simple() {
// Move from first => second.
// first
// |
// second
// |
// third
//
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Create a simple linear history, which we'll traverse.
work_dir.run_jj(["commit", "-m", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr
○ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
// Move to `first`
work_dir.run_jj(["new", "@--"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr
│ ○ kkmpptxzrspx third
├─╯
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["next"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 01f06d39 (empty) (no description set)
Parent commit (@-) : kkmpptxz 7576de42 (empty) third
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ vruxwmqvtpmx
○ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_next_multiple() {
// Move from first => fourth.
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["commit", "-m", "fourth"]).success();
work_dir.run_jj(["new", "@---"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr
│ ○ zsuskulnrvyr fourth
│ ○ kkmpptxzrspx third
├─╯
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
// We should now be the child of the fourth commit.
let output = work_dir.run_jj(["next", "2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv a53dd783 (empty) (no description set)
Parent commit (@-) : zsuskuln c5025ce1 (empty) fourth
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ vruxwmqvtpmx
○ zsuskulnrvyr fourth
○ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_prev_simple() {
// Move @- from third to second.
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr
○ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["prev"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: royxmykx 539f176b (empty) (no description set)
Parent commit (@-) : rlvkpnrz 9439bf06 (empty) second
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr
│ ○ kkmpptxzrspx third
├─╯
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_prev_multiple_without_root() {
// Move @- from fourth to second.
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["commit", "-m", "fourth"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ mzvwutvlkqwt
○ zsuskulnrvyr fourth
○ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["prev", "2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: yqosqzyt a4d3accb (empty) (no description set)
Parent commit (@-) : rlvkpnrz 9439bf06 (empty) second
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ yqosqzytrlsw
│ ○ zsuskulnrvyr fourth
│ ○ kkmpptxzrspx third
├─╯
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_next_exceeding_history() {
// Try to step beyond the current repos history.
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["new", "-r", "@--"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ mzvwutvlkqwt
│ ○ kkmpptxzrspx third
├─╯
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
// `jj next` beyond existing history fails.
let output = work_dir.run_jj(["next", "3"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No other descendant found 3 commit(s) forward from the working copy parent(s)
Hint: Working copy parent: rlvkpnrz 9439bf06 (empty) second
[EOF]
[exit status: 1]
");
}
// The working copy commit is a child of a "fork" with two children on each
// bookmark.
#[test]
fn test_next_parent_has_multiple_descendants() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Setup.
work_dir.run_jj(["desc", "-m", "1"]).success();
work_dir.run_jj(["new", "-m", "2"]).success();
work_dir.run_jj(["new", "root()", "-m", "3"]).success();
work_dir.run_jj(["new", "-m", "4"]).success();
work_dir.run_jj(["edit", "subject(3)"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ mzvwutvlkqwt 4
@ zsuskulnrvyr 3
│ ○ kkmpptxzrspx 2
│ ○ qpvuntsmwlqt 1
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["next", "--edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: mzvwutvl e5543950 (empty) 4
Parent commit (@-) : zsuskuln 83df6e43 (empty) 3
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ mzvwutvlkqwt 4
○ zsuskulnrvyr 3
│ ○ kkmpptxzrspx 2
│ ○ qpvuntsmwlqt 1
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_next_with_merge_commit_parent() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Setup.
work_dir.run_jj(["desc", "-m", "1"]).success();
work_dir.run_jj(["new", "root()", "-m", "2"]).success();
work_dir
.run_jj(["new", "subject(1)", "subject(2)", "-m", "3"])
.success();
work_dir.run_jj(["new", "-m", "4"]).success();
work_dir.run_jj(["prev", "0"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr
│ ○ mzvwutvlkqwt 4
├─╯
○ zsuskulnrvyr 3
├─╮
│ ○ kkmpptxzrspx 2
○ │ qpvuntsmwlqt 1
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["next"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv 7a09c355 (empty) (no description set)
Parent commit (@-) : mzvwutvl f02c921e (empty) 4
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ vruxwmqvtpmx
○ mzvwutvlkqwt 4
○ zsuskulnrvyr 3
├─╮
│ ○ kkmpptxzrspx 2
○ │ qpvuntsmwlqt 1
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_next_on_merge_commit() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Setup.
work_dir.run_jj(["desc", "-m", "1"]).success();
work_dir.run_jj(["new", "root()", "-m", "2"]).success();
work_dir
.run_jj(["new", "subject(1)", "subject(2)", "-m", "3"])
.success();
work_dir.run_jj(["new", "-m", "4"]).success();
work_dir.run_jj(["edit", "subject(3)"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ mzvwutvlkqwt 4
@ zsuskulnrvyr 3
├─╮
│ ○ kkmpptxzrspx 2
○ │ qpvuntsmwlqt 1
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["next", "--edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: mzvwutvl f02c921e (empty) 4
Parent commit (@-) : zsuskuln d2500577 (empty) 3
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ mzvwutvlkqwt 4
○ zsuskulnrvyr 3
├─╮
│ ○ kkmpptxzrspx 2
○ │ qpvuntsmwlqt 1
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_next_fails_on_bookmarking_children_no_stdin() {
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["new", "@--"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["new", "@--"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr
│ ○ zsuskulnrvyr third
├─╯
│ ○ rlvkpnrzqnoo second
├─╯
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
// Try to advance the working copy commit.
let output = work_dir.run_jj(["next"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
ambiguous next commit, choose one to target:
1: zsuskuln 6fc6af46 (empty) third
2: rlvkpnrz 9439bf06 (empty) second
q: quit the prompt
Error: Cannot prompt for input since the output is not connected to a terminal
[EOF]
[exit status: 1]
");
}
#[test]
fn test_next_fails_on_bookmarking_children_quit_prompt() {
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["new", "@--"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["new", "@--"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr
│ ○ zsuskulnrvyr third
├─╯
│ ○ rlvkpnrzqnoo second
├─╯
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
// Try to advance the working copy commit.
let output = work_dir.run_jj_with(|cmd| force_interactive(cmd).arg("next").write_stdin("q\n"));
insta::assert_snapshot!(output, @r"
------- stderr -------
ambiguous next commit, choose one to target:
1: zsuskuln 6fc6af46 (empty) third
2: rlvkpnrz 9439bf06 (empty) second
q: quit the prompt
enter the index of the commit you want to target: Error: ambiguous target commit
[EOF]
[exit status: 1]
");
}
#[test]
fn test_next_choose_bookmarking_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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["new", "@--"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["new", "@--"]).success();
work_dir.run_jj(["commit", "-m", "fourth"]).success();
work_dir.run_jj(["new", "@--"]).success();
// Advance the working copy commit.
let output = work_dir.run_jj_with(|cmd| force_interactive(cmd).arg("next").write_stdin("2\n"));
insta::assert_snapshot!(output, @r"
------- stderr -------
ambiguous next commit, choose one to target:
1: royxmykx 3522c887 (empty) fourth
2: zsuskuln 6fc6af46 (empty) third
3: rlvkpnrz 9439bf06 (empty) second
q: quit the prompt
enter the index of the commit you want to target: Working copy (@) now at: yostqsxw 683938a4 (empty) (no description set)
Parent commit (@-) : zsuskuln 6fc6af46 (empty) third
[EOF]
");
}
#[test]
fn test_prev_on_merge_commit() {
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(["desc", "-m", "first"]).success();
work_dir.run_jj(["bookmark", "c", "-r@", "left"]).success();
work_dir.run_jj(["new", "root()", "-m", "second"]).success();
work_dir.run_jj(["bookmark", "c", "-r@", "right"]).success();
work_dir.run_jj(["new", "left", "right"]).success();
// Check that the graph looks the way we expect.
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr
├─╮
│ ○ zsuskulnrvyr right second
○ │ qpvuntsmwlqt left first
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
let setup_opid = work_dir.current_operation_id();
let output = work_dir.run_jj(["prev"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: vruxwmqv b64f323d (empty) (no description set)
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj_with(|cmd| {
force_interactive(cmd)
.args(["prev", "--edit"])
.write_stdin("2\n")
});
insta::assert_snapshot!(output, @r"
------- stderr -------
ambiguous prev commit, choose one to target:
1: zsuskuln 22a08bc0 right | (empty) second
2: qpvuntsm 68a50538 left | (empty) first
q: quit the prompt
enter the index of the commit you want to target: Working copy (@) now at: qpvuntsm 68a50538 left | (empty) first
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_prev_on_merge_commit_with_parent_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(["desc", "-m", "x"]).success();
work_dir.run_jj(["new", "root()", "-m", "y"]).success();
work_dir
.run_jj(["new", "subject(x)", "subject(y)", "-m", "z"])
.success();
work_dir.run_jj(["new", "root()", "-m", "1"]).success();
work_dir
.run_jj(["new", "subject(z)", "subject(1)", "-m", "M"])
.success();
// Check that the graph looks the way we expect.
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr M
├─╮
│ ○ mzvwutvlkqwt 1
○ │ zsuskulnrvyr z
├───╮
│ │ ○ kkmpptxzrspx y
│ ├─╯
○ │ qpvuntsmwlqt x
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
let setup_opid = work_dir.current_operation_id();
let output = work_dir.run_jj_with(|cmd| force_interactive(cmd).arg("prev").write_stdin("2\n"));
insta::assert_snapshot!(output, @r"
------- stderr -------
ambiguous prev commit, choose one to target:
1: kkmpptxz ab947132 (empty) y
2: qpvuntsm 007e88d2 (empty) x
3: zzzzzzzz 00000000 (empty) (no description set)
q: quit the prompt
enter the index of the commit you want to target: Working copy (@) now at: vruxwmqv ff8922ba (empty) (no description set)
Parent commit (@-) : qpvuntsm 007e88d2 (empty) x
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj_with(|cmd| {
force_interactive(cmd)
.args(["prev", "--edit"])
.write_stdin("2\n")
});
insta::assert_snapshot!(output, @r"
------- stderr -------
ambiguous prev commit, choose one to target:
1: mzvwutvl 0e8fc48c (empty) 1
2: zsuskuln e7382ca4 (empty) z
q: quit the prompt
enter the index of the commit you want to target: Working copy (@) now at: zsuskuln e7382ca4 (empty) z
Parent commit (@-) : qpvuntsm 007e88d2 (empty) x
Parent commit (@-) : kkmpptxz ab947132 (empty) y
[EOF]
");
}
#[test]
fn test_prev_prompts_on_multiple_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", "first"]).success();
work_dir.run_jj(["new", "@--"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["new", "@--"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
// Create a merge commit, which has two parents.
work_dir.run_jj(["new", "@--+"]).success();
work_dir.run_jj(["commit", "-m", "merge"]).success();
work_dir.run_jj(["commit", "-m", "merge+1"]).success();
// Check that the graph looks the way we expect.
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ yostqsxwqrlt
○ vruxwmqvtpmx merge+1
○ yqosqzytrlsw merge
├─┬─╮
│ │ ○ qpvuntsmwlqt first
│ ○ │ kkmpptxzrspx second
│ ├─╯
○ │ mzvwutvlkqwt third
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
// Move @ backwards.
let output = work_dir.run_jj_with(|cmd| {
force_interactive(cmd)
.args(["prev", "2"])
.write_stdin("3\n")
});
insta::assert_snapshot!(output, @r"
------- stderr -------
ambiguous prev commit, choose one to target:
1: mzvwutvl 5ec63817 (empty) third
2: kkmpptxz e8959fbd (empty) second
3: qpvuntsm 68a50538 (empty) first
q: quit the prompt
enter the index of the commit you want to target: Working copy (@) now at: kpqxywon 5448803a (empty) (no description set)
Parent commit (@-) : qpvuntsm 68a50538 (empty) first
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ kpqxywonksrl
│ ○ vruxwmqvtpmx merge+1
│ ○ yqosqzytrlsw merge
╭─┼─╮
○ │ │ qpvuntsmwlqt first
│ │ ○ kkmpptxzrspx second
├───╯
│ ○ mzvwutvlkqwt third
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
work_dir.run_jj(["next"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ wqnwkozpkust
│ ○ vruxwmqvtpmx merge+1
├─╯
○ yqosqzytrlsw merge
├─┬─╮
│ │ ○ qpvuntsmwlqt first
│ ○ │ kkmpptxzrspx second
│ ├─╯
○ │ mzvwutvlkqwt third
├─╯
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_prev_beyond_root_fails() {
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["commit", "-m", "fourth"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ mzvwutvlkqwt
○ zsuskulnrvyr fourth
○ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
// @- is at "fourth", and there is no parent 5 commits behind it.
let output = work_dir.run_jj(["prev", "5"]);
insta::assert_snapshot!(output,@r"
------- stderr -------
Error: No ancestor found 5 commit(s) back from the working copy parents(s)
Hint: Working copy parent: zsuskuln c5025ce1 (empty) fourth
[EOF]
[exit status: 1]
");
}
#[test]
fn test_prev_editing() {
// Edit the third commit.
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["commit", "-m", "fourth"]).success();
// Edit the "fourth" commit, which becomes the leaf.
work_dir.run_jj(["edit", "@-"]).success();
// Check that the graph looks the way we expect.
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr fourth
○ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["prev", "--edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 7576de42 (empty) third
Parent commit (@-) : rlvkpnrz 9439bf06 (empty) second
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ zsuskulnrvyr fourth
@ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_next_editing() {
// Edit the second commit.
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["commit", "-m", "fourth"]).success();
work_dir.run_jj(["edit", "@---"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ zsuskulnrvyr fourth
○ kkmpptxzrspx third
@ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["next", "--edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 7576de42 (empty) third
Parent commit (@-) : rlvkpnrz 9439bf06 (empty) second
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ zsuskulnrvyr fourth
@ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_prev_conflict() {
// Make the first commit our new 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.write_file("content.txt", "first");
work_dir.run_jj(["commit", "-m", "first"]).success();
work_dir.write_file("content.txt", "second");
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
// Create a conflict in the first commit, where we'll jump to.
work_dir.run_jj(["edit", "subject(first)"]).success();
work_dir.write_file("content.txt", "first+1");
work_dir.run_jj(["new", "subject(third)"]).success();
work_dir.run_jj(["commit", "-m", "fourth"]).success();
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ yqosqzytrlsw conflict
× royxmykxtrkr conflict fourth
× kkmpptxzrspx conflict third
× rlvkpnrzqnoo conflict second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
work_dir.run_jj(["prev", "--conflict"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ yostqsxwqrlt conflict
│ × royxmykxtrkr conflict fourth
├─╯
× kkmpptxzrspx conflict third
× rlvkpnrzqnoo conflict second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_prev_conflict_editing() {
// Edit the third commit.
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", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.write_file("content.txt", "second");
work_dir.run_jj(["commit", "-m", "third"]).success();
// Create a conflict in the third commit, where we'll jump to.
work_dir.run_jj(["edit", "subject(first)"]).success();
work_dir.write_file("content.txt", "first text");
work_dir.run_jj(["new", "subject(third)"]).success();
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr conflict
× kkmpptxzrspx conflict third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
work_dir.run_jj(["prev", "--conflict", "--edit"]).success();
// We now should be editing the third commit.
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ kkmpptxzrspx conflict third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_next_conflict() {
// There is a conflict in the third commit, so after next it should be the new
// parent.
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("content.txt", "first");
work_dir.run_jj(["commit", "-m", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
// Create a conflict in the third commit.
work_dir.write_file("content.txt", "third");
work_dir.run_jj(["commit", "-m", "third"]).success();
work_dir.run_jj(["new", "subject(first)"]).success();
work_dir.write_file("content.txt", "first v2");
work_dir
.run_jj(["squash", "--into", "subject(third)"])
.success();
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ royxmykxtrkr
│ × kkmpptxzrspx conflict third
│ ○ rlvkpnrzqnoo second
├─╯
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
work_dir.run_jj(["next", "--conflict"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ vruxwmqvtpmx conflict
× kkmpptxzrspx conflict third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_next_conflict_editing() {
// There is a conflict in the third commit, so after next it should be our
// 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(["commit", "-m", "first"]).success();
work_dir.write_file("content.txt", "second");
work_dir.run_jj(["commit", "-m", "second"]).success();
// Create a conflict in the third commit.
work_dir.write_file("content.txt", "third");
work_dir.run_jj(["edit", "subject(second)"]).success();
work_dir.write_file("content.txt", "modified second");
work_dir.run_jj(["edit", "@-"]).success();
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
× kkmpptxzrspx conflict
○ rlvkpnrzqnoo second
@ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
work_dir.run_jj(["next", "--conflict", "--edit"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ kkmpptxzrspx conflict
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
}
#[test]
fn test_next_conflict_head() {
// When editing a head with conflicts, `jj next --conflict [--edit]` errors out.
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.write_file("file", "first");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file", "second");
work_dir.run_jj(["abandon", "@-"]).success();
// Test the setup
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ rlvkpnrzqnoo conflict
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["next", "--conflict"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The working copy parent(s) have no other descendants with conflicts
Hint: Working copy parent: zzzzzzzz 00000000 (empty) (no description set)
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["next", "--conflict", "--edit"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The working copy has no descendants with conflicts
Hint: Working copy: rlvkpnrz 3074024b (conflict) (no description set)
[EOF]
[exit status: 1]
");
}
#[test]
fn test_movement_edit_mode_true() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"ui.movement.edit = true"#);
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["commit", "-m", "first"]).success();
work_dir.run_jj(["commit", "-m", "second"]).success();
work_dir.run_jj(["commit", "-m", "third"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ zsuskulnrvyr
○ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
work_dir.run_jj(["prev"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ kkmpptxzrspx third
○ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["prev"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: rlvkpnrz 9439bf06 (empty) second
Parent commit (@-) : qpvuntsm 68a50538 (empty) first
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ kkmpptxzrspx third
@ rlvkpnrzqnoo second
○ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["prev"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: qpvuntsm 68a50538 (empty) first
Parent commit (@-) : zzzzzzzz 00000000 (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
○ kkmpptxzrspx third
○ rlvkpnrzqnoo second
@ qpvuntsmwlqt first
◆ zzzzzzzzzzzz
[EOF]
");
let output = work_dir.run_jj(["prev"]);
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_bookmark_command.rs | cli/tests/test_bookmark_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 testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
fn create_commit_with_refs(
repo: &gix::Repository,
message: &str,
content: &[u8],
ref_names: &[&str],
) {
let git::CommitResult {
tree_id: _,
commit_id,
} = git::add_commit(repo, "refs/heads/dummy", "file", content, message, &[]);
repo.find_reference("dummy").unwrap().delete().unwrap();
for name in ref_names {
repo.reference(
*name,
commit_id,
gix::refs::transaction::PreviousValue::Any,
"log message",
)
.unwrap();
}
}
#[test]
fn test_bookmark_multiple_names() {
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(["bookmark", "create", "-r@", "foo", "bar"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Created 2 bookmarks pointing to qpvuntsm e8849ae1 bar foo | (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bar foo e8849ae12c70
◆ 000000000000
[EOF]
");
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj(["bookmark", "set", "foo", "bar"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Moved 2 bookmarks to zsuskuln 0e555a27 bar foo | (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bar foo 0e555a27ac99
○ e8849ae12c70
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["bookmark", "delete", "foo", "bar", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Deleted 2 bookmarks.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0e555a27ac99
○ e8849ae12c70
◆ 000000000000
[EOF]
");
// Hint should be omitted if -r is specified
let output = work_dir.run_jj(["bookmark", "create", "-r@-", "foo", "bar"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Created 2 bookmarks pointing to qpvuntsm e8849ae1 bar foo | (empty) (no description set)
[EOF]
");
// Create and move with explicit -r
let output = work_dir.run_jj(["bookmark", "set", "-r@", "bar", "baz"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Created 1 bookmarks pointing to zsuskuln 0e555a27 bar baz | (empty) (no description set)
Moved 1 bookmarks to zsuskuln 0e555a27 bar baz | (empty) (no description set)
[EOF]
");
// Noop changes should not be included in the stats
let output = work_dir.run_jj(["bookmark", "set", "-r@", "foo", "bar", "baz"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Moved 1 bookmarks to zsuskuln 0e555a27 bar baz foo | (empty) (no description set)
[EOF]
");
}
#[test]
fn test_bookmark_at_root() {
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(["bookmark", "create", "fred", "-r=root()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Created 1 bookmarks pointing to zzzzzzzz 00000000 fred | (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["git", "export"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
Warning: Failed to export some bookmarks:
fred@git: Ref cannot point to the root commit in Git
[EOF]
");
}
#[test]
fn test_bookmark_bad_name() {
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(["bookmark", "create", ""]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value '' for '<NAMES>...': Failed to parse bookmark name: Syntax error
For more information, try '--help'.
Caused by: --> 1:1
|
1 |
| ^---
|
= expected <identifier>, <string_literal>, or <raw_string_literal>
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for how to quote symbols.
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["bookmark", "set", "''"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value '''' for '<NAMES>...': Failed to parse bookmark name: Expected non-empty string
For more information, try '--help'.
Caused by: --> 1:1
|
1 | ''
| ^^
|
= Expected non-empty string
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for how to quote symbols.
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj(["bookmark", "rename", "x", ""]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value '' for '<NEW>': Failed to parse bookmark name: Syntax error
For more information, try '--help'.
Caused by: --> 1:1
|
1 |
| ^---
|
= expected <identifier>, <string_literal>, or <raw_string_literal>
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for how to quote symbols.
[EOF]
[exit status: 2]
");
// common errors
let output = work_dir.run_jj(["bookmark", "set", "@-", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: invalid value '@-' for '<NAMES>...': Failed to parse bookmark name: Syntax error
For more information, try '--help'.
Caused by: --> 1:1
|
1 | @-
| ^---
|
= expected <identifier>, <string_literal>, or <raw_string_literal>
Hint: See https://docs.jj-vcs.dev/latest/revsets/ or use `jj help -k revsets` for how to quote symbols.
[EOF]
[exit status: 2]
");
let stderr = work_dir.run_jj(["bookmark", "set", "-r@-", "foo@bar"]);
insta::assert_snapshot!(stderr, @r"
------- stderr -------
error: invalid value 'foo@bar' for '<NAMES>...': Failed to parse bookmark name: Syntax error
For more information, try '--help'.
Caused by: --> 1:4
|
1 | foo@bar
| ^---
|
= expected <EOI>
Hint: Looks like remote bookmark. Run `jj bookmark track foo --remote=bar` to track it.
[EOF]
[exit status: 2]
");
// quoted name works
let output = work_dir.run_jj(["bookmark", "create", "'foo@bar'"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Warning: Target revision is empty.
Created 1 bookmarks pointing to qpvuntsm e8849ae1 "foo@bar" | (empty) (no description set)
[EOF]
"#);
}
#[test]
fn test_bookmark_move() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Set up remote
let git_repo_path = test_env.env_root().join("git-repo");
git::init_bare(git_repo_path);
work_dir
.run_jj(["git", "remote", "add", "origin", "../git-repo"])
.success();
let output = work_dir.run_jj(["bookmark", "move", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching bookmarks for names: foo
No bookmarks to update.
[EOF]
");
let output = work_dir.run_jj(["bookmark", "set", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Created 1 bookmarks pointing to qpvuntsm e8849ae1 foo | (empty) (no description set)
[EOF]
");
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj(["bookmark", "create", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Bookmark already exists: foo
Hint: Use `jj bookmark set` to update it.
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["bookmark", "set", "foo", "--revision", "@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Moved 1 bookmarks to mzvwutvl 8afc18ff foo | (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["bookmark", "set", "-r@-", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Refusing to move bookmark backwards or sideways: foo
Hint: Use --allow-backwards to allow it.
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["bookmark", "set", "-r@-", "--allow-backwards", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Moved 1 bookmarks to qpvuntsm e8849ae1 foo | (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["bookmark", "move", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Moved 1 bookmarks to mzvwutvl 8afc18ff foo | (empty) (no description set)
[EOF]
");
let output = work_dir.run_jj(["bookmark", "move", "--to=@-", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Refusing to move bookmark backwards or sideways: foo
Hint: Use --allow-backwards to allow it.
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["bookmark", "move", "--to=@-", "--allow-backwards", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Moved 1 bookmarks to qpvuntsm e8849ae1 foo | (empty) (no description set)
[EOF]
");
// Delete bookmark locally, but is still tracking remote
work_dir.run_jj(["describe", "@-", "-mcommit"]).success();
work_dir
.run_jj(["git", "push", "--allow-new", "-r@-"])
.success();
work_dir.run_jj(["bookmark", "delete", "foo"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
foo (deleted)
@origin: qpvuntsm 5f3ceb1e (empty) commit
[EOF]
");
// Deleted tracking bookmark name should still be allocated
let output = work_dir.run_jj(["bookmark", "create", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Tracked remote bookmarks exist for deleted bookmark: foo
Hint: Use `jj bookmark set` to recreate the local bookmark. Run `jj bookmark untrack foo` to disassociate them.
[EOF]
[exit status: 1]
");
// Restoring local target shouldn't invalidate tracking state
let output = work_dir.run_jj(["bookmark", "set", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Moved 1 bookmarks to mzvwutvl 91b59745 foo* | (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
foo: mzvwutvl 91b59745 (empty) (no description set)
@origin (behind by 1 commits): qpvuntsm 5f3ceb1e (empty) commit
[EOF]
");
// Untracked remote bookmark shouldn't block creation of local bookmark
work_dir.run_jj(["bookmark", "untrack", "foo"]).success();
work_dir.run_jj(["bookmark", "delete", "foo"]).success();
let output = work_dir.run_jj(["bookmark", "create", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Target revision is empty.
Created 1 bookmarks pointing to mzvwutvl 91b59745 foo | (empty) (no description set)
[EOF]
");
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
foo: mzvwutvl 91b59745 (empty) (no description set)
foo@origin: qpvuntsm 5f3ceb1e (empty) commit
[EOF]
");
}
#[test]
fn test_bookmark_move_matching() {
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", "a1", "a2"])
.success();
work_dir.run_jj(["new", "-mhead1"]).success();
work_dir.run_jj(["new", "root()"]).success();
work_dir.run_jj(["bookmark", "create", "b1"]).success();
work_dir.run_jj(["new"]).success();
work_dir.run_jj(["bookmark", "create", "c1"]).success();
work_dir.run_jj(["new", "-mhead2"]).success();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0dd9a4b12283
○ c1 2cbf65662e56
○ b1 c2934cfbfb19
│ ○ 9328ecc52471
│ ○ a1 a2 e8849ae12c70
├─╯
◆ 000000000000
[EOF]
");
let setup_opid = work_dir.current_operation_id();
// The default could be considered "--from=all() *", but is disabled
let output = work_dir.run_jj(["bookmark", "move"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the following required arguments were not provided:
<NAMES|--from <REVSETS>>
Usage: jj bookmark move <NAMES|--from <REVSETS>>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
// No bookmarks pointing to the source revisions
let output = work_dir.run_jj(["bookmark", "move", "--from=none()"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No bookmarks to update.
[EOF]
");
// No matching bookmarks within the source revisions
let output = work_dir.run_jj(["bookmark", "move", "--from=::@", "'a?'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No bookmarks to update.
[EOF]
");
// Noop move
let output = work_dir.run_jj(["bookmark", "move", "--to=a1", "a2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No bookmarks to update.
[EOF]
");
// Move from multiple revisions
let output = work_dir.run_jj(["bookmark", "move", "--from=::@"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Moved 2 bookmarks to vruxwmqv 0dd9a4b1 b1 c1 | (empty) head2
Hint: Specify bookmark by name to update just one of the bookmarks.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ b1 c1 0dd9a4b12283
○ 2cbf65662e56
○ c2934cfbfb19
│ ○ 9328ecc52471
│ ○ a1 a2 e8849ae12c70
├─╯
◆ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Move multiple bookmarks by name
let output = work_dir.run_jj(["bookmark", "move", "b1", "c1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Moved 2 bookmarks to vruxwmqv 0dd9a4b1 b1 c1 | (empty) head2
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ b1 c1 0dd9a4b12283
○ 2cbf65662e56
○ c2934cfbfb19
│ ○ 9328ecc52471
│ ○ a1 a2 e8849ae12c70
├─╯
◆ 000000000000
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
// Try to move multiple bookmarks, but one of them isn't fast-forward
let output = work_dir.run_jj(["bookmark", "move", "'?1'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Refusing to move bookmark backwards or sideways: a1
Hint: Use --allow-backwards to allow it.
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0dd9a4b12283
○ c1 2cbf65662e56
○ b1 c2934cfbfb19
│ ○ 9328ecc52471
│ ○ a1 a2 e8849ae12c70
├─╯
◆ 000000000000
[EOF]
");
// Select by revision and name
let output = work_dir.run_jj(["bookmark", "move", "--from=::a1+", "--to=a1+", "'?1'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Moved 1 bookmarks to kkmpptxz 9328ecc5 a1 | (empty) head1
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ 0dd9a4b12283
○ c1 2cbf65662e56
○ b1 c2934cfbfb19
│ ○ a1 9328ecc52471
│ ○ a2 e8849ae12c70
├─╯
◆ 000000000000
[EOF]
");
}
#[test]
fn test_bookmark_move_conflicting() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let get_log = || {
let template = r#"separate(" ", description.first_line(), bookmarks)"#;
work_dir.run_jj(["log", "-T", template])
};
work_dir.run_jj(["new", "root()", "-mA0"]).success();
work_dir.run_jj(["new", "root()", "-mB0"]).success();
work_dir.run_jj(["new", "root()", "-mC0"]).success();
work_dir.run_jj(["new", "subject(A0)", "-mA1"]).success();
// Set up conflicting bookmark.
work_dir
.run_jj(["bookmark", "create", "-rsubject(A0)", "foo"])
.success();
work_dir
.run_jj(["bookmark", "create", "--at-op=@-", "-rsubject(B0)", "foo"])
.success();
insta::assert_snapshot!(get_log(), @r"
@ A1
○ A0 foo??
│ ○ C0
├─╯
│ ○ B0 foo??
├─╯
◆
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
// Can't move the bookmark to C0 since it's sibling.
let output = work_dir.run_jj(["bookmark", "set", "-rsubject(C0)", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Refusing to move bookmark backwards or sideways: foo
Hint: Use --allow-backwards to allow it.
[EOF]
[exit status: 1]
");
// Can move the bookmark to A1 since it's descendant of A0. It's not
// descendant of B0, though.
let output = work_dir.run_jj(["bookmark", "set", "-rsubject(A1)", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Moved 1 bookmarks to mzvwutvl 0f5f3e2c foo | (empty) A1
[EOF]
");
insta::assert_snapshot!(get_log(), @r"
@ A1 foo
○ A0
│ ○ C0
├─╯
│ ○ B0
├─╯
◆
[EOF]
");
}
#[test]
fn test_bookmark_rename() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Set up remote
let git_repo_path = test_env.env_root().join("git-repo");
git::init_bare(git_repo_path);
work_dir
.run_jj(["git", "remote", "add", "origin", "../git-repo"])
.success();
let output = work_dir.run_jj(["bookmark", "rename", "bnoexist", "blocal"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No such bookmark: bnoexist
[EOF]
[exit status: 1]
");
work_dir.run_jj(["describe", "-m=commit-0"]).success();
work_dir.run_jj(["bookmark", "create", "blocal"]).success();
let output = work_dir.run_jj(["bookmark", "rename", "blocal", "blocal1"]);
insta::assert_snapshot!(output, @"");
work_dir.run_jj(["new"]).success();
work_dir.run_jj(["describe", "-m=commit-1"]).success();
work_dir.run_jj(["bookmark", "create", "bexist"]).success();
let output = work_dir.run_jj(["bookmark", "rename", "blocal1", "bexist"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Bookmark already exists: bexist
[EOF]
[exit status: 1]
");
work_dir.run_jj(["new"]).success();
work_dir.run_jj(["describe", "-m=commit-2"]).success();
work_dir
.run_jj(["bookmark", "create", "bremote", "buntracked"])
.success();
work_dir
.run_jj(["git", "push", "--allow-new", "-b=bremote", "-b=buntracked"])
.success();
let output = work_dir.run_jj(["bookmark", "rename", "bremote", "bremote2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Tracked remote bookmarks for bookmark bremote were not renamed.
Hint: To rename the bookmark on the remote, you can `jj git push --bookmark bremote` first (to delete it on the remote), and then `jj git push --bookmark bremote2`. `jj git push --all --deleted` would also be sufficient.
[EOF]
");
let op_id_after_rename = work_dir.current_operation_id();
let output = work_dir.run_jj(["bookmark", "rename", "bremote2", "bremote"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Tracked remote bookmarks for bookmark bremote exist.
Hint: Run `jj bookmark untrack bremote` to disassociate them.
[EOF]
");
work_dir
.run_jj(["op", "restore", &op_id_after_rename])
.success();
let output = work_dir.run_jj(["git", "push", "--bookmark", "bremote2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Changes to push to origin:
Add bookmark bremote2 to a9d7418c1c3f
[EOF]
");
work_dir
.run_jj(["git", "push", "--named", "bremote-untracked=@"])
.success();
work_dir
.run_jj(["bookmark", "forget", "bremote-untracked"])
.success();
let output = work_dir.run_jj(["bookmark", "rename", "bremote2", "bremote-untracked"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: The renamed bookmark already exists on the remote 'origin', tracking state was dropped.
Hint: To track the existing remote bookmark, run `jj bookmark track bremote-untracked --remote=origin`
Warning: Tracked remote bookmarks for bookmark bremote2 were not renamed.
Hint: To rename the bookmark on the remote, you can `jj git push --bookmark bremote2` first (to delete it on the remote), and then `jj git push --bookmark bremote-untracked`. `jj git push --all --deleted` would also be sufficient.
[EOF]
");
// rename an untracked bookmark
work_dir
.run_jj(["bookmark", "untrack", "buntracked"])
.success();
let output = work_dir.run_jj(["bookmark", "rename", "buntracked", "buntracked2"]);
insta::assert_snapshot!(output, @"");
}
#[test]
fn test_bookmark_rename_colocated() {
let test_env = TestEnvironment::default();
test_env
.run_jj_in(".", ["git", "init", "repo", "--colocate"])
.success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-m=commit-0"]).success();
work_dir.run_jj(["bookmark", "create", "blocal"]).success();
// Make sure that git tracking bookmarks don't cause a warning
let output = work_dir.run_jj(["bookmark", "rename", "blocal", "blocal1"]);
insta::assert_snapshot!(output, @"");
}
#[test]
fn test_bookmark_forget_glob() {
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", "foo-1"]).success();
work_dir.run_jj(["bookmark", "create", "bar-2"]).success();
work_dir.run_jj(["bookmark", "create", "foo-3"]).success();
work_dir.run_jj(["bookmark", "create", "foo-4"]).success();
let setup_opid = work_dir.current_operation_id();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bar-2 foo-1 foo-3 foo-4 e8849ae12c70
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["bookmark", "forget", "'foo-[1-3]'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Forgot 2 local bookmarks.
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["bookmark", "forget", "'foo-[1-3]'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Forgot 2 local bookmarks.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bar-2 foo-4 e8849ae12c70
◆ 000000000000
[EOF]
");
// Forgetting a bookmark via both explicit name and glob pattern, or with
// multiple glob patterns, shouldn't produce an error.
let output = work_dir.run_jj(["bookmark", "forget", "foo-4", "foo-*", "foo-*"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Forgot 1 local bookmarks.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bar-2 e8849ae12c70
◆ 000000000000
[EOF]
");
// Malformed glob
let output = work_dir.run_jj(["bookmark", "forget", "glob:'foo-[1-3'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse name pattern: Invalid string pattern
Caused by:
1: --> 1:1
|
1 | glob:'foo-[1-3'
| ^-------------^
|
= Invalid string pattern
2: error parsing glob 'foo-[1-3': unclosed character class; missing ']'
[EOF]
[exit status: 1]
");
// None of the globs match anything
let output = work_dir.run_jj(["bookmark", "forget", "baz*", "boom*"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No bookmarks to forget.
[EOF]
");
}
#[test]
fn test_bookmark_delete_glob() {
// Set up a git repo with a bookmark and a jj repo that has it as a remote.
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let git_repo_path = test_env.env_root().join("git-repo");
let git_repo = git::init_bare(git_repo_path);
let blob_oid = git_repo.write_blob(b"content").unwrap();
let mut tree_editor = git_repo
.edit_tree(gix::ObjectId::empty_tree(gix::hash::Kind::default()))
.unwrap();
tree_editor
.upsert("file", gix::object::tree::EntryKind::Blob, blob_oid)
.unwrap();
let _tree_id = tree_editor.write().unwrap();
work_dir
.run_jj(["git", "remote", "add", "origin", "../git-repo"])
.success();
work_dir.run_jj(["describe", "-m=commit"]).success();
work_dir.run_jj(["bookmark", "create", "foo-1"]).success();
work_dir.run_jj(["bookmark", "create", "bar-2"]).success();
work_dir.run_jj(["bookmark", "create", "foo-3"]).success();
work_dir.run_jj(["bookmark", "create", "foo-4"]).success();
// Push to create remote-tracking bookmarks
work_dir.run_jj(["git", "push", "--all"]).success();
// Add absent-tracked bookmark
work_dir.run_jj(["bookmark", "create", "foo-5"]).success();
work_dir.run_jj(["bookmark", "track", "foo-5"]).success();
let setup_opid = work_dir.current_operation_id();
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bar-2 foo-1 foo-3 foo-4 foo-5* 8e056f6b8c37
◆ 000000000000
[EOF]
");
let output = work_dir.run_jj(["bookmark", "delete", "'foo-[1-3]'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Deleted 2 bookmarks.
[EOF]
");
work_dir.run_jj(["op", "restore", &setup_opid]).success();
let output = work_dir.run_jj(["bookmark", "delete", "'foo-[1-3]'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Deleted 2 bookmarks.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bar-2 foo-1@origin foo-3@origin foo-4 foo-5* 8e056f6b8c37
◆ 000000000000
[EOF]
");
// We get an error if none of the globs match live bookmarks. Unlike `jj
// bookmark forget`, it's not allowed to delete already deleted bookmarks.
let output = work_dir.run_jj(["bookmark", "delete", "'foo-[1-3]'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
No bookmarks to delete.
[EOF]
");
// Deleting a bookmark via both explicit name and glob pattern, or with
// multiple glob patterns, shouldn't produce an error.
let output = work_dir.run_jj(["bookmark", "delete", "foo-4", "foo-*", "foo-*"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Deleted 2 bookmarks.
[EOF]
");
insta::assert_snapshot!(get_log_output(&work_dir), @r"
@ bar-2 foo-1@origin foo-3@origin foo-4@origin 8e056f6b8c37
◆ 000000000000
[EOF]
");
// The deleted bookmarks are still there, whereas absent-tracked bookmarks
// aren't.
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
bar-2: qpvuntsm 8e056f6b (empty) commit
@origin: qpvuntsm 8e056f6b (empty) commit
foo-1 (deleted)
@origin: qpvuntsm 8e056f6b (empty) commit
foo-3 (deleted)
@origin: qpvuntsm 8e056f6b (empty) commit
foo-4 (deleted)
@origin: qpvuntsm 8e056f6b (empty) commit
[EOF]
");
// Malformed glob
let output = work_dir.run_jj(["bookmark", "delete", "glob:'foo-[1-3'"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse name pattern: Invalid string pattern
Caused by:
1: --> 1:1
|
1 | glob:'foo-[1-3'
| ^-------------^
|
= Invalid string pattern
2: error parsing glob 'foo-[1-3': unclosed character class; missing ']'
[EOF]
[exit status: 1]
");
// Unknown pattern kind
let output = work_dir.run_jj(["bookmark", "forget", "whatever:bookmark"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse name pattern: Invalid string pattern
Caused by:
1: --> 1:1
|
1 | whatever:bookmark
| ^---------------^
|
= Invalid string pattern
2: Invalid string pattern kind `whatever:`
Hint: Try prefixing with one of `exact:`, `glob:`, `regex:`, `substring:`, or one of these with `-i` suffix added (e.g. `glob-i:`) for case-insensitive matching
[EOF]
[exit status: 1]
");
}
#[test]
fn test_bookmark_delete_export() {
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(["bookmark", "create", "foo"]).success();
work_dir.run_jj(["git", "export"]).success();
work_dir.run_jj(["bookmark", "delete", "foo"]).success();
let output = work_dir.run_jj(["bookmark", "list", "--all-remotes"]);
insta::assert_snapshot!(output, @r"
foo (deleted)
@git: rlvkpnrz 43444d88 (empty) (no description set)
[EOF]
------- stderr -------
Hint: Bookmarks marked as deleted will be deleted from the underlying Git repo on the next `jj git export`.
[EOF]
");
work_dir.run_jj(["git", "export"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
}
#[test]
fn test_bookmark_forget_export() {
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(["bookmark", "create", "foo"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
foo: rlvkpnrz 43444d88 (empty) (no description set)
[EOF]
");
// Exporting the bookmark to git creates a local-git tracking bookmark
let output = work_dir.run_jj(["git", "export"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["bookmark", "forget", "--include-remotes", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Forgot 1 local bookmarks.
Forgot 1 remote bookmarks.
[EOF]
");
// Forgetting a bookmark with --include-remotes deletes local and
// remote-tracking bookmarks including the corresponding git-tracking bookmark.
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"");
let output = work_dir.run_jj(["log", "-r=foo", "--no-graph"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Revision `foo` doesn't exist
[EOF]
[exit status: 1]
");
// `jj git export` will delete the bookmark from git. In a colocated
| 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_annotate_command.rs | cli/tests/test_file_annotate_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 std::fs::OpenOptions;
use std::io::Write as _;
use std::path::Path;
use jj_lib::file_util::check_symlink_support;
use jj_lib::file_util::symlink_file;
use crate::common::TestEnvironment;
fn append_to_file(file_path: &Path, contents: &str) {
let mut options = OpenOptions::new();
options.append(true);
let mut file = options.open(file_path).unwrap();
writeln!(file, "{contents}").unwrap();
}
#[test]
fn test_annotate_linear() {
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.txt", "line1\n");
work_dir
.run_jj(["describe", "-m=initial", "--author=Foo <foo@example.org>"])
.success();
work_dir.run_jj(["new", "-m=next"]).success();
append_to_file(
&work_dir.root().join("file.txt"),
"new text from new commit",
);
let output = work_dir.run_jj(["file", "annotate", "file.txt"]);
insta::assert_snapshot!(output, @r"
qpvuntsm foo 2001-02-03 08:05:08 1: line1
kkmpptxz test.use 2001-02-03 08:05:10 2: new text from new commit
[EOF]
");
}
#[test]
fn test_annotate_non_file() {
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", "annotate", "non-existent.txt"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Error: No such path: non-existent.txt
[EOF]
[exit status: 1]
");
work_dir.write_file("dir/file.txt", "");
let output = work_dir.run_jj(["file", "annotate", "dir"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Path exists but is not a regular file: dir
[EOF]
[exit status: 1]
");
if check_symlink_support().unwrap() {
symlink_file("target", work_dir.root().join("symlink")).unwrap();
let output = work_dir.run_jj(["file", "annotate", "symlink"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Error: Path exists but is not a regular file: symlink
[EOF]
[exit status: 1]
");
}
}
#[test]
fn test_annotate_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.txt", "line1\n");
work_dir.run_jj(["describe", "-m=initial"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "initial"])
.success();
work_dir.run_jj(["new", "-m=commit1"]).success();
append_to_file(
&work_dir.root().join("file.txt"),
"new text from new commit 1",
);
work_dir
.run_jj(["bookmark", "create", "-r@", "commit1"])
.success();
work_dir.run_jj(["new", "-m=commit2", "initial"]).success();
append_to_file(
&work_dir.root().join("file.txt"),
"new text from new commit 2",
);
work_dir
.run_jj(["bookmark", "create", "-r@", "commit2"])
.success();
// create a (conflicted) merge
work_dir
.run_jj(["new", "-m=merged", "commit1", "commit2"])
.success();
// resolve conflicts
work_dir.write_file(
"file.txt",
"line1\nnew text from new commit 1\nnew text from new commit 2\n",
);
let output = work_dir.run_jj(["file", "annotate", "file.txt"]);
insta::assert_snapshot!(output, @r"
qpvuntsm test.use 2001-02-03 08:05:08 1: line1
zsuskuln test.use 2001-02-03 08:05:11 2: new text from new commit 1
royxmykx test.use 2001-02-03 08:05:13 3: new text from new commit 2
[EOF]
");
}
#[test]
fn test_annotate_conflicted() {
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.txt", "line1\n");
work_dir.run_jj(["describe", "-m=initial"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "initial"])
.success();
work_dir.run_jj(["new", "-m=commit1"]).success();
append_to_file(
&work_dir.root().join("file.txt"),
"new text from new commit 1",
);
work_dir
.run_jj(["bookmark", "create", "-r@", "commit1"])
.success();
work_dir.run_jj(["new", "-m=commit2", "initial"]).success();
append_to_file(
&work_dir.root().join("file.txt"),
"new text from new commit 2",
);
work_dir
.run_jj(["bookmark", "create", "-r@", "commit2"])
.success();
// create a (conflicted) merge
work_dir
.run_jj(["new", "-m=merged", "commit1", "commit2"])
.success();
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj(["file", "annotate", "file.txt"]);
insta::assert_snapshot!(output, @r#"
qpvuntsm test.use 2001-02-03 08:05:08 1: line1
yostqsxw test.use 2001-02-03 08:05:15 2: <<<<<<< conflict 1 of 1
yostqsxw test.use 2001-02-03 08:05:15 3: %%%%%%% diff from: qpvuntsm a5daff01 "initial"
yostqsxw test.use 2001-02-03 08:05:15 4: \\\\\\\ to: zsuskuln 30cd4478 "commit1"
yostqsxw test.use 2001-02-03 08:05:15 5: +new text from new commit 1
yostqsxw test.use 2001-02-03 08:05:15 6: +++++++ royxmykx ad312256 "commit2"
royxmykx test.use 2001-02-03 08:05:13 7: new text from new commit 2
yostqsxw test.use 2001-02-03 08:05:15 8: >>>>>>> conflict 1 of 1 ends
[EOF]
"#);
}
#[test]
fn test_annotate_merge_one_sided_conflict_resolution() {
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.txt", "line1\n");
work_dir.run_jj(["describe", "-m=initial"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "initial"])
.success();
work_dir.run_jj(["new", "-m=commit1"]).success();
append_to_file(
&work_dir.root().join("file.txt"),
"new text from new commit 1",
);
work_dir
.run_jj(["bookmark", "create", "-r@", "commit1"])
.success();
work_dir.run_jj(["new", "-m=commit2", "initial"]).success();
append_to_file(
&work_dir.root().join("file.txt"),
"new text from new commit 2",
);
work_dir
.run_jj(["bookmark", "create", "-r@", "commit2"])
.success();
// create a (conflicted) merge
work_dir
.run_jj(["new", "-m=merged", "commit1", "commit2"])
.success();
// resolve conflicts
work_dir.write_file("file.txt", "line1\nnew text from new commit 1\n");
let output = work_dir.run_jj(["file", "annotate", "file.txt"]);
insta::assert_snapshot!(output, @r"
qpvuntsm test.use 2001-02-03 08:05:08 1: line1
zsuskuln test.use 2001-02-03 08:05:11 2: new text from new commit 1
[EOF]
");
}
#[test]
fn test_annotate_abandoned() {
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.txt", "line1\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file.txt", "line1\nline2\n");
work_dir.run_jj(["abandon"]).success();
let output = work_dir.run_jj(["file", "annotate", "-rat_operation(@-, @)", "file.txt"]);
insta::assert_snapshot!(output, @r"
qpvuntsm test.use 2001-02-03 08:05:08 1: line1
rlvkpnrz test.use 2001-02-03 08:05:09 2: line2
[EOF]
");
}
#[test]
fn test_annotate_with_template() {
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.txt", "initial 1\ninitial 2\ninitial 3\n");
work_dir.run_jj(["commit", "-m=initial"]).success();
work_dir.write_file(
work_dir.root().join("file.txt"),
"initial 2\nnew text from new commit 1\nthat splits into multiple lines\n",
);
work_dir.run_jj(["commit", "-m=commit1"]).success();
append_to_file(
&work_dir.root().join("file.txt"),
"new text from new commit 2\nalso continuing on a second line\nand a third!",
);
work_dir.run_jj(["describe", "-m=commit2"]).success();
let template = indoc::indoc! {r#"
if(first_line_in_hunk, "\n" ++ separate("\n",
commit.change_id().shortest(8)
++ " "
++ commit.description().first_line(),
commit_timestamp(commit).local().format('%Y-%m-%d %H:%M:%S')
++ " "
++ commit.author(),
) ++ "\n") ++ pad_start(4, original_line_number) ++ " ->" ++ pad_start(4, line_number) ++ ": " ++ content
"#};
let output = work_dir.run_jj(["file", "annotate", "file.txt", "-T", template]);
insta::assert_snapshot!(output, @r"
qpvuntsm initial
2001-02-03 08:05:08 Test User <test.user@example.com>
2 -> 1: initial 2
rlvkpnrz commit1
2001-02-03 08:05:09 Test User <test.user@example.com>
2 -> 2: new text from new commit 1
3 -> 3: that splits into multiple lines
kkmpptxz commit2
2001-02-03 08:05:10 Test User <test.user@example.com>
4 -> 4: new text from new commit 2
5 -> 5: also continuing on a second line
6 -> 6: and a third!
[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_file_show_command.rs | cli/tests/test_file_show_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;
#[test]
fn test_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("file1", "a\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "b\n");
work_dir.create_dir("dir");
work_dir.write_file("dir/file2", "c\n");
work_dir.write_file("file3", "d\n");
// Can print the contents of a file in a commit
let output = work_dir.run_jj(["file", "show", "file1", "-r", "@-"]);
insta::assert_snapshot!(output, @r"
a
[EOF]
");
// Defaults to printing the working-copy version
let output = work_dir.run_jj(["file", "show", "file1"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
");
// Can print a file in a subdirectory
let subdir_file = if cfg!(unix) {
"dir/file2"
} else {
"dir\\file2"
};
let output = work_dir.run_jj(["file", "show", subdir_file]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
// Error if the path doesn't exist
let output = work_dir.run_jj(["file", "show", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No such path: nonexistent
[EOF]
[exit status: 1]
");
// Can print files under the specified directory
let output = work_dir.run_jj(["file", "show", "dir"]);
insta::assert_snapshot!(output, @r"
c
[EOF]
");
// Can print a single file with template
let template = r#""--- " ++ path ++ "\n""#;
let output = work_dir.run_jj(["file", "show", "-T", template, "file1"]);
insta::assert_snapshot!(output, @r"
--- file1
b
[EOF]
");
// Can print multiple files with template
let output = work_dir.run_jj(["file", "show", "-T", template, "."]);
insta::assert_snapshot!(output, @r"
--- dir/file2
c
--- file1
b
--- file3
d
[EOF]
");
// Can glob for multiple files too
let output = work_dir.run_jj(["file", "show", "-T", template, "file*"]);
insta::assert_snapshot!(output, @r"
--- file1
b
--- file3
d
[EOF]
");
// Unmatched paths should generate warnings
let output = work_dir.run_jj(["file", "show", "file1", "non-existent"]);
insta::assert_snapshot!(output, @r"
b
[EOF]
------- stderr -------
Warning: No matching entries for paths: non-existent
[EOF]
");
// Can print a conflict
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "c\n");
work_dir
.run_jj(["rebase", "-r", "@", "-o", "@--"])
.success();
let output = work_dir.run_jj(["file", "show", "file1"]);
insta::assert_snapshot!(output, @r"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: rlvkpnrz fc7b369e (parents of rebased revision)
\\\\\\\ to: qpvuntsm eb7b8a1f (rebase destination)
-b
+a
+++++++ kmkuslsw f74f80c5 (rebased revision)
c
>>>>>>> conflict 1 of 1 ends
[EOF]
");
}
#[cfg(unix)]
#[test]
fn test_show_symlink() {
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", "a\n");
work_dir.create_dir("dir");
work_dir.write_file("dir/file2", "c\n");
std::os::unix::fs::symlink("symlink1_target", work_dir.root().join("symlink1")).unwrap();
// Can print multiple files with template
let template = r#""--- " ++ path ++ " [" ++ file_type ++ "]\n""#;
let output = work_dir.run_jj(["file", "show", "-T", template, "."]);
insta::assert_snapshot!(output, @r"
--- dir/file2 [file]
c
--- file1 [file]
a
--- symlink1 [symlink]
[EOF]
------- stderr -------
Warning: Path 'symlink1' exists but is not a file
[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_workspaces.rs | cli/tests/test_workspaces.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 test_case::test_case;
use testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_workspaces_invalid_name() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let main_dir = test_env.work_dir("repo");
// refuse to create, directory not created
let output = main_dir.run_jj(["workspace", "add", "--name", "", "../secondary"]);
insta::assert_snapshot!(output, @"
------- stderr -------
Error: New workspace name cannot be empty
[EOF]
[exit status: 1]
");
assert!(!test_env.env_root().join("secondary").exists());
// refuse to rename
let output = main_dir.run_jj(["workspace", "rename", ""]);
insta::assert_snapshot!(output, @"
------- stderr -------
Error: New workspace name cannot be empty
[EOF]
[exit status: 1]
");
}
/// Test adding a second and a third workspace
#[test]
fn test_workspaces_add_second_and_third_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");
main_dir.write_file("file", "contents");
main_dir.run_jj(["commit", "-m", "initial"]).success();
let output = main_dir.run_jj(["workspace", "list"]);
insta::assert_snapshot!(output, @r"
default: rlvkpnrz 504e3d8c (empty) (no description set)
[EOF]
");
let output = main_dir.run_jj(["workspace", "add", "--name", "second", "../secondary"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Created workspace in "../secondary"
Working copy (@) now at: rzvqmyuk bcc858e1 (empty) (no description set)
Parent commit (@-) : qpvuntsm 7b22a8cb initial
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
// Can see the working-copy commit in each workspace in the log output. The "@"
// node in the graph indicates the current workspace's working-copy commit.
insta::assert_snapshot!(get_log_output(&main_dir), @r#"
@ 504e3d8c1bcd default@
│ ○ bcc858e1d93f second@
├─╯
○ 7b22a8cbe888 "initial"
◆ 000000000000
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&secondary_dir), @r#"
@ bcc858e1d93f second@
│ ○ 504e3d8c1bcd default@
├─╯
○ 7b22a8cbe888 "initial"
◆ 000000000000
[EOF]
"#);
// Both workspaces show up when we list them
let output = main_dir.run_jj(["workspace", "list"]);
insta::assert_snapshot!(output, @r"
default: rlvkpnrz 504e3d8c (empty) (no description set)
second: rzvqmyuk bcc858e1 (empty) (no description set)
[EOF]
");
// Check that a workspace can be created in an existing empty directory
main_dir.create_dir("../third");
let output = main_dir.run_jj(["workspace", "add", "--name", "third", "../third"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Created workspace in "../third"
Working copy (@) now at: nuwvvtmy d55e769c (empty) (no description set)
Parent commit (@-) : qpvuntsm 7b22a8cb initial
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
// Duplicate names are not allowed, directory not created
let output = main_dir.run_jj(["workspace", "add", "--name", "third", "../tertiary"]);
insta::assert_snapshot!(output.normalize_backslash(), @"
------- stderr -------
Error: Workspace named 'third' already exists
[EOF]
[exit status: 1]
");
assert!(!test_env.env_root().join("tertiary").exists());
}
/// Test how sparse patterns are inherited
#[test]
fn test_workspaces_sparse_patterns() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "ws1"]).success();
let ws1_dir = test_env.work_dir("ws1");
let ws2_dir = test_env.work_dir("ws2");
let ws3_dir = test_env.work_dir("ws3");
let ws4_dir = test_env.work_dir("ws4");
let ws5_dir = test_env.work_dir("ws5");
let ws6_dir = test_env.work_dir("ws6");
ws1_dir
.run_jj(["sparse", "set", "--clear", "--add=foo"])
.success();
ws1_dir.run_jj(["workspace", "add", "../ws2"]).success();
let output = ws2_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
foo
[EOF]
");
ws2_dir.run_jj(["sparse", "set", "--add=bar"]).success();
ws2_dir.run_jj(["workspace", "add", "../ws3"]).success();
let output = ws3_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
bar
foo
[EOF]
");
// --sparse-patterns behavior
ws3_dir
.run_jj(["workspace", "add", "--sparse-patterns=copy", "../ws4"])
.success();
let output = ws4_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
bar
foo
[EOF]
");
ws3_dir
.run_jj(["workspace", "add", "--sparse-patterns=full", "../ws5"])
.success();
let output = ws5_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @r"
.
[EOF]
");
ws3_dir
.run_jj(["workspace", "add", "--sparse-patterns=empty", "../ws6"])
.success();
let output = ws6_dir.run_jj(["sparse", "list"]);
insta::assert_snapshot!(output, @"");
}
/// Test adding a second workspace while the current workspace is editing a
/// merge
#[test]
fn test_workspaces_add_second_workspace_on_merge() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "main"]).success();
let main_dir = test_env.work_dir("main");
main_dir.run_jj(["describe", "-m=left"]).success();
main_dir.run_jj(["new", "@-", "-m=right"]).success();
main_dir.run_jj(["new", "@-+", "-m=merge"]).success();
let output = main_dir.run_jj(["workspace", "list"]);
insta::assert_snapshot!(output, @r"
default: zsuskuln 46ed31b6 (empty) merge
[EOF]
");
main_dir
.run_jj(["workspace", "add", "--name", "second", "../secondary"])
.success();
// The new workspace's working-copy commit shares all parents with the old one.
insta::assert_snapshot!(get_log_output(&main_dir), @r#"
@ 46ed31b61ce9 default@ "merge"
├─╮
│ │ ○ d23b2d4ff55c second@
╭─┬─╯
│ ○ 3c52528f5893 "left"
○ │ a3155ab1bf5a "right"
├─╯
◆ 000000000000
[EOF]
"#);
}
/// Test that --ignore-working-copy is respected
#[test]
fn test_workspaces_add_ignore_working_copy() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "main"]).success();
let main_dir = test_env.work_dir("main");
// TODO: maybe better to error out early?
let output = main_dir.run_jj(["workspace", "add", "--ignore-working-copy", "../secondary"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Created workspace in "../secondary"
Error: This command must be able to update the working copy.
Hint: Don't use --ignore-working-copy.
[EOF]
[exit status: 1]
"#);
}
/// Test that --at-op is respected
#[test]
fn test_workspaces_add_at_operation() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "main"]).success();
let main_dir = test_env.work_dir("main");
main_dir.write_file("file1", "");
let output = main_dir.run_jj(["commit", "-m1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: rlvkpnrz 59e07459 (empty) (no description set)
Parent commit (@-) : qpvuntsm 9e4b0b91 1
[EOF]
");
main_dir.write_file("file2", "");
let output = main_dir.run_jj(["commit", "-m2"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: kkmpptxz 6e9610ac (empty) (no description set)
Parent commit (@-) : rlvkpnrz 8b7259b9 2
[EOF]
");
// --at-op should disable snapshot in the main workspace, but the newly
// created workspace should still be writable.
main_dir.write_file("file3", "");
let output = main_dir.run_jj(["workspace", "add", "--at-op=@-", "../secondary"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Created workspace in "../secondary"
Working copy (@) now at: rzvqmyuk b8772476 (empty) (no description set)
Parent commit (@-) : qpvuntsm 9e4b0b91 1
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
let secondary_dir = test_env.work_dir("secondary");
// New snapshot can be taken in the secondary workspace.
secondary_dir.write_file("file4", "");
let output = secondary_dir.run_jj(["status"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
A file4
Working copy (@) : rzvqmyuk f2ff8257 (no description set)
Parent commit (@-): qpvuntsm 9e4b0b91 1
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
let output = secondary_dir.run_jj(["op", "log", "-Tdescription"]);
insta::assert_snapshot!(output, @r"
@ snapshot working copy
○ reconcile divergent operations
├─╮
○ │ commit 9152e822279787a168ddf4cede6440a21faa00d7
│ ○ create initial working-copy commit in workspace secondary
│ ○ add workspace 'secondary'
├─╯
○ snapshot working copy
○ commit 093c3c9624b6cfe22b310586f5638792aa80e6d7
○ snapshot working copy
○ add workspace 'default'
○
[EOF]
");
}
/// Test adding a workspace, but at a specific revision using '-r'
#[test]
fn test_workspaces_add_workspace_at_revision() {
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");
main_dir.write_file("file-1", "contents");
main_dir.run_jj(["commit", "-m", "first"]).success();
main_dir.write_file("file-2", "contents");
main_dir.run_jj(["commit", "-m", "second"]).success();
let output = main_dir.run_jj(["workspace", "list"]);
insta::assert_snapshot!(output, @r"
default: kkmpptxz 5ac9178d (empty) (no description set)
[EOF]
");
let output = main_dir.run_jj([
"workspace",
"add",
"--name",
"second",
"../secondary",
"-r",
"@--",
]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Created workspace in "../secondary"
Working copy (@) now at: zxsnswpr ea5860fb (empty) (no description set)
Parent commit (@-) : qpvuntsm 27473635 first
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
// Can see the working-copy commit in each workspace in the log output. The "@"
// node in the graph indicates the current workspace's working-copy commit.
insta::assert_snapshot!(get_log_output(&main_dir), @r#"
@ 5ac9178da8b2 default@
○ a47d8a593529 "second"
│ ○ ea5860fbd622 second@
├─╯
○ 27473635a942 "first"
◆ 000000000000
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&secondary_dir), @r#"
@ ea5860fbd622 second@
│ ○ 5ac9178da8b2 default@
│ ○ a47d8a593529 "second"
├─╯
○ 27473635a942 "first"
◆ 000000000000
[EOF]
"#);
}
/// Test multiple `-r` flags to `workspace add` to create a workspace
/// working-copy commit with multiple parents.
#[test]
fn test_workspaces_add_workspace_multiple_revisions() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "main"]).success();
let main_dir = test_env.work_dir("main");
main_dir.write_file("file-1", "contents");
main_dir.run_jj(["commit", "-m", "first"]).success();
main_dir.run_jj(["new", "-r", "root()"]).success();
main_dir.write_file("file-2", "contents");
main_dir.run_jj(["commit", "-m", "second"]).success();
main_dir.run_jj(["new", "-r", "root()"]).success();
main_dir.write_file("file-3", "contents");
main_dir.run_jj(["commit", "-m", "third"]).success();
main_dir.run_jj(["new", "-r", "root()"]).success();
insta::assert_snapshot!(get_log_output(&main_dir), @r#"
@ 8d23abddc924
│ ○ eba7f49e2358 "third"
├─╯
│ ○ 62444a45efcf "second"
├─╯
│ ○ 27473635a942 "first"
├─╯
◆ 000000000000
[EOF]
"#);
let output = main_dir.run_jj([
"workspace",
"add",
"--name=merge",
"../merged",
"-r=subject(third)",
"-r=subject(second)",
"-r=subject(first)",
]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Created workspace in "../merged"
Working copy (@) now at: wmwvqwsz 2d7c9a2d (empty) (no description set)
Parent commit (@-) : mzvwutvl eba7f49e third
Parent commit (@-) : kkmpptxz 62444a45 second
Parent commit (@-) : qpvuntsm 27473635 first
Added 3 files, modified 0 files, removed 0 files
[EOF]
"#);
insta::assert_snapshot!(get_log_output(&main_dir), @r#"
@ 8d23abddc924 default@
│ ○ 2d7c9a2d41dc merge@
│ ├─┬─╮
│ │ │ ○ 27473635a942 "first"
├─────╯
│ │ ○ 62444a45efcf "second"
├───╯
│ ○ eba7f49e2358 "third"
├─╯
◆ 000000000000
[EOF]
"#);
}
#[test]
fn test_workspaces_add_workspace_from_subdir() {
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 subdir_dir = main_dir.create_dir("subdir");
subdir_dir.write_file("file", "contents");
main_dir.run_jj(["commit", "-m", "initial"]).success();
let output = main_dir.run_jj(["workspace", "list"]);
insta::assert_snapshot!(output, @r"
default: rlvkpnrz 0ba0ff35 (empty) (no description set)
[EOF]
");
// Create workspace while in sub-directory of current workspace
let output = subdir_dir.run_jj(["workspace", "add", "../../secondary"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Created workspace in "../../secondary"
Working copy (@) now at: rzvqmyuk dea1be10 (empty) (no description set)
Parent commit (@-) : qpvuntsm 80b67806 initial
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
// Both workspaces show up when we list them
let output = secondary_dir.run_jj(["workspace", "list"]);
insta::assert_snapshot!(output, @r"
default: rlvkpnrz 0ba0ff35 (empty) (no description set)
secondary: rzvqmyuk dea1be10 (empty) (no description set)
[EOF]
");
}
#[test]
fn test_workspaces_add_workspace_in_current_workspace() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "main"]).success();
let main_dir = test_env.work_dir("main");
main_dir.write_file("file", "contents");
main_dir.run_jj(["commit", "-m", "initial"]).success();
// Try to create workspace using name instead of path
let output = main_dir.run_jj(["workspace", "add", "secondary"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Created workspace in "secondary"
Warning: Workspace created inside current directory. If this was unintentional, delete the "secondary" directory and run `jj workspace forget secondary` to remove it.
Working copy (@) now at: pmmvwywv 058f604d (empty) (no description set)
Parent commit (@-) : qpvuntsm 7b22a8cb initial
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
// Workspace created despite warning
let output = main_dir.run_jj(["workspace", "list"]);
insta::assert_snapshot!(output, @r"
default: rlvkpnrz 504e3d8c (empty) (no description set)
secondary: pmmvwywv 058f604d (empty) (no description set)
[EOF]
");
// Use explicit path instead (no warning)
let output = main_dir.run_jj(["workspace", "add", "./third"]);
insta::assert_snapshot!(output.normalize_backslash(), @r#"
------- stderr -------
Created workspace in "third"
Working copy (@) now at: zxsnswpr 1c1effec (empty) (no description set)
Parent commit (@-) : qpvuntsm 7b22a8cb initial
Added 1 files, modified 0 files, removed 0 files
[EOF]
"#);
// Both workspaces created
let output = main_dir.run_jj(["workspace", "list"]);
insta::assert_snapshot!(output, @r"
default: rlvkpnrz 504e3d8c (empty) (no description set)
secondary: pmmvwywv 058f604d (empty) (no description set)
third: zxsnswpr 1c1effec (empty) (no description set)
[EOF]
");
let output = main_dir.run_jj(["file", "list"]);
insta::assert_snapshot!(output.normalize_backslash(), @r"
file
[EOF]
");
}
/// Test making changes to the working copy in a workspace as it gets rewritten
/// from another workspace
#[test]
fn test_workspaces_conflicting_edits() {
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");
main_dir.write_file("file", "contents\n");
main_dir.run_jj(["new"]).success();
main_dir
.run_jj(["workspace", "add", "../secondary"])
.success();
insta::assert_snapshot!(get_log_output(&main_dir), @r"
@ 393250c59e39 default@
│ ○ 547036666102 secondary@
├─╯
○ 9a462e35578a
◆ 000000000000
[EOF]
");
// Make changes in both working copies
main_dir.write_file("file", "changed in main\n");
secondary_dir.write_file("file", "changed in second\n");
// Squash the changes from the main workspace into the initial commit (before
// running any command in the secondary workspace
let output = main_dir.run_jj(["squash"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: mzvwutvl 3a9b690d (empty) (no description set)
Parent commit (@-) : qpvuntsm b853f7c8 (no description set)
[EOF]
");
// The secondary workspace's working-copy commit was updated
insta::assert_snapshot!(get_log_output(&main_dir), @r"
@ 3a9b690d6e67 default@
│ ○ 90f3d42e0bff secondary@
├─╯
○ b853f7c8b006
◆ 000000000000
[EOF]
");
let output = secondary_dir.run_jj(["st"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The working copy is stale (not updated since operation bd4f780d0422).
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]
");
// Same error on second run, and from another command
let output = secondary_dir.run_jj(["log"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The working copy is stale (not updated since operation bd4f780d0422).
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]
");
// It was detected that the working copy is now stale.
// Since there was an uncommitted change in the working copy, it should
// have been committed first (causing divergence)
let output = secondary_dir.run_jj(["workspace", "update-stale"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Concurrent modification detected, resolving automatically.
Rebased 1 descendant commits onto commits rewritten by other operation
Working copy (@) now at: pmmvwywv/2 90f3d42e (divergent) (empty) (no description set)
Parent commit (@-) : qpvuntsm b853f7c8 (no description set)
Added 0 files, modified 1 files, removed 0 files
Updated working copy to fresh commit 90f3d42e0bff
[EOF]
");
insta::assert_snapshot!(get_log_output(&secondary_dir),
@r"
@ 90f3d42e0bff secondary@ (divergent)
│ × 5ae7e71904b9 (divergent)
├─╯
│ ○ 3a9b690d6e67 default@
├─╯
○ b853f7c8b006
◆ 000000000000
[EOF]
");
// The stale working copy should have been resolved by the previous command
insta::assert_snapshot!(get_log_output(&secondary_dir), @r"
@ 90f3d42e0bff secondary@ (divergent)
│ × 5ae7e71904b9 (divergent)
├─╯
│ ○ 3a9b690d6e67 default@
├─╯
○ b853f7c8b006
◆ 000000000000
[EOF]
");
}
/// Test a clean working copy that gets rewritten from another workspace
#[test]
fn test_workspaces_updated_by_other() {
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");
main_dir.write_file("file", "contents\n");
main_dir.run_jj(["new"]).success();
main_dir
.run_jj(["workspace", "add", "../secondary"])
.success();
insta::assert_snapshot!(get_log_output(&main_dir), @r"
@ 393250c59e39 default@
│ ○ 547036666102 secondary@
├─╯
○ 9a462e35578a
◆ 000000000000
[EOF]
");
// Rewrite the check-out commit in one workspace.
main_dir.write_file("file", "changed in main\n");
let output = main_dir.run_jj(["squash"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: mzvwutvl 3a9b690d (empty) (no description set)
Parent commit (@-) : qpvuntsm b853f7c8 (no description set)
[EOF]
");
// The secondary workspace's working-copy commit was updated.
insta::assert_snapshot!(get_log_output(&main_dir), @r"
@ 3a9b690d6e67 default@
│ ○ 90f3d42e0bff secondary@
├─╯
○ b853f7c8b006
◆ 000000000000
[EOF]
");
let output = secondary_dir.run_jj(["st"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: The working copy is stale (not updated since operation bd4f780d0422).
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]
");
// It was detected that the working copy is now stale, but clean. So no
// divergent commit should be created.
let output = secondary_dir.run_jj(["workspace", "update-stale"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: pmmvwywv 90f3d42e (empty) (no description set)
Parent commit (@-) : qpvuntsm b853f7c8 (no description set)
Added 0 files, modified 1 files, removed 0 files
Updated working copy to fresh commit 90f3d42e0bff
[EOF]
");
insta::assert_snapshot!(get_log_output(&secondary_dir),
@r"
@ 90f3d42e0bff secondary@
│ ○ 3a9b690d6e67 default@
├─╯
○ b853f7c8b006
◆ 000000000000
[EOF]
");
}
/// Test a clean working copy that gets rewritten from another workspace
#[test]
fn test_workspaces_updated_by_other_automatic() {
let test_env = TestEnvironment::default();
test_env.add_config("snapshot.auto-update-stale = true\n");
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");
main_dir.write_file("file", "contents\n");
main_dir.run_jj(["new"]).success();
main_dir
.run_jj(["workspace", "add", "../secondary"])
.success();
insta::assert_snapshot!(get_log_output(&main_dir), @r"
@ 393250c59e39 default@
│ ○ 547036666102 secondary@
├─╯
○ 9a462e35578a
◆ 000000000000
[EOF]
");
// Rewrite the check-out commit in one workspace.
main_dir.write_file("file", "changed in main\n");
let output = main_dir.run_jj(["squash"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 descendant commits
Working copy (@) now at: mzvwutvl 3a9b690d (empty) (no description set)
Parent commit (@-) : qpvuntsm b853f7c8 (no description set)
[EOF]
");
// The secondary workspace's working-copy commit was updated.
insta::assert_snapshot!(get_log_output(&main_dir), @r"
@ 3a9b690d6e67 default@
│ ○ 90f3d42e0bff secondary@
├─╯
○ b853f7c8b006
◆ 000000000000
[EOF]
");
// The first working copy gets automatically updated.
let output = secondary_dir.run_jj(["st"]);
insta::assert_snapshot!(output, @r"
The working copy has no changes.
Working copy (@) : pmmvwywv 90f3d42e (empty) (no description set)
Parent commit (@-): qpvuntsm b853f7c8 (no description set)
[EOF]
------- stderr -------
Working copy (@) now at: pmmvwywv 90f3d42e (empty) (no description set)
Parent commit (@-) : qpvuntsm b853f7c8 (no description set)
Added 0 files, modified 1 files, removed 0 files
Updated working copy to fresh commit 90f3d42e0bff
[EOF]
");
insta::assert_snapshot!(get_log_output(&secondary_dir),
@r"
@ 90f3d42e0bff secondary@
│ ○ 3a9b690d6e67 default@
├─╯
○ b853f7c8b006
◆ 000000000000
[EOF]
");
}
#[test_case(false; "manual")]
#[test_case(true; "automatic")]
fn test_workspaces_current_op_discarded_by_other(automatic: bool) {
let test_env = TestEnvironment::default();
if automatic {
test_env.add_config("snapshot.auto-update-stale = true\n");
}
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");
main_dir.write_file("modified", "base\n");
main_dir.write_file("deleted", "base\n");
main_dir.write_file("sparse", "base\n");
main_dir.run_jj(["new"]).success();
main_dir.write_file("modified", "main\n");
main_dir.run_jj(["new"]).success();
main_dir
.run_jj(["workspace", "add", "../secondary"])
.success();
// Make unsnapshotted writes in the secondary working copy
secondary_dir
.run_jj([
"sparse",
"set",
"--clear",
"--add=modified",
"--add=deleted",
"--add=added",
])
.success();
secondary_dir.write_file("modified", "secondary\n");
secondary_dir.remove_file("deleted");
secondary_dir.write_file("added", "secondary\n");
// Create an op by abandoning the parent commit. Importantly, that commit also
// changes the target tree in the secondary workspace.
main_dir.run_jj(["abandon", "@-"]).success();
let output = main_dir.run_jj([
"operation",
"log",
"--template",
r#"id.short(10) ++ " " ++ description"#,
]);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r"
@ b0789def13 abandon commit de90575a14d8b9198dc0930f9de4a69f846ded36
○ 778c9aae54 create initial working-copy commit in workspace secondary
○ 219d4aca5c add workspace 'secondary'
○ 31ad55e98c new empty commit
○ 4ba7680cbe snapshot working copy
○ 9739176f19 new empty commit
○ 4b5baa44b7 snapshot working copy
○ 8f47435a39 add workspace 'default'
○ 0000000000
[EOF]
");
}
// Abandon ops, including the one the secondary workspace is currently on.
main_dir.run_jj(["operation", "abandon", "..@-"]).success();
main_dir.run_jj(["util", "gc", "--expire=now"]).success();
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output(&main_dir), @r"
@ 320bc89effc9 default@
│ ○ 891f00062e10 secondary@
├─╯
○ 367415be5b44
◆ 000000000000
[EOF]
");
}
if automatic {
// Run a no-op command to set the randomness seed for commit hashes.
secondary_dir.run_jj(["help"]).success();
let output = secondary_dir.run_jj(["st"]);
insta::assert_snapshot!(output, @r"
Working copy changes:
C {modified => added}
D deleted
M modified
Working copy (@) : kmkuslsw 18851b39 RECOVERY COMMIT FROM `jj workspace update-stale`
Parent commit (@-): rzvqmyuk 891f0006 (empty) (no description set)
[EOF]
------- stderr -------
Failed to read working copy's current operation; attempting recovery. Error message from read attempt: Object 778c9aae54957e842bede2223fda227be33e08061732276a4cfb7b431a3e146e5c62187d640aa883095d3b2c6cf43d31ad5fde72076bb9a88b8594fb8b5e6606 of type operation not found
Created and checked out recovery commit 866928d1e0fd
[EOF]
");
} else {
let output = secondary_dir.run_jj(["st"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Could not read working copy's operation.
Hint: Run `jj workspace update-stale` to recover.
See https://docs.jj-vcs.dev/latest/working-copy/#stale-working-copy for more information.
[EOF]
[exit status: 1]
");
let output = secondary_dir.run_jj(["workspace", "update-stale"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Failed to read working copy's current operation; attempting recovery. Error message from read attempt: Object 778c9aae54957e842bede2223fda227be33e08061732276a4cfb7b431a3e146e5c62187d640aa883095d3b2c6cf43d31ad5fde72076bb9a88b8594fb8b5e6606 of type operation not found
Created and checked out recovery commit 866928d1e0fd
[EOF]
");
}
insta::allow_duplicates! {
insta::assert_snapshot!(get_log_output(&main_dir), @r#"
@ 320bc89effc9 default@
│ ○ 18851b397d09 secondary@ "RECOVERY COMMIT FROM `jj workspace update-stale`"
│ ○ 891f00062e10
├─╯
○ 367415be5b44
◆ 000000000000
[EOF]
"#);
}
// The sparse patterns should remain
let output = secondary_dir.run_jj(["sparse", "list"]);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r"
added
deleted
modified
[EOF]
");
}
let output = secondary_dir.run_jj(["st"]);
insta::allow_duplicates! {
insta::assert_snapshot!(output, @r"
Working copy changes:
C {modified => added}
D deleted
M modified
Working copy (@) : kmkuslsw 18851b39 RECOVERY COMMIT FROM `jj workspace update-stale`
Parent commit (@-): rzvqmyuk 891f0006 (empty) (no description set)
[EOF]
");
}
insta::allow_duplicates! {
// The modified file should have the same contents it had before (not reset to
// the base contents)
insta::assert_snapshot!(secondary_dir.read_file("modified"), @"secondary");
}
let output = secondary_dir.run_jj(["evolog"]);
if automatic {
insta::assert_snapshot!(output, @r"
@ kmkuslsw test.user@example.com 2001-02-03 08:05:18 secondary@ 18851b39
│ RECOVERY COMMIT FROM `jj workspace update-stale`
│ -- operation 0a26da4b0149 snapshot working copy
○ kmkuslsw/1 test.user@example.com 2001-02-03 08:05:18 866928d1 (hidden)
(empty) RECOVERY COMMIT FROM `jj workspace update-stale`
| 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_absorb_command.rs | cli/tests/test_absorb_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_absorb_simple() {
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", "-m0"]).success();
work_dir.write_file("file1", "");
work_dir.run_jj(["new", "-m1"]).success();
work_dir.write_file("file1", "1a\n1b\n");
work_dir.run_jj(["new", "-m2"]).success();
work_dir.write_file("file1", "1a\n1b\n2a\n2b\n");
// Empty commit
work_dir.run_jj(["new"]).success();
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
// Insert first and last lines
work_dir.write_file("file1", "1X\n1a\n1b\n2a\n2b\n2Z\n");
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 2 revisions:
zsuskuln 95568809 2
kkmpptxz bd7d4016 1
Working copy (@) now at: yqosqzyt 977269ac (empty) (no description set)
Parent commit (@-) : zsuskuln 95568809 2
[EOF]
");
// Modify middle line in hunk
work_dir.write_file("file1", "1X\n1A\n1b\n2a\n2b\n2Z\n");
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
kkmpptxz 5810eb0f 1
Rebased 1 descendant commits.
Working copy (@) now at: vruxwmqv 48c7d8fa (empty) (no description set)
Parent commit (@-) : zsuskuln 8edd60a2 2
[EOF]
");
// Remove middle line from hunk
work_dir.write_file("file1", "1X\n1A\n1b\n2a\n2Z\n");
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
zsuskuln dd109863 2
Working copy (@) now at: yostqsxw 7482f74b (empty) (no description set)
Parent commit (@-) : zsuskuln dd109863 2
[EOF]
");
// Insert ambiguous line in between
work_dir.write_file("file1", "1X\n1A\n1b\nY\n2a\n2Z\n");
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Nothing changed.
[EOF]
");
insta::assert_snapshot!(get_diffs(&work_dir, "mutable()"), @r"
@ yostqsxw bde51bc9 (no description set)
│ diff --git a/file1 b/file1
│ index 8653ca354d..88eb438902 100644
│ --- a/file1
│ +++ b/file1
│ @@ -1,5 +1,6 @@
│ 1X
│ 1A
│ 1b
│ +Y
│ 2a
│ 2Z
○ zsuskuln dd109863 2
│ diff --git a/file1 b/file1
│ index ed237b5112..8653ca354d 100644
│ --- a/file1
│ +++ b/file1
│ @@ -1,3 +1,5 @@
│ 1X
│ 1A
│ 1b
│ +2a
│ +2Z
○ kkmpptxz 5810eb0f 1
│ diff --git a/file1 b/file1
│ index e69de29bb2..ed237b5112 100644
│ --- a/file1
│ +++ b/file1
│ @@ -0,0 +1,3 @@
│ +1X
│ +1A
│ +1b
○ qpvuntsm 6a446874 0
│ diff --git a/file1 b/file1
~ new file mode 100644
index 0000000000..e69de29bb2
[EOF]
");
insta::assert_snapshot!(get_evolog(&work_dir, "subject(1)"), @r"
○ kkmpptxz 5810eb0f 1
├─╮
│ ○ yqosqzyt/0 39b42898 (hidden) (no description set)
│ ○ yqosqzyt/1 977269ac (hidden) (empty) (no description set)
○ kkmpptxz/1 bd7d4016 (hidden) 1
├─╮
│ ○ mzvwutvl/0 0b307741 (hidden) (no description set)
│ ○ mzvwutvl/1 f2709b4e (hidden) (empty) (no description set)
○ kkmpptxz/2 1553c5e8 (hidden) 1
○ kkmpptxz/3 eb943711 (hidden) (empty) 1
[EOF]
");
insta::assert_snapshot!(get_evolog(&work_dir, "subject(2)"), @r"
○ zsuskuln dd109863 2
├─╮
│ ○ vruxwmqv/0 761492a8 (hidden) (no description set)
│ ○ vruxwmqv/1 48c7d8fa (hidden) (empty) (no description set)
○ zsuskuln/1 8edd60a2 (hidden) 2
○ zsuskuln/2 95568809 (hidden) 2
├─╮
│ ○ mzvwutvl/0 0b307741 (hidden) (no description set)
│ ○ mzvwutvl/1 f2709b4e (hidden) (empty) (no description set)
○ zsuskuln/3 36fad385 (hidden) 2
○ zsuskuln/4 561fbce9 (hidden) (empty) 2
[EOF]
");
}
#[test]
fn test_absorb_replace_single_line_hunk() {
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", "-m1"]).success();
work_dir.write_file("file1", "1a\n");
work_dir.run_jj(["new", "-m2"]).success();
work_dir.write_file("file1", "2a\n1a\n2b\n");
// Replace single-line hunk, which produces a conflict right now. If our
// merge logic were based on interleaved delta, the hunk would be applied
// cleanly.
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "2a\n1A\n2b\n");
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
qpvuntsm b00f5b08 (conflict) 1
Rebased 1 descendant commits.
Working copy (@) now at: mzvwutvl 9655ef4d (empty) (no description set)
Parent commit (@-) : kkmpptxz a6531d0a 2
New conflicts appeared in 1 commits:
qpvuntsm b00f5b08 (conflict) 1
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new qpvuntsm
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_diffs(&work_dir, "mutable()"), @r#"
@ mzvwutvl 9655ef4d (empty) (no description set)
○ kkmpptxz a6531d0a 2
│ diff --git a/file1 b/file1
│ index 0000000000..2f87e8e465 100644
│ --- a/file1
│ +++ b/file1
│ @@ -1,11 +1,3 @@
│ -<<<<<<< conflict 1 of 1
│ -%%%%%%% diff from: kkmpptxz 9d700628 "2" (parents of absorbed revision)
│ -\\\\\\\ to: qpvuntsm aa6cb9bc "1" (absorb destination)
│ --2a
│ - 1a
│ --2b
│ -+++++++ absorbed changes (from zsuskuln 5d926f12)
│ 2a
│ 1A
│ 2b
│ ->>>>>>> conflict 1 of 1 ends
× qpvuntsm b00f5b08 (conflict) 1
│ diff --git a/file1 b/file1
~ new file mode 100644
index 0000000000..0000000000
--- /dev/null
+++ b/file1
@@ -0,0 +1,11 @@
+<<<<<<< conflict 1 of 1
+%%%%%%% diff from: kkmpptxz 9d700628 "2" (parents of absorbed revision)
+\\\\\\\ to: qpvuntsm aa6cb9bc "1" (absorb destination)
+-2a
+ 1a
+-2b
++++++++ absorbed changes (from zsuskuln 5d926f12)
+2a
+1A
+2b
+>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
}
#[test]
fn test_absorb_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", "-m0"]).success();
work_dir.write_file("file1", "0a\n");
work_dir.run_jj(["new", "-m1"]).success();
work_dir.write_file("file1", "1a\n1b\n0a\n");
work_dir.run_jj(["new", "-m2", "subject(0)"]).success();
work_dir.write_file("file1", "0a\n2a\n2b\n");
let output = work_dir.run_jj(["new", "-m3", "subject(1)", "subject(2)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: mzvwutvl 42875bf7 (empty) 3
Parent commit (@-) : kkmpptxz 9c66f62f 1
Parent commit (@-) : zsuskuln 6a3dcbcf 2
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
// Modify first and last lines, absorb from merge
work_dir.write_file("file1", "1A\n1b\n0a\n2a\n2B\n");
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 2 revisions:
zsuskuln a6fde7ea 2
kkmpptxz 00ecc958 1
Rebased 1 descendant commits.
Working copy (@) now at: mzvwutvl 30499858 (empty) 3
Parent commit (@-) : kkmpptxz 00ecc958 1
Parent commit (@-) : zsuskuln a6fde7ea 2
[EOF]
");
// Add hunk to merge revision
work_dir.write_file("file2", "3a\n");
// Absorb into merge
work_dir.run_jj(["new"]).success();
work_dir.write_file("file2", "3A\n");
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
mzvwutvl faf778a4 3
Working copy (@) now at: vruxwmqv cec519a1 (empty) (no description set)
Parent commit (@-) : mzvwutvl faf778a4 3
[EOF]
");
insta::assert_snapshot!(get_diffs(&work_dir, "mutable()"), @r"
@ vruxwmqv cec519a1 (empty) (no description set)
○ mzvwutvl faf778a4 3
├─╮ diff --git a/file2 b/file2
│ │ new file mode 100644
│ │ index 0000000000..44442d2d7b
│ │ --- /dev/null
│ │ +++ b/file2
│ │ @@ -0,0 +1,1 @@
│ │ +3A
│ ○ zsuskuln a6fde7ea 2
│ │ diff --git a/file1 b/file1
│ │ index eb6e8821f1..4907935b9f 100644
│ │ --- a/file1
│ │ +++ b/file1
│ │ @@ -1,1 +1,3 @@
│ │ 0a
│ │ +2a
│ │ +2B
○ │ kkmpptxz 00ecc958 1
├─╯ diff --git a/file1 b/file1
│ index eb6e8821f1..902dd8ef13 100644
│ --- a/file1
│ +++ b/file1
│ @@ -1,1 +1,3 @@
│ +1A
│ +1b
│ 0a
○ qpvuntsm d4f07be5 0
│ diff --git a/file1 b/file1
~ new file mode 100644
index 0000000000..eb6e8821f1
--- /dev/null
+++ b/file1
@@ -0,0 +1,1 @@
+0a
[EOF]
");
}
#[test]
fn test_absorb_discardable_merge_with_descendant() {
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", "-m0"]).success();
work_dir.write_file("file1", "0a\n");
work_dir.run_jj(["new", "-m1"]).success();
work_dir.write_file("file1", "1a\n1b\n0a\n");
work_dir.run_jj(["new", "-m2", "subject(0)"]).success();
work_dir.write_file("file1", "0a\n2a\n2b\n");
let output = work_dir.run_jj(["new", "subject(1)", "subject(2)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Working copy (@) now at: mzvwutvl ad00b91a (empty) (no description set)
Parent commit (@-) : kkmpptxz 9c66f62f 1
Parent commit (@-) : zsuskuln 6a3dcbcf 2
Added 0 files, modified 1 files, removed 0 files
[EOF]
");
// Modify first and last lines in the merge commit
work_dir.write_file("file1", "1A\n1b\n0a\n2a\n2B\n");
// Add new commit on top
work_dir.run_jj(["new", "-m3"]).success();
work_dir.write_file("file2", "3a\n");
// Then absorb the merge commit
let output = work_dir.run_jj(["absorb", "--from=@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 2 revisions:
zsuskuln a6cd8e87 2
kkmpptxz 98b7d214 1
Rebased 1 descendant commits.
Working copy (@) now at: royxmykx df946e9b 3
Parent commit (@-) : kkmpptxz 98b7d214 1
Parent commit (@-) : zsuskuln a6cd8e87 2
[EOF]
");
insta::assert_snapshot!(get_diffs(&work_dir, "mutable()"), @r"
@ royxmykx df946e9b 3
├─╮ diff --git a/file2 b/file2
│ │ new file mode 100644
│ │ index 0000000000..31cd755d20
│ │ --- /dev/null
│ │ +++ b/file2
│ │ @@ -0,0 +1,1 @@
│ │ +3a
│ ○ zsuskuln a6cd8e87 2
│ │ diff --git a/file1 b/file1
│ │ index eb6e8821f1..4907935b9f 100644
│ │ --- a/file1
│ │ +++ b/file1
│ │ @@ -1,1 +1,3 @@
│ │ 0a
│ │ +2a
│ │ +2B
○ │ kkmpptxz 98b7d214 1
├─╯ diff --git a/file1 b/file1
│ index eb6e8821f1..902dd8ef13 100644
│ --- a/file1
│ +++ b/file1
│ @@ -1,1 +1,3 @@
│ +1A
│ +1b
│ 0a
○ qpvuntsm d4f07be5 0
│ diff --git a/file1 b/file1
~ new file mode 100644
index 0000000000..eb6e8821f1
--- /dev/null
+++ b/file1
@@ -0,0 +1,1 @@
+0a
[EOF]
");
}
#[test]
fn test_absorb_conflict() {
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", "-m1"]).success();
work_dir.write_file("file1", "1a\n1b\n");
work_dir.run_jj(["new", "root()"]).success();
work_dir.write_file("file1", "2a\n2b\n");
let output = work_dir.run_jj(["rebase", "-r@", "-dsubject(1)"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Rebased 1 commits to destination
Working copy (@) now at: kkmpptxz 4ab5d3e5 (conflict) (no description set)
Parent commit (@-) : qpvuntsm e35bcaff 1
Added 0 files, modified 1 files, removed 0 files
Warning: There are unresolved conflicts at these paths:
file1 2-sided conflict
New conflicts appeared in 1 commits:
kkmpptxz 4ab5d3e5 (conflict) (no description set)
Hint: To resolve the conflicts, start by creating a commit on top of
the conflicted commit:
jj new kkmpptxz
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 conflict_content = work_dir.read_file("file1");
insta::assert_snapshot!(conflict_content, @r#"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: zzzzzzzz 00000000 (parents of rebased revision)
\\\\\\\ to: qpvuntsm e35bcaff "1" (rebase destination)
+1a
+1b
+++++++ kkmpptxz e05db987 (rebased revision)
2a
2b
>>>>>>> conflict 1 of 1 ends
"#);
// Cannot absorb from conflict
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Skipping file1: Is a conflict
Nothing changed.
[EOF]
");
// Cannot absorb from resolved conflict
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "1A\n1b\n2a\n2B\n");
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: Skipping file1: Is a conflict
Nothing changed.
[EOF]
");
}
#[test]
fn test_absorb_deleted_file() {
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", "-m1"]).success();
work_dir.write_file("file1", "1a\n");
work_dir.write_file("file2", "1a\n");
work_dir.write_file("file3", "");
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.write_file("file2", ""); // emptied
work_dir.remove_file("file3"); // no content change
// Since the destinations are chosen based on content diffs, file3 cannot be
// absorbed.
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
qpvuntsm 38af7fd3 1
Rebased 1 descendant commits.
Working copy (@) now at: kkmpptxz efd883f6 (no description set)
Parent commit (@-) : qpvuntsm 38af7fd3 1
Remaining changes:
D file3
[EOF]
");
insta::assert_snapshot!(get_diffs(&work_dir, "mutable()"), @r"
@ kkmpptxz efd883f6 (no description set)
│ diff --git a/file3 b/file3
│ deleted file mode 100644
│ index e69de29bb2..0000000000
○ qpvuntsm 38af7fd3 1
│ diff --git a/file2 b/file2
~ new file mode 100644
index 0000000000..e69de29bb2
diff --git a/file3 b/file3
new file mode 100644
index 0000000000..e69de29bb2
[EOF]
");
}
#[test]
fn test_absorb_deleted_file_with_multiple_hunks() {
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", "-m1"]).success();
work_dir.write_file("file1", "1a\n1b\n");
work_dir.write_file("file2", "1a\n");
work_dir.run_jj(["new", "-m2"]).success();
work_dir.write_file("file1", "1a\n");
work_dir.write_file("file2", "1a\n1b\n");
// These changes produce conflicts because
// - for file1, "1a\n" is deleted from the commit 1,
// - for file2, two consecutive hunks are deleted.
//
// Since file2 change is split to two separate hunks, the file deletion
// cannot be propagated. If we implement merging based on interleaved delta,
// the file2 change will apply cleanly. The file1 change might be split into
// "1a\n" deletion at the commit 1 and file deletion at the commit 2, but
// I'm not sure if that's intuitive.
work_dir.run_jj(["new"]).success();
work_dir.remove_file("file1");
work_dir.remove_file("file2");
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 2 revisions:
kkmpptxz af86b290 (conflict) 2
qpvuntsm 536f8cbe (conflict) 1
Rebased 1 descendant commits.
Working copy (@) now at: zsuskuln 3058e6b0 (no description set)
Parent commit (@-) : kkmpptxz af86b290 (conflict) 2
New conflicts appeared in 2 commits:
kkmpptxz af86b290 (conflict) 2
qpvuntsm 536f8cbe (conflict) 1
Hint: To resolve the conflicts, start by creating a commit on top of
the first conflicted commit:
jj new qpvuntsm
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.
Remaining changes:
D file2
[EOF]
");
insta::assert_snapshot!(get_diffs(&work_dir, "mutable()"), @r#"
@ zsuskuln 3058e6b0 (no description set)
│ diff --git a/file2 b/file2
│ deleted file mode 100644
│ index 0000000000..0000000000
│ --- a/file2
│ +++ /dev/null
│ @@ -1,8 +0,0 @@
│ -<<<<<<< conflict 1 of 1
│ -%%%%%%% diff from: kkmpptxz 33662096 "2" (parents of absorbed revision)
│ -\\\\\\\ to: kkmpptxz 33662096 "2" (absorb destination)
│ --1a
│ - 1b
│ -+++++++ absorbed changes (from zsuskuln d6492c8f)
│ -1a
│ ->>>>>>> conflict 1 of 1 ends
× kkmpptxz af86b290 (conflict) 2
│ diff --git a/file1 b/file1
│ deleted file mode 100644
│ index 0000000000..0000000000
│ --- a/file1
│ +++ /dev/null
│ @@ -1,7 +0,0 @@
│ -<<<<<<< conflict 1 of 1
│ -%%%%%%% diff from: kkmpptxz 33662096 "2" (parents of absorbed revision)
│ -\\\\\\\ to: qpvuntsm 66b2ce5b "1" (absorb destination)
│ - 1a
│ -+1b
│ -+++++++ absorbed changes (from zsuskuln d6492c8f)
│ ->>>>>>> conflict 1 of 1 ends
│ diff --git a/file2 b/file2
│ --- a/file2
│ +++ b/file2
│ @@ -1,8 +1,8 @@
│ <<<<<<< conflict 1 of 1
│ %%%%%%% diff from: kkmpptxz 33662096 "2" (parents of absorbed revision)
│ -\\\\\\\ to: qpvuntsm 66b2ce5b "1" (absorb destination)
│ - 1a
│ --1b
│ +\\\\\\\ to: kkmpptxz 33662096 "2" (absorb destination)
│ +-1a
│ + 1b
│ +++++++ absorbed changes (from zsuskuln d6492c8f)
│ -1b
│ +1a
│ >>>>>>> conflict 1 of 1 ends
× qpvuntsm 536f8cbe (conflict) 1
│ diff --git a/file1 b/file1
~ new file mode 100644
index 0000000000..0000000000
--- /dev/null
+++ b/file1
@@ -0,0 +1,7 @@
+<<<<<<< conflict 1 of 1
+%%%%%%% diff from: kkmpptxz 33662096 "2" (parents of absorbed revision)
+\\\\\\\ to: qpvuntsm 66b2ce5b "1" (absorb destination)
+ 1a
++1b
++++++++ absorbed changes (from zsuskuln d6492c8f)
+>>>>>>> conflict 1 of 1 ends
diff --git a/file2 b/file2
new file mode 100644
index 0000000000..0000000000
--- /dev/null
+++ b/file2
@@ -0,0 +1,8 @@
+<<<<<<< conflict 1 of 1
+%%%%%%% diff from: kkmpptxz 33662096 "2" (parents of absorbed revision)
+\\\\\\\ to: qpvuntsm 66b2ce5b "1" (absorb destination)
+ 1a
+-1b
++++++++ absorbed changes (from zsuskuln d6492c8f)
+1b
+>>>>>>> conflict 1 of 1 ends
[EOF]
"#);
}
#[test]
fn test_absorb_file_mode() {
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", "-m1"]).success();
work_dir.write_file("file1", "1a\n");
work_dir.run_jj(["file", "chmod", "x", "file1"]).success();
// Modify content and mode
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "1A\n");
work_dir.run_jj(["file", "chmod", "n", "file1"]).success();
// Mode change shouldn't be absorbed
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
qpvuntsm 2a0c7f1d 1
Rebased 1 descendant commits.
Working copy (@) now at: zsuskuln 8ca9761d (no description set)
Parent commit (@-) : qpvuntsm 2a0c7f1d 1
Remaining changes:
M file1
[EOF]
");
insta::assert_snapshot!(get_diffs(&work_dir, "mutable()"), @r"
@ zsuskuln 8ca9761d (no description set)
│ diff --git a/file1 b/file1
│ old mode 100755
│ new mode 100644
○ qpvuntsm 2a0c7f1d 1
│ diff --git a/file1 b/file1
~ new file mode 100755
index 0000000000..268de3f3ec
--- /dev/null
+++ b/file1
@@ -0,0 +1,1 @@
+1A
[EOF]
");
}
#[test]
fn test_absorb_from_into() {
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", "-m1"]).success();
work_dir.write_file("file1", "1a\n1b\n1c\n");
work_dir.run_jj(["new", "-m2"]).success();
work_dir.write_file("file1", "1a\n2a\n1b\n1c\n2b\n");
// Line "X" and "Z" have unambiguous adjacent line within the destinations
// range. Line "Y" doesn't have such line.
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "1a\nX\n2a\n1b\nY\n1c\n2b\nZ\n");
let output = work_dir.run_jj(["absorb", "--into=@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
kkmpptxz cae507ef 2
Rebased 1 descendant commits.
Working copy (@) now at: zsuskuln f02fd9ea (no description set)
Parent commit (@-) : kkmpptxz cae507ef 2
Remaining changes:
M file1
[EOF]
");
insta::assert_snapshot!(get_diffs(&work_dir, "@-::"), @r"
@ zsuskuln f02fd9ea (no description set)
│ diff --git a/file1 b/file1
│ index faf62af049..c2d0b12547 100644
│ --- a/file1
│ +++ b/file1
│ @@ -2,6 +2,7 @@
│ X
│ 2a
│ 1b
│ +Y
│ 1c
│ 2b
│ Z
○ kkmpptxz cae507ef 2
│ diff --git a/file1 b/file1
~ index 352e9b3794..faf62af049 100644
--- a/file1
+++ b/file1
@@ -1,3 +1,7 @@
1a
+X
+2a
1b
1c
+2b
+Z
[EOF]
");
// Absorb all lines from the working-copy parent. An empty commit won't be
// discarded because "absorb" isn't a command to squash commit descriptions.
let output = work_dir.run_jj(["absorb", "--from=@-"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
rlvkpnrz ddaed33d 1
Rebased 2 descendant commits.
Working copy (@) now at: zsuskuln 3652e5e5 (no description set)
Parent commit (@-) : kkmpptxz 7f4339e7 (empty) 2
[EOF]
");
insta::assert_snapshot!(get_diffs(&work_dir, "mutable()"), @r"
@ zsuskuln 3652e5e5 (no description set)
│ diff --git a/file1 b/file1
│ index faf62af049..c2d0b12547 100644
│ --- a/file1
│ +++ b/file1
│ @@ -2,6 +2,7 @@
│ X
│ 2a
│ 1b
│ +Y
│ 1c
│ 2b
│ Z
○ kkmpptxz 7f4339e7 (empty) 2
○ rlvkpnrz ddaed33d 1
│ diff --git a/file1 b/file1
│ new file mode 100644
│ index 0000000000..faf62af049
│ --- /dev/null
│ +++ b/file1
│ @@ -0,0 +1,7 @@
│ +1a
│ +X
│ +2a
│ +1b
│ +1c
│ +2b
│ +Z
○ qpvuntsm e8849ae1 (empty) (no description set)
│
~
[EOF]
");
}
#[test]
fn test_absorb_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.run_jj(["describe", "-m1"]).success();
work_dir.write_file("file1", "1a\n");
work_dir.write_file("file2", "1a\n");
// Modify both files
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "1A\n");
work_dir.write_file("file2", "1A\n");
let output = work_dir.run_jj(["absorb", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Warning: No matching entries for paths: nonexistent
Nothing changed.
[EOF]
");
let output = work_dir.run_jj(["absorb", "file1"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
qpvuntsm ca07fabe 1
Rebased 1 descendant commits.
Working copy (@) now at: kkmpptxz 4d80ada8 (no description set)
Parent commit (@-) : qpvuntsm ca07fabe 1
Remaining changes:
M file2
[EOF]
");
insta::assert_snapshot!(get_diffs(&work_dir, "mutable()"), @r"
@ kkmpptxz 4d80ada8 (no description set)
│ diff --git a/file2 b/file2
│ index a8994dc188..268de3f3ec 100644
│ --- a/file2
│ +++ b/file2
│ @@ -1,1 +1,1 @@
│ -1a
│ +1A
○ qpvuntsm ca07fabe 1
│ diff --git a/file1 b/file1
~ new file mode 100644
index 0000000000..268de3f3ec
--- /dev/null
+++ b/file1
@@ -0,0 +1,1 @@
+1A
diff --git a/file2 b/file2
new file mode 100644
index 0000000000..a8994dc188
--- /dev/null
+++ b/file2
@@ -0,0 +1,1 @@
+1a
[EOF]
");
}
#[test]
fn test_absorb_immutable() {
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("revset-aliases.'immutable_heads()' = 'present(main)'");
work_dir.run_jj(["describe", "-m1"]).success();
work_dir.write_file("file1", "1a\n1b\n");
work_dir.run_jj(["new", "-m2"]).success();
work_dir
.run_jj(["bookmark", "set", "-r@-", "main"])
.success();
work_dir.write_file("file1", "1a\n1b\n2a\n2b\n");
work_dir.run_jj(["new"]).success();
work_dir.write_file("file1", "1A\n1b\n2a\n2B\n");
// Immutable revisions are excluded by default
let output = work_dir.run_jj(["absorb"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Absorbed changes into 1 revisions:
kkmpptxz e68cc3e2 2
Rebased 1 descendant commits.
Working copy (@) now at: mzvwutvl 88443af7 (no description set)
Parent commit (@-) : kkmpptxz e68cc3e2 2
Remaining changes:
M file1
[EOF]
");
// Immutable revisions shouldn't be rewritten
let output = work_dir.run_jj(["absorb", "--into=all()"]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Commit e35bcaffcb55 is immutable
Hint: Could not modify commit: qpvuntsm e35bcaff main | 1
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]
"#);
insta::assert_snapshot!(get_diffs(&work_dir, ".."), @r"
@ mzvwutvl 88443af7 (no description set)
│ diff --git a/file1 b/file1
│ index 75e4047831..428796ca20 100644
│ --- a/file1
│ +++ b/file1
│ @@ -1,4 +1,4 @@
│ -1a
│ +1A
│ 1b
│ 2a
│ 2B
○ kkmpptxz e68cc3e2 2
│ diff --git a/file1 b/file1
│ index 8c5268f893..75e4047831 100644
│ --- a/file1
│ +++ b/file1
│ @@ -1,2 +1,4 @@
│ 1a
│ 1b
│ +2a
│ +2B
◆ qpvuntsm e35bcaff 1
│ diff --git a/file1 b/file1
~ new file mode 100644
index 0000000000..8c5268f893
--- /dev/null
+++ b/file1
@@ -0,0 +1,2 @@
+1a
+1b
[EOF]
");
}
#[must_use]
fn get_diffs(work_dir: &TestWorkDir, revision: &str) -> CommandOutput {
let template = r#"format_commit_summary_with_refs(self, "") ++ "\n""#;
work_dir.run_jj(["log", "-r", revision, "-T", template, "--git"])
}
#[must_use]
fn get_evolog(work_dir: &TestWorkDir, revision: &str) -> CommandOutput {
let template = r#"format_commit_summary_with_refs(commit, "") ++ "\n""#;
work_dir.run_jj(["evolog", "-r", revision, "-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_remotes.rs | cli/tests/test_git_remotes.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::fs;
use std::io::Write as _;
use std::path::Path;
use std::path::PathBuf;
use indoc::indoc;
use testutils::git;
use crate::common::TestEnvironment;
fn read_git_config(repo_path: &Path) -> String {
let git_config = fs::read_to_string(repo_path.join(".jj/repo/store/git/config"))
.or_else(|_| fs::read_to_string(repo_path.join(".git/config")))
.unwrap();
git_config
.split_inclusive('\n')
.filter(|line| {
// Filter out non‐portable values.
[
"\tfilemode =",
"\tsymlinks =",
"\tignorecase =",
"\tprecomposeunicode =",
]
.iter()
.all(|prefix| !line.to_ascii_lowercase().starts_with(prefix))
})
.collect()
}
#[test]
fn test_git_remotes() {
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(["git", "remote", "list"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "add", "foo", "http://example.com/repo/foo"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "add", "bar", "http://example.com/repo/bar"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj([
"git",
"remote",
"add",
"baz",
"http://example.com/repo/baz",
"--push-url",
"git@example.com:repo/baz",
]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
bar http://example.com/repo/bar
baz http://example.com/repo/baz (push: git@example.com:repo/baz)
foo http://example.com/repo/foo
[EOF]
");
let output = work_dir.run_jj(["git", "remote", "remove", "foo"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
bar http://example.com/repo/bar
baz http://example.com/repo/baz (push: git@example.com:repo/baz)
[EOF]
");
let output = work_dir.run_jj(["git", "remote", "remove", "nonexistent"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No git remote named 'nonexistent'
[EOF]
[exit status: 1]
");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "bar"]
url = http://example.com/repo/bar
fetch = +refs/heads/*:refs/remotes/bar/*
[remote "baz"]
url = http://example.com/repo/baz
pushurl = git@example.com:repo/baz
fetch = +refs/heads/*:refs/remotes/baz/*
"#);
}
#[test]
fn test_git_remote_add() {
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(["git", "remote", "add", "foo", "http://example.com/repo/foo"])
.success();
let output = work_dir.run_jj([
"git",
"remote",
"add",
"foo",
"http://example.com/repo/foo2",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remote named 'foo' already exists
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["git", "remote", "add", "git", "http://example.com/repo/git"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remote named 'git' is reserved for local Git repository
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
foo http://example.com/repo/foo
[EOF]
");
}
#[test]
fn test_git_remote_with_fetch_tags() {
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(["git", "remote", "add", "foo", "http://example.com/repo"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj([
"git",
"remote",
"add",
"foo-included",
"http://example.com/repo",
"--fetch-tags",
"included",
]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj([
"git",
"remote",
"add",
"foo-all",
"http://example.com/repo",
"--fetch-tags",
"all",
]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj([
"git",
"remote",
"add",
"foo-none",
"http://example.com/repo",
"--fetch-tags",
"none",
]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "foo"]
url = http://example.com/repo
fetch = +refs/heads/*:refs/remotes/foo/*
[remote "foo-included"]
url = http://example.com/repo
fetch = +refs/heads/*:refs/remotes/foo-included/*
[remote "foo-all"]
url = http://example.com/repo
tagOpt = --tags
fetch = +refs/heads/*:refs/remotes/foo-all/*
[remote "foo-none"]
url = http://example.com/repo
tagOpt = --no-tags
fetch = +refs/heads/*:refs/remotes/foo-none/*
"#);
}
#[test]
fn test_git_remote_set_url() {
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(["git", "remote", "add", "foo", "http://example.com/repo/foo"])
.success();
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"bar",
"http://example.com/repo/bar",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No git remote named 'bar'
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"git",
"http://example.com/repo/git",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remote named 'git' is reserved for local Git repository
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"foo",
"http://example.com/repo/bar",
]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
foo http://example.com/repo/bar
[EOF]
");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "foo"]
url = http://example.com/repo/bar
fetch = +refs/heads/*:refs/remotes/foo/*
"#);
// explicitly set the push url to the same value as fetch works.
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"foo",
"--push",
"https://example.com/repo/bar",
]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "foo"]
url = http://example.com/repo/bar
pushurl = https://example.com/repo/bar
fetch = +refs/heads/*:refs/remotes/foo/*
"#);
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"foo",
"--push",
"git@example.com:repo/bar",
]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "foo"]
url = http://example.com/repo/bar
pushurl = git@example.com:repo/bar
fetch = +refs/heads/*:refs/remotes/foo/*
"#);
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"foo",
"--fetch",
"http://example.com/repo/bar2",
]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "foo"]
url = http://example.com/repo/bar2
pushurl = git@example.com:repo/bar
fetch = +refs/heads/*:refs/remotes/foo/*
"#);
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"foo",
"http://example.com/repo/bar",
]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "foo"]
url = http://example.com/repo/bar
pushurl = git@example.com:repo/bar
fetch = +refs/heads/*:refs/remotes/foo/*
"#);
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"foo",
"https://example.com/repo/baz",
"--fetch",
"https://example.com/repo/bar2",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
error: the argument '[URL]' cannot be used with '--fetch <FETCH>'
Usage: jj git remote set-url <REMOTE> <URL>
For more information, try '--help'.
[EOF]
[exit status: 2]
");
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"foo",
"https://example.com/repo/baz",
"--push",
"git@example.com:/repo/baz",
]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "foo"]
url = https://example.com/repo/baz
pushurl = git@example.com:/repo/baz
fetch = +refs/heads/*:refs/remotes/foo/*
"#);
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"foo",
"--fetch",
"https://example.com/repo/bar",
"--push",
"git@example.com:/repo/bar",
]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "foo"]
url = https://example.com/repo/bar
pushurl = git@example.com:/repo/bar
fetch = +refs/heads/*:refs/remotes/foo/*
"#);
}
#[test]
fn test_git_remote_relative_path() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// Relative path using OS-native separator
let path = PathBuf::from_iter(["..", "native", "sep"]);
work_dir
.run_jj(["git", "remote", "add", "foo", path.to_str().unwrap()])
.success();
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
foo $TEST_ENV/native/sep
[EOF]
");
// Relative path using UNIX separator
test_env
.run_jj_in(
".",
["-Rrepo", "git", "remote", "set-url", "foo", "unix/sep"],
)
.success();
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
foo $TEST_ENV/unix/sep
[EOF]
");
}
#[test]
fn test_git_remote_rename() {
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(["git", "remote", "add", "foo", "http://example.com/repo/foo"])
.success();
work_dir
.run_jj(["git", "remote", "add", "baz", "http://example.com/repo/baz"])
.success();
let output = work_dir.run_jj(["git", "remote", "rename", "bar", "foo"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: No git remote named 'bar'
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["git", "remote", "rename", "foo", "baz"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remote named 'baz' already exists
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["git", "remote", "rename", "foo", "git"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remote named 'git' is reserved for local Git repository
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["git", "remote", "rename", "foo", "bar"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
bar http://example.com/repo/foo
baz http://example.com/repo/baz
[EOF]
");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "baz"]
url = http://example.com/repo/baz
fetch = +refs/heads/*:refs/remotes/baz/*
[remote "bar"]
url = http://example.com/repo/foo
fetch = +refs/heads/*:refs/remotes/bar/*
"#);
}
#[test]
fn test_git_remote_named_git() {
let test_env = TestEnvironment::default();
// Existing remote named 'git' shouldn't block the repo initialization.
let work_dir = test_env.work_dir("repo");
git::init(work_dir.root());
git::add_remote(work_dir.root(), "git", "http://example.com/repo/repo");
work_dir.run_jj(["git", "init", "--git-repo=."]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
// The remote can be renamed.
let output = work_dir.run_jj(["git", "remote", "rename", "git", "bar"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
bar http://example.com/repo/repo
[EOF]
------- stderr -------
Done importing changes from the underlying Git repo.
[EOF]
");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = false
logallrefupdates = true
[remote "bar"]
url = http://example.com/repo/repo
fetch = +refs/heads/*:refs/remotes/bar/*
"#);
// @git bookmark shouldn't be renamed.
let output = work_dir.run_jj(["log", "-rmain@git", "-Tbookmarks"]);
insta::assert_snapshot!(output, @r"
@ main
│
~
[EOF]
");
// The remote cannot be renamed back by jj.
let output = work_dir.run_jj(["git", "remote", "rename", "bar", "git"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remote named 'git' is reserved for local Git repository
[EOF]
[exit status: 1]
");
// Reinitialize the repo with remote named 'git'.
work_dir.remove_dir_all(".jj");
git::rename_remote(work_dir.root(), "bar", "git");
work_dir.run_jj(["git", "init", "--git-repo=."]).success();
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = false
logallrefupdates = true
[remote "git"]
url = http://example.com/repo/repo
fetch = +refs/heads/*:refs/remotes/git/*
"#);
// The remote can also be removed.
let output = work_dir.run_jj(["git", "remote", "remove", "git"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r"
[core]
repositoryformatversion = 0
bare = false
logallrefupdates = true
");
// @git bookmark shouldn't be removed.
let output = work_dir.run_jj(["log", "-rmain@git", "-Tbookmarks"]);
insta::assert_snapshot!(output, @r"
○ main
│
~
[EOF]
");
}
#[test]
fn test_git_remote_with_slashes() {
let test_env = TestEnvironment::default();
// Existing remote with slashes shouldn't block the repo initialization.
let work_dir = test_env.work_dir("repo");
git::init(work_dir.root());
git::add_remote(
work_dir.root(),
"slash/origin",
"http://example.com/repo/repo",
);
work_dir.run_jj(["git", "init", "--git-repo=."]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
// Cannot add remote with a slash via `jj`
let output = work_dir.run_jj([
"git",
"remote",
"add",
"another/origin",
"http://examples.org/repo/repo",
]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remotes with slashes are incompatible with jj: another/origin
[EOF]
[exit status: 1]
");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
slash/origin http://example.com/repo/repo
[EOF]
");
// The remote can be renamed.
let output = work_dir.run_jj(["git", "remote", "rename", "slash/origin", "origin"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
origin http://example.com/repo/repo
[EOF]
");
// The remote cannot be renamed back by jj.
let output = work_dir.run_jj(["git", "remote", "rename", "origin", "slash/origin"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Git remotes with slashes are incompatible with jj: slash/origin
[EOF]
[exit status: 1]
");
// Reinitialize the repo with remote with slashes
work_dir.remove_dir_all(".jj");
git::rename_remote(work_dir.root(), "origin", "slash/origin");
work_dir.run_jj(["git", "init", "--git-repo=."]).success();
// The remote can also be removed.
let output = work_dir.run_jj(["git", "remote", "remove", "slash/origin"]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @"");
// @git bookmark shouldn't be removed.
let output = work_dir.run_jj(["log", "-rmain@git", "-Tbookmarks"]);
insta::assert_snapshot!(output, @r"
○ main
│
~
[EOF]
");
}
#[test]
fn test_git_remote_with_branch_config() {
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(["git", "remote", "add", "foo", "http://example.com/repo"]);
insta::assert_snapshot!(output, @"");
let mut config_file = fs::OpenOptions::new()
.append(true)
.open(work_dir.root().join(".jj/repo/store/git/config"))
.unwrap();
// `git clone` adds branch configuration like this.
let eol = if cfg!(windows) { "\r\n" } else { "\n" };
write!(config_file, "[branch \"test\"]{eol}").unwrap();
write!(config_file, "\tremote = foo{eol}").unwrap();
write!(config_file, "\tmerge = refs/heads/test{eol}").unwrap();
drop(config_file);
let output = work_dir.run_jj(["git", "remote", "rename", "foo", "bar"]);
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[branch "test"]
remote = bar
merge = refs/heads/test
[remote "bar"]
url = http://example.com/repo
fetch = +refs/heads/*:refs/remotes/bar/*
"#);
}
#[test]
fn test_git_remote_with_global_git_remote_config() {
let mut test_env = TestEnvironment::default();
test_env.work_dir("").write_file(
"git-config",
indoc! {r#"
[remote "origin"]
prune = true
[remote "foo"]
url = htps://example.com/repo/foo
fetch = +refs/heads/*:refs/remotes/foo/*
"#},
);
test_env.add_env_var("GIT_CONFIG_GLOBAL", test_env.env_root().join("git-config"));
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["git", "remote", "list"]);
// Complete remotes from the global configuration are listed.
//
// `git remote -v` lists all remotes from the global configuration,
// even incomplete ones like `origin`. This is inconsistent with
// the other `git remote` commands, which ignore the global
// configuration (even `git remote get-url`).
insta::assert_snapshot!(output, @r"
foo htps://example.com/repo/foo
[EOF]
");
let output = work_dir.run_jj(["git", "remote", "rename", "foo", "bar"]);
// Divergence from Git: we read the remote from the global
// configuration and write it back out. Git will use the global
// configuration for commands like `git remote -v`, `git fetch`,
// and `git push`, but `git remote rename`, `git remote remove`,
// `git remote set-url`, etc., will ignore it.
//
// This behavior applies to `jj git remote remove` and
// `jj git remote set-url` as well. It would be hard to change due
// to gitoxide’s model, but hopefully it’s relatively harmless.
insta::assert_snapshot!(output, @"");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "bar"]
url = htps://example.com/repo/foo
fetch = +refs/heads/*:refs/remotes/bar/*
"#);
// This has the unfortunate consequence that the original remote
// still exists after renaming.
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
bar htps://example.com/repo/foo
foo htps://example.com/repo/foo
[EOF]
");
let output = work_dir.run_jj([
"git",
"remote",
"add",
"origin",
"http://example.com/repo/origin/1",
]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj([
"git",
"remote",
"set-url",
"origin",
"https://example.com/repo/origin/2",
]);
insta::assert_snapshot!(output, @"");
let output = work_dir.run_jj(["git", "remote", "list"]);
insta::assert_snapshot!(output, @r"
bar htps://example.com/repo/foo
foo htps://example.com/repo/foo
origin https://example.com/repo/origin/2
[EOF]
");
insta::assert_snapshot!(read_git_config(work_dir.root()), @r#"
[core]
repositoryformatversion = 0
bare = true
logallrefupdates = false
[remote "bar"]
url = htps://example.com/repo/foo
fetch = +refs/heads/*:refs/remotes/bar/*
[remote "origin"]
url = https://example.com/repo/origin/2
fetch = +refs/heads/*:refs/remotes/origin/*
"#);
}
| 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_template.rs | cli/tests/test_commit_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 indoc::indoc;
use regex::Regex;
use testutils::git;
use crate::common::TestEnvironment;
#[test]
fn test_log_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(["new"]).success();
work_dir.run_jj(["new", "@-"]).success();
work_dir.run_jj(["new", "@", "@-"]).success();
let template =
r#"commit_id ++ "\nP: " ++ parents.len() ++ " " ++ parents.map(|c| c.commit_id()) ++ "\n""#;
let output = work_dir.run_jj(["log", "-T", template]);
insta::assert_snapshot!(output, @r"
@ 8b93ef7a3ceefa4e4b1a506945588dd0da2d9e3e
├─╮ P: 2 1c1c95df80e53b1e654608d7589f5baabb10ebb2 e8849ae12c709f2321908879bc724fdb2ab8a781
○ │ 1c1c95df80e53b1e654608d7589f5baabb10ebb2
├─╯ P: 1 e8849ae12c709f2321908879bc724fdb2ab8a781
○ e8849ae12c709f2321908879bc724fdb2ab8a781
│ P: 1 0000000000000000000000000000000000000000
◆ 0000000000000000000000000000000000000000
P: 0
[EOF]
");
// List<Commit> can be filtered
let template =
r#""P: " ++ parents.filter(|c| !c.root()).map(|c| c.commit_id().short()) ++ "\n""#;
let output = work_dir.run_jj(["log", "-T", template]);
insta::assert_snapshot!(output, @r"
@ P: 1c1c95df80e5 e8849ae12c70
├─╮
○ │ P: e8849ae12c70
├─╯
○ P:
◆ P:
[EOF]
");
let template = r#"parents.map(|c| c.commit_id().shortest(4))"#;
let output = work_dir.run_jj(["log", "-T", template, "-r@", "--color=always"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m [1m[38;5;4m1[0m[38;5;8mc1c[39m [1m[38;5;4me[0m[38;5;8m884[39m
│
~
[EOF]
");
// Commit object isn't printable
let output = work_dir.run_jj(["log", "-T", "parents"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Failed to parse template: Expected expression of type `Template`, but actual type is `List<Commit>`
Caused by: --> 1:1
|
1 | parents
| ^-----^
|
= Expected expression of type `Template`, but actual type is `List<Commit>`
[EOF]
[exit status: 1]
");
// Redundant argument passed to keyword method
let template = r#"parents.map(|c| c.commit_id(""))"#;
let output = work_dir.run_jj(["log", "-T", template]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Failed to parse template: Function `commit_id`: Expected 0 arguments
Caused by: --> 1:29
|
1 | parents.map(|c| c.commit_id(""))
| ^^
|
= Function `commit_id`: Expected 0 arguments
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_log_author_timestamp() {
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", "author.timestamp()"]);
insta::assert_snapshot!(output, @r"
@ 2001-02-03 04:05:09.000 +07:00
○ 2001-02-03 04:05:08.000 +07:00
◆ 1970-01-01 00:00:00.000 +00:00
[EOF]
");
}
#[test]
fn test_log_author_timestamp_ago() {
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 template = r#"author.timestamp().ago() ++ "\n""#;
let output = work_dir
.run_jj(&["log", "--no-graph", "-T", template])
.success();
let line_re = Regex::new(r"[0-9]+ years ago").unwrap();
assert!(
output.stdout.raw().lines().all(|x| line_re.is_match(x)),
"expected every line to match regex"
);
}
#[test]
fn test_log_author_timestamp_utc() {
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", "author.timestamp().utc()"]);
insta::assert_snapshot!(output, @r"
@ 2001-02-02 21:05:07.000 +00:00
◆ 1970-01-01 00:00:00.000 +00:00
[EOF]
");
}
#[cfg(unix)]
#[test]
fn test_log_author_timestamp_local() {
let mut test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
test_env.add_env_var("TZ", "UTC-05:30");
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["log", "-T", "author.timestamp().local()"]);
insta::assert_snapshot!(output, @r"
@ 2001-02-03 08:05:07.000 +11:00
◆ 1970-01-01 11:00:00.000 +11:00
[EOF]
");
test_env.add_env_var("TZ", "UTC+10:00");
let work_dir = test_env.work_dir("repo");
let output = work_dir.run_jj(["log", "-T", "author.timestamp().local()"]);
insta::assert_snapshot!(output, @r"
@ 2001-02-03 08:05:07.000 +11:00
◆ 1970-01-01 11:00:00.000 +11:00
[EOF]
");
}
#[test]
fn test_log_author_timestamp_after_before() {
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();
let template = r#"
separate(" ",
author.timestamp(),
":",
if(author.timestamp().after("1969"), "(after 1969)", "(before 1969)"),
if(author.timestamp().before("1975"), "(before 1975)", "(after 1975)"),
if(author.timestamp().before("now"), "(before now)", "(after now)")
) ++ "\n""#;
let output = work_dir.run_jj(["log", "--no-graph", "-T", template]);
insta::assert_snapshot!(output, @r"
2001-02-03 04:05:08.000 +07:00 : (after 1969) (after 1975) (before now)
1970-01-01 00:00:00.000 +00:00 : (after 1969) (before 1975) (before now)
[EOF]
");
// Should display error with invalid date.
let template = r#"author.timestamp().after("invalid date")"#;
let output = work_dir.run_jj(["log", "-r@", "--no-graph", "-T", template]);
insta::assert_snapshot!(output, @r#"
------- stderr -------
Error: Failed to parse template: Invalid date pattern
Caused by:
1: --> 1:26
|
1 | author.timestamp().after("invalid date")
| ^------------^
|
= Invalid date pattern
2: expected unsupported identifier as position 0..7
[EOF]
[exit status: 1]
"#);
}
#[test]
fn test_mine_is_true_when_author_is_user() {
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=user.email=johndoe@example.com",
"--config=user.name=John Doe",
"new",
])
.success();
let output = work_dir.run_jj([
"log",
"-T",
r#"coalesce(if(mine, "mine"), author.email(), email_placeholder)"#,
]);
insta::assert_snapshot!(output, @r"
@ johndoe@example.com
○ mine
◆ (no email set)
[EOF]
");
}
#[test]
fn test_log_json() {
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", r#"-Tjson(self) ++ "\n""#]);
insta::assert_snapshot!(output, @r#"
@ {"commit_id":"b1cb6b2f9141e6ffee18532a8bf9a2075ca02606","parents":["68a505386f936fff6d718f55005e77ea72589bc1"],"change_id":"kkmpptxzrspxrzommnulwmwkkqwworpl","description":"second\n","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"}}
○ {"commit_id":"68a505386f936fff6d718f55005e77ea72589bc1","parents":["0000000000000000000000000000000000000000"],"change_id":"qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu","description":"first\n","author":{"name":"Test User","email":"test.user@example.com","timestamp":"2001-02-03T04:05:08+07:00"},"committer":{"name":"Test User","email":"test.user@example.com","timestamp":"2001-02-03T04:05:08+07:00"}}
◆ {"commit_id":"0000000000000000000000000000000000000000","parents":[],"change_id":"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz","description":"","author":{"name":"","email":"","timestamp":"1970-01-01T00:00:00Z"},"committer":{"name":"","email":"","timestamp":"1970-01-01T00:00:00Z"}}
[EOF]
"#);
}
#[test]
fn test_log_default() {
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", "description 1"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "my-bookmark"])
.success();
// Test default log output format
let output = work_dir.run_jj(["log"]);
insta::assert_snapshot!(output, @r"
@ kkmpptxz test.user@example.com 2001-02-03 08:05:09 my-bookmark c938c088
│ (empty) description 1
○ qpvuntsm test.user@example.com 2001-02-03 08:05:08 007859d3
│ add a file
◆ zzzzzzzz root() 00000000
[EOF]
");
// Color
let output = work_dir.run_jj(["log", "--color=always"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m [1m[38;5;13mk[38;5;8mkmpptxz[39m [38;5;3mtest.user@example.com[39m [38;5;14m2001-02-03 08:05:09[39m [38;5;13mmy-bookmark[39m [38;5;12mc[38;5;8m938c088[39m[0m
│ [1m[38;5;10m(empty)[39m description 1[0m
○ [1m[38;5;5mq[0m[38;5;8mpvuntsm[39m [38;5;3mtest.user@example.com[39m [38;5;6m2001-02-03 08:05:08[39m [1m[38;5;4m007[0m[38;5;8m859d3[39m
│ add a file
[1m[38;5;14m◆[0m [1m[38;5;5mz[0m[38;5;8mzzzzzzz[39m [38;5;2mroot()[39m [1m[38;5;4m000[0m[38;5;8m00000[39m
[EOF]
");
// Color without graph
let output = work_dir.run_jj(["log", "--color=always", "--no-graph"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;13mk[38;5;8mkmpptxz[39m [38;5;3mtest.user@example.com[39m [38;5;14m2001-02-03 08:05:09[39m [38;5;13mmy-bookmark[39m [38;5;12mc[38;5;8m938c088[39m[0m
[1m[38;5;10m(empty)[39m description 1[0m
[1m[38;5;5mq[0m[38;5;8mpvuntsm[39m [38;5;3mtest.user@example.com[39m [38;5;6m2001-02-03 08:05:08[39m [1m[38;5;4m007[0m[38;5;8m859d3[39m
add a file
[1m[38;5;5mz[0m[38;5;8mzzzzzzz[39m [38;5;2mroot()[39m [1m[38;5;4m000[0m[38;5;8m00000[39m
[EOF]
");
}
#[test]
fn test_log_default_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(["log"]);
insta::assert_snapshot!(output, @r"
◆ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_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(["log", "-T", template, "--no-graph"]);
work_dir
.run_jj(["--config=user.email=''", "--config=user.name=''", "new"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "my-bookmark"])
.success();
insta::assert_snapshot!(render(r#"builtin_log_oneline"#), @r"
rlvkpnrz (no email set) 2001-02-03 08:05:08 my-bookmark aec3ec96 (empty) (no description set)
qpvuntsm test.user 2001-02-03 08:05:07 e8849ae1 (empty) (no description set)
zzzzzzzz root() 00000000
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_log_compact"#), @r"
rlvkpnrz (no email set) 2001-02-03 08:05:08 my-bookmark aec3ec96
(empty) (no description set)
qpvuntsm test.user@example.com 2001-02-03 08:05:07 e8849ae1
(empty) (no description set)
zzzzzzzz root() 00000000
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_log_comfortable"#), @r"
rlvkpnrz (no email set) 2001-02-03 08:05:08 my-bookmark aec3ec96
(empty) (no description set)
qpvuntsm test.user@example.com 2001-02-03 08:05:07 e8849ae1
(empty) (no description set)
zzzzzzzz root() 00000000
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_log_detailed"#), @r"
Commit ID: aec3ec964d0771edea9da48a2a170bc6ffa1c725
Change ID: rlvkpnrzqnoowoytxnquwvuryrwnrmlp
Bookmarks: my-bookmark
Author : (no name set) <(no email set)> (2001-02-03 08:05:08)
Committer: (no name set) <(no email set)> (2001-02-03 08:05:08)
(no description set)
Commit ID: e8849ae12c709f2321908879bc724fdb2ab8a781
Change ID: qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
Author : Test User <test.user@example.com> (2001-02-03 08:05:07)
Committer: Test User <test.user@example.com> (2001-02-03 08:05:07)
(no description set)
Commit ID: 0000000000000000000000000000000000000000
Change ID: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author : (no name set) <(no email set)> (1970-01-01 11:00:00)
Committer: (no name set) <(no email set)> (1970-01-01 11:00:00)
(no description set)
[EOF]
");
}
#[test]
fn test_log_builtin_templates_colored() {
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(["--color=always", "log", "-T", template]);
work_dir
.run_jj(["--config=user.email=''", "--config=user.name=''", "new"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "my-bookmark"])
.success();
insta::assert_snapshot!(render(r#"builtin_log_oneline"#), @r"
[1m[38;5;2m@[0m [1m[38;5;13mr[38;5;8mlvkpnrz[39m [38;5;9m(no email set)[39m [38;5;14m2001-02-03 08:05:08[39m [38;5;13mmy-bookmark[39m [38;5;12ma[38;5;8mec3ec96[39m [38;5;10m(empty)[39m [38;5;10m(no description set)[39m[0m
○ [1m[38;5;5mq[0m[38;5;8mpvuntsm[39m [38;5;3mtest.user[39m [38;5;6m2001-02-03 08:05:07[39m [1m[38;5;4me[0m[38;5;8m8849ae1[39m [38;5;2m(empty)[39m [38;5;2m(no description set)[39m
[1m[38;5;14m◆[0m [1m[38;5;5mz[0m[38;5;8mzzzzzzz[39m [38;5;2mroot()[39m [1m[38;5;4m0[0m[38;5;8m0000000[39m
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_log_compact"#), @r"
[1m[38;5;2m@[0m [1m[38;5;13mr[38;5;8mlvkpnrz[39m [38;5;9m(no email set)[39m [38;5;14m2001-02-03 08:05:08[39m [38;5;13mmy-bookmark[39m [38;5;12ma[38;5;8mec3ec96[39m[0m
│ [1m[38;5;10m(empty)[39m [38;5;10m(no description set)[39m[0m
○ [1m[38;5;5mq[0m[38;5;8mpvuntsm[39m [38;5;3mtest.user@example.com[39m [38;5;6m2001-02-03 08:05:07[39m [1m[38;5;4me[0m[38;5;8m8849ae1[39m
│ [38;5;2m(empty)[39m [38;5;2m(no description set)[39m
[1m[38;5;14m◆[0m [1m[38;5;5mz[0m[38;5;8mzzzzzzz[39m [38;5;2mroot()[39m [1m[38;5;4m0[0m[38;5;8m0000000[39m
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_log_comfortable"#), @r"
[1m[38;5;2m@[0m [1m[38;5;13mr[38;5;8mlvkpnrz[39m [38;5;9m(no email set)[39m [38;5;14m2001-02-03 08:05:08[39m [38;5;13mmy-bookmark[39m [38;5;12ma[38;5;8mec3ec96[39m[0m
│ [1m[38;5;10m(empty)[39m [38;5;10m(no description set)[39m[0m
│
○ [1m[38;5;5mq[0m[38;5;8mpvuntsm[39m [38;5;3mtest.user@example.com[39m [38;5;6m2001-02-03 08:05:07[39m [1m[38;5;4me[0m[38;5;8m8849ae1[39m
│ [38;5;2m(empty)[39m [38;5;2m(no description set)[39m
│
[1m[38;5;14m◆[0m [1m[38;5;5mz[0m[38;5;8mzzzzzzz[39m [38;5;2mroot()[39m [1m[38;5;4m0[0m[38;5;8m0000000[39m
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_log_detailed"#), @r"
[1m[38;5;2m@[0m Commit ID: [38;5;4maec3ec964d0771edea9da48a2a170bc6ffa1c725[39m
│ Change ID: [38;5;5mrlvkpnrzqnoowoytxnquwvuryrwnrmlp[39m
│ Bookmarks: [38;5;5mmy-bookmark[39m
│ Author : [38;5;1m(no name set)[39m <[38;5;1m(no email set)[39m> ([38;5;6m2001-02-03 08:05:08[39m)
│ Committer: [38;5;1m(no name set)[39m <[38;5;1m(no email set)[39m> ([38;5;6m2001-02-03 08:05:08[39m)
│
│ [38;5;2m (no description set)[39m
│
○ Commit ID: [38;5;4me8849ae12c709f2321908879bc724fdb2ab8a781[39m
│ Change ID: [38;5;5mqpvuntsmwlqtpsluzzsnyyzlmlwvmlnu[39m
│ Author : [38;5;3mTest User[39m <[38;5;3mtest.user@example.com[39m> ([38;5;6m2001-02-03 08:05:07[39m)
│ Committer: [38;5;3mTest User[39m <[38;5;3mtest.user@example.com[39m> ([38;5;6m2001-02-03 08:05:07[39m)
│
│ [38;5;2m (no description set)[39m
│
[1m[38;5;14m◆[0m Commit ID: [38;5;4m0000000000000000000000000000000000000000[39m
Change ID: [38;5;5mzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz[39m
Author : [38;5;1m(no name set)[39m <[38;5;1m(no email set)[39m> ([38;5;6m1970-01-01 11:00:00[39m)
Committer: [38;5;1m(no name set)[39m <[38;5;1m(no email set)[39m> ([38;5;6m1970-01-01 11:00:00[39m)
[38;5;2m (no description set)[39m
[EOF]
");
}
#[test]
fn test_log_builtin_templates_colored_debug() {
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(["--color=debug", "log", "-T", template]);
work_dir
.run_jj(["--config=user.email=''", "--config=user.name=''", "new"])
.success();
work_dir
.run_jj(["bookmark", "create", "-r@", "my-bookmark"])
.success();
insta::assert_snapshot!(render(r#"builtin_log_oneline"#), @r"
[1m[38;5;2m<<log commit node working_copy mutable::@>>[0m [1m[38;5;13m<<log commit working_copy mutable change_id shortest prefix::r>>[38;5;8m<<log commit working_copy mutable change_id shortest rest::lvkpnrz>>[39m<<log commit working_copy mutable:: >>[38;5;9m<<log commit working_copy mutable email placeholder::(no email set)>>[39m<<log commit working_copy mutable:: >>[38;5;14m<<log commit working_copy mutable committer timestamp local format::2001-02-03 08:05:08>>[39m<<log commit working_copy mutable:: >>[38;5;13m<<log commit working_copy mutable bookmarks name::my-bookmark>>[39m<<log commit working_copy mutable:: >>[38;5;12m<<log commit working_copy mutable commit_id shortest prefix::a>>[38;5;8m<<log commit working_copy mutable commit_id shortest rest::ec3ec96>>[39m<<log commit working_copy mutable:: >>[38;5;10m<<log commit working_copy mutable empty::(empty)>>[39m<<log commit working_copy mutable:: >>[38;5;10m<<log commit working_copy mutable empty description placeholder::(no description set)>>[39m<<log commit working_copy mutable::>>[0m
<<log commit node mutable::○>> [1m[38;5;5m<<log commit mutable change_id shortest prefix::q>>[0m[38;5;8m<<log commit mutable change_id shortest rest::pvuntsm>>[39m<<log commit mutable:: >>[38;5;3m<<log commit mutable author email local::test.user>>[39m<<log commit mutable:: >>[38;5;6m<<log commit mutable committer timestamp local format::2001-02-03 08:05:07>>[39m<<log commit mutable:: >>[1m[38;5;4m<<log commit mutable commit_id shortest prefix::e>>[0m[38;5;8m<<log commit mutable commit_id shortest rest::8849ae1>>[39m<<log commit mutable:: >>[38;5;2m<<log commit mutable empty::(empty)>>[39m<<log commit mutable:: >>[38;5;2m<<log commit mutable empty description placeholder::(no description set)>>[39m<<log commit mutable::>>
[1m[38;5;14m<<log commit node immutable::◆>>[0m [1m[38;5;5m<<log commit immutable change_id shortest prefix::z>>[0m[38;5;8m<<log commit immutable change_id shortest rest::zzzzzzz>>[39m<<log commit immutable:: >>[38;5;2m<<log commit immutable root::root()>>[39m<<log commit immutable:: >>[1m[38;5;4m<<log commit immutable commit_id shortest prefix::0>>[0m[38;5;8m<<log commit immutable commit_id shortest rest::0000000>>[39m<<log commit immutable::>>
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_log_compact"#), @r"
[1m[38;5;2m<<log commit node working_copy mutable::@>>[0m [1m[38;5;13m<<log commit working_copy mutable change_id shortest prefix::r>>[38;5;8m<<log commit working_copy mutable change_id shortest rest::lvkpnrz>>[39m<<log commit working_copy mutable:: >>[38;5;9m<<log commit working_copy mutable email placeholder::(no email set)>>[39m<<log commit working_copy mutable:: >>[38;5;14m<<log commit working_copy mutable committer timestamp local format::2001-02-03 08:05:08>>[39m<<log commit working_copy mutable:: >>[38;5;13m<<log commit working_copy mutable bookmarks name::my-bookmark>>[39m<<log commit working_copy mutable:: >>[38;5;12m<<log commit working_copy mutable commit_id shortest prefix::a>>[38;5;8m<<log commit working_copy mutable commit_id shortest rest::ec3ec96>>[39m<<log commit working_copy mutable::>>[0m
│ [1m[38;5;10m<<log commit working_copy mutable empty::(empty)>>[39m<<log commit working_copy mutable:: >>[38;5;10m<<log commit working_copy mutable empty description placeholder::(no description set)>>[39m<<log commit working_copy mutable::>>[0m
<<log commit node mutable::○>> [1m[38;5;5m<<log commit mutable change_id shortest prefix::q>>[0m[38;5;8m<<log commit mutable change_id shortest rest::pvuntsm>>[39m<<log commit mutable:: >>[38;5;3m<<log commit mutable author email local::test.user>><<log commit mutable author email::@>><<log commit mutable author email domain::example.com>>[39m<<log commit mutable:: >>[38;5;6m<<log commit mutable committer timestamp local format::2001-02-03 08:05:07>>[39m<<log commit mutable:: >>[1m[38;5;4m<<log commit mutable commit_id shortest prefix::e>>[0m[38;5;8m<<log commit mutable commit_id shortest rest::8849ae1>>[39m<<log commit mutable::>>
│ [38;5;2m<<log commit mutable empty::(empty)>>[39m<<log commit mutable:: >>[38;5;2m<<log commit mutable empty description placeholder::(no description set)>>[39m<<log commit mutable::>>
[1m[38;5;14m<<log commit node immutable::◆>>[0m [1m[38;5;5m<<log commit immutable change_id shortest prefix::z>>[0m[38;5;8m<<log commit immutable change_id shortest rest::zzzzzzz>>[39m<<log commit immutable:: >>[38;5;2m<<log commit immutable root::root()>>[39m<<log commit immutable:: >>[1m[38;5;4m<<log commit immutable commit_id shortest prefix::0>>[0m[38;5;8m<<log commit immutable commit_id shortest rest::0000000>>[39m<<log commit immutable::>>
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_log_comfortable"#), @r"
[1m[38;5;2m<<log commit node working_copy mutable::@>>[0m [1m[38;5;13m<<log commit working_copy mutable change_id shortest prefix::r>>[38;5;8m<<log commit working_copy mutable change_id shortest rest::lvkpnrz>>[39m<<log commit working_copy mutable:: >>[38;5;9m<<log commit working_copy mutable email placeholder::(no email set)>>[39m<<log commit working_copy mutable:: >>[38;5;14m<<log commit working_copy mutable committer timestamp local format::2001-02-03 08:05:08>>[39m<<log commit working_copy mutable:: >>[38;5;13m<<log commit working_copy mutable bookmarks name::my-bookmark>>[39m<<log commit working_copy mutable:: >>[38;5;12m<<log commit working_copy mutable commit_id shortest prefix::a>>[38;5;8m<<log commit working_copy mutable commit_id shortest rest::ec3ec96>>[39m<<log commit working_copy mutable::>>[0m
│ [1m[38;5;10m<<log commit working_copy mutable empty::(empty)>>[39m<<log commit working_copy mutable:: >>[38;5;10m<<log commit working_copy mutable empty description placeholder::(no description set)>>[39m<<log commit working_copy mutable::>>[0m
│ <<log commit::>>
<<log commit node mutable::○>> [1m[38;5;5m<<log commit mutable change_id shortest prefix::q>>[0m[38;5;8m<<log commit mutable change_id shortest rest::pvuntsm>>[39m<<log commit mutable:: >>[38;5;3m<<log commit mutable author email local::test.user>><<log commit mutable author email::@>><<log commit mutable author email domain::example.com>>[39m<<log commit mutable:: >>[38;5;6m<<log commit mutable committer timestamp local format::2001-02-03 08:05:07>>[39m<<log commit mutable:: >>[1m[38;5;4m<<log commit mutable commit_id shortest prefix::e>>[0m[38;5;8m<<log commit mutable commit_id shortest rest::8849ae1>>[39m<<log commit mutable::>>
│ [38;5;2m<<log commit mutable empty::(empty)>>[39m<<log commit mutable:: >>[38;5;2m<<log commit mutable empty description placeholder::(no description set)>>[39m<<log commit mutable::>>
│ <<log commit::>>
[1m[38;5;14m<<log commit node immutable::◆>>[0m [1m[38;5;5m<<log commit immutable change_id shortest prefix::z>>[0m[38;5;8m<<log commit immutable change_id shortest rest::zzzzzzz>>[39m<<log commit immutable:: >>[38;5;2m<<log commit immutable root::root()>>[39m<<log commit immutable:: >>[1m[38;5;4m<<log commit immutable commit_id shortest prefix::0>>[0m[38;5;8m<<log commit immutable commit_id shortest rest::0000000>>[39m<<log commit immutable::>>
<<log commit::>>
[EOF]
");
insta::assert_snapshot!(render(r#"builtin_log_detailed"#), @r"
[1m[38;5;2m<<log commit node working_copy mutable::@>>[0m <<log commit::Commit ID: >>[38;5;4m<<log commit commit_id::aec3ec964d0771edea9da48a2a170bc6ffa1c725>>[39m<<log commit::>>
│ <<log commit::Change ID: >>[38;5;5m<<log commit change_id::rlvkpnrzqnoowoytxnquwvuryrwnrmlp>>[39m<<log commit::>>
│ <<log commit::Bookmarks: >>[38;5;5m<<log commit local_bookmarks name::my-bookmark>>[39m<<log commit::>>
│ <<log commit::Author : >>[38;5;1m<<log commit name placeholder::(no name set)>>[39m<<log commit:: <>>[38;5;1m<<log commit email placeholder::(no email set)>>[39m<<log commit::> (>>[38;5;6m<<log commit author timestamp local format::2001-02-03 08:05:08>>[39m<<log commit::)>>
│ <<log commit::Committer: >>[38;5;1m<<log commit name placeholder::(no name set)>>[39m<<log commit:: <>>[38;5;1m<<log commit email placeholder::(no email set)>>[39m<<log commit::> (>>[38;5;6m<<log commit committer timestamp local format::2001-02-03 08:05:08>>[39m<<log commit::)>>
│ <<log commit::>>
│ [38;5;2m<<log commit empty description placeholder:: (no description set)>>[39m<<log commit::>>
│ <<log commit::>>
<<log commit node mutable::○>> <<log commit::Commit ID: >>[38;5;4m<<log commit commit_id::e8849ae12c709f2321908879bc724fdb2ab8a781>>[39m<<log commit::>>
│ <<log commit::Change ID: >>[38;5;5m<<log commit change_id::qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu>>[39m<<log commit::>>
│ <<log commit::Author : >>[38;5;3m<<log commit author name::Test User>>[39m<<log commit:: <>>[38;5;3m<<log commit author email local::test.user>><<log commit author email::@>><<log commit author email domain::example.com>>[39m<<log commit::> (>>[38;5;6m<<log commit author timestamp local format::2001-02-03 08:05:07>>[39m<<log commit::)>>
│ <<log commit::Committer: >>[38;5;3m<<log commit committer name::Test User>>[39m<<log commit:: <>>[38;5;3m<<log commit committer email local::test.user>><<log commit committer email::@>><<log commit committer email domain::example.com>>[39m<<log commit::> (>>[38;5;6m<<log commit committer timestamp local format::2001-02-03 08:05:07>>[39m<<log commit::)>>
│ <<log commit::>>
│ [38;5;2m<<log commit empty description placeholder:: (no description set)>>[39m<<log commit::>>
│ <<log commit::>>
[1m[38;5;14m<<log commit node immutable::◆>>[0m <<log commit::Commit ID: >>[38;5;4m<<log commit commit_id::0000000000000000000000000000000000000000>>[39m<<log commit::>>
<<log commit::Change ID: >>[38;5;5m<<log commit change_id::zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz>>[39m<<log commit::>>
<<log commit::Author : >>[38;5;1m<<log commit name placeholder::(no name set)>>[39m<<log commit:: <>>[38;5;1m<<log commit email placeholder::(no email set)>>[39m<<log commit::> (>>[38;5;6m<<log commit author timestamp local format::1970-01-01 11:00:00>>[39m<<log commit::)>>
<<log commit::Committer: >>[38;5;1m<<log commit name placeholder::(no name set)>>[39m<<log commit:: <>>[38;5;1m<<log commit email placeholder::(no email set)>>[39m<<log commit::> (>>[38;5;6m<<log commit committer timestamp local format::1970-01-01 11:00:00>>[39m<<log commit::)>>
<<log commit::>>
[38;5;2m<<log commit empty description placeholder:: (no description set)>>[39m<<log commit::>>
<<log commit::>>
[EOF]
");
}
#[test]
fn test_log_evolog_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.write_file("file", "foo\n");
work_dir
.run_jj(["describe", "-m", "description 1"])
.success();
// No divergence
let output = work_dir.run_jj(["log"]);
insta::assert_snapshot!(output, @r"
@ qpvuntsm test.user@example.com 2001-02-03 08:05:08 556daeb7
│ description 1
◆ zzzzzzzz root() 00000000
[EOF]
");
// Create divergence
work_dir
.run_jj(["describe", "-m", "description 2", "--at-operation", "@-"])
.success();
let output = work_dir.run_jj(["log"]);
insta::assert_snapshot!(output, @r"
@ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:08 556daeb7 (divergent)
│ description 1
│ ○ qpvuntsm/0 test.user@example.com 2001-02-03 08:05:10 5cea51a1 (divergent)
├─╯ description 2
◆ zzzzzzzz root() 00000000
[EOF]
------- stderr -------
Concurrent modification detected, resolving automatically.
[EOF]
");
// Color
let output = work_dir.run_jj(["log", "--color=always"]);
insta::assert_snapshot!(output, @r"
[1m[38;5;2m@[0m [1m[38;5;9mq[38;5;8mpvuntsm[38;5;9m/1[39m [38;5;3mtest.user@example.com[39m [38;5;14m2001-02-03 08:05:08[39m [38;5;12m55[38;5;8m6daeb7[39m [38;5;9m(divergent)[39m[0m
│ [1mdescription 1[0m
│ ○ [1m[38;5;1mq[0m[38;5;8mpvuntsm[1m[38;5;1m/0[0m [38;5;3mtest.user@example.com[39m [38;5;6m2001-02-03 08:05:10[39m [1m[38;5;4m5c[0m[38;5;8mea51a1[39m [38;5;1m(divergent)[39m
├─╯ description 2
[1m[38;5;14m◆[0m [1m[38;5;5mz[0m[38;5;8mzzzzzzz[39m [38;5;2mroot()[39m [1m[38;5;4m0[0m[38;5;8m0000000[39m
[EOF]
");
// Evolog and hidden divergent
let output = work_dir.run_jj(["evolog"]);
insta::assert_snapshot!(output, @r"
@ qpvuntsm/1 test.user@example.com 2001-02-03 08:05:08 556daeb7 (divergent)
│ description 1
│ -- operation fec5a045b947 describe commit d0c049cd993a8d3a2e69ba6df98788e264ea9fa1
○ qpvuntsm/2 test.user@example.com 2001-02-03 08:05:08 d0c049cd (hidden)
│ (no description set)
│ -- operation 911e64a1b666 snapshot working copy
○ qpvuntsm/3 test.user@example.com 2001-02-03 08:05:07 e8849ae1 (hidden)
(empty) (no description set)
-- operation 8f47435a3990 add workspace 'default'
[EOF]
");
// Colored evolog
let output = work_dir.run_jj(["evolog", "--color=always"]);
insta::assert_snapshot!(output, @r"
| 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_op_revert_command.rs | cli/tests/test_op_revert_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 testutils::git;
use crate::common::CommandOutput;
use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
#[test]
fn test_revert_root_operation() {
let test_env = TestEnvironment::default();
test_env.run_jj_in(".", ["git", "init", "repo"]).success();
let work_dir = test_env.work_dir("repo");
// TODO: `jj op revert 'root()'` is not a valid command, so use the
// hardcoded root op id here.
let output = work_dir.run_jj(["op", "revert", "000000000000"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Error: Cannot revert root operation
[EOF]
[exit status: 1]
");
}
#[test]
fn test_revert_merge_operation() {
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", "--at-op=@-"]).success();
let output = work_dir.run_jj(["op", "revert"]);
insta::assert_snapshot!(output, @r"
------- stderr -------
Concurrent modification detected, resolving automatically.
Error: Cannot revert a merge operation
[EOF]
[exit status: 1]
");
}
#[test]
fn test_revert_rewrite_with_child() {
// Test that if we revert an operation that rewrote some commit, any descendants
// after that will be rebased on top of the un-rewritten commit.
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", "initial"]).success();
work_dir.run_jj(["describe", "-m", "modified"]).success();
work_dir.run_jj(["new", "-m", "child"]).success();
let output = work_dir.run_jj(["log", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ child
○ modified
◆
[EOF]
");
work_dir.run_jj(["op", "revert", "@-"]).success();
// Since we undid the description-change, the child commit should now be on top
// of the initial commit
let output = work_dir.run_jj(["log", "-T", "description"]);
insta::assert_snapshot!(output, @r"
@ child
○ initial
◆
[EOF]
");
}
#[test]
fn test_git_push_revert() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
let git_repo_path = test_env.env_root().join("git-repo");
git::init_bare(git_repo_path);
test_env
.run_jj_in(".", ["git", "clone", "git-repo", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
work_dir.run_jj(["describe", "-m", "AA"]).success();
work_dir.run_jj(["git", "push", "--allow-new"]).success();
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir.run_jj(["describe", "-m", "BB"]).success();
// Refs at this point look as follows (-- means no ref)
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | -- | --
// remote-tracking | AA | AA | AA
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 3a44d6c5 (hidden) (empty) AA
[EOF]
");
let pre_push_opid = work_dir.current_operation_id();
work_dir.run_jj(["git", "push"]).success();
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | -- | --
// remote-tracking | BB | BB | BB
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@origin: qpvuntsm d9a9f6a0 (empty) BB
[EOF]
");
// Revert the push
work_dir.run_jj(["op", "restore", &pre_push_opid]).success();
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | -- | --
// remote-tracking | AA | AA | BB
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 3a44d6c5 (hidden) (empty) AA
[EOF]
");
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir.run_jj(["describe", "-m", "CC"]).success();
work_dir.run_jj(["git", "fetch"]).success();
// TODO: The user would probably not expect a conflict here. It currently is
// because the revert made us forget that the remote was at v2, so the fetch
// made us think it updated from v1 to v2 (instead of the no-op it could
// have been).
//
// One option to solve this would be to have `op revert` not restore
// remote-tracking bookmarks, but that also has undersired consequences: the
// second fetch in `jj git fetch && jj op revert && jj git fetch` would
// become a no-op.
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main (conflicted):
- qpvuntsm/2 3a44d6c5 (hidden) (empty) AA
+ qpvuntsm/0 1e742089 (divergent) (empty) CC
+ qpvuntsm/1 d9a9f6a0 (divergent) (empty) BB
@origin (behind by 1 commits): qpvuntsm/1 d9a9f6a0 (divergent) (empty) BB
[EOF]
");
}
/// This test is identical to the previous one, except for one additional
/// import. It demonstrates that this changes the outcome.
#[test]
fn test_git_push_revert_with_import() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
let git_repo_path = test_env.env_root().join("git-repo");
git::init_bare(git_repo_path);
test_env
.run_jj_in(".", ["git", "clone", "git-repo", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
work_dir.run_jj(["describe", "-m", "AA"]).success();
work_dir.run_jj(["git", "push", "--allow-new"]).success();
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir.run_jj(["describe", "-m", "BB"]).success();
// Refs at this point look as follows (-- means no ref)
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | -- | --
// remote-tracking | AA | AA | AA
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 3a44d6c5 (hidden) (empty) AA
[EOF]
");
let pre_push_opid = work_dir.current_operation_id();
work_dir.run_jj(["git", "push"]).success();
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | -- | --
// remote-tracking | BB | BB | BB
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@origin: qpvuntsm d9a9f6a0 (empty) BB
[EOF]
");
// Revert the push
work_dir.run_jj(["op", "restore", &pre_push_opid]).success();
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | -- | --
// remote-tracking | AA | AA | BB
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 3a44d6c5 (hidden) (empty) AA
[EOF]
");
// PROBLEM: inserting this import changes the outcome compared to previous test
// TODO: decide if this is the better behavior, and whether import of
// remote-tracking bookmarks should happen on every operation.
work_dir.run_jj(["git", "import"]).success();
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | -- | --
// remote-tracking | BB | BB | BB
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@origin: qpvuntsm d9a9f6a0 (empty) BB
[EOF]
");
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir.run_jj(["describe", "-m", "CC"]).success();
work_dir.run_jj(["git", "fetch"]).success();
// There is not a conflict. This seems like a good outcome; reverting `git push`
// was essentially a no-op.
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm 1e742089 (empty) CC
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 d9a9f6a0 (hidden) (empty) BB
[EOF]
");
}
// This test is currently *identical* to `test_git_push_revert` except the repo
// it's operating on is colocated.
#[test]
fn test_git_push_revert_colocated() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
let git_repo_path = test_env.env_root().join("git-repo");
git::init_bare(git_repo_path.clone());
let work_dir = test_env.work_dir("clone");
git::clone(work_dir.root(), git_repo_path.to_str().unwrap(), None);
work_dir.run_jj(["git", "init", "--git-repo=."]).success();
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
work_dir.run_jj(["describe", "-m", "AA"]).success();
work_dir.run_jj(["git", "push", "--allow-new"]).success();
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir.run_jj(["describe", "-m", "BB"]).success();
// Refs at this point look as follows (-- means no ref)
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | BB | BB
// remote-tracking | AA | AA | AA
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@git: qpvuntsm d9a9f6a0 (empty) BB
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 3a44d6c5 (hidden) (empty) AA
[EOF]
");
let pre_push_opid = work_dir.current_operation_id();
work_dir.run_jj(["git", "push"]).success();
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | BB | BB
// remote-tracking | BB | BB | BB
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@git: qpvuntsm d9a9f6a0 (empty) BB
@origin: qpvuntsm d9a9f6a0 (empty) BB
[EOF]
");
// Revert the push
work_dir.run_jj(["op", "restore", &pre_push_opid]).success();
// === Before auto-export ====
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | BB | BB
// remote-tracking | AA | BB | BB
// === After automatic `jj git export` ====
// | jj refs | jj's | git
// | | git | repo
// | |tracking|
// ------------------------------------------
// local `main` | BB | BB | BB
// remote-tracking | AA | AA | AA
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@git: qpvuntsm d9a9f6a0 (empty) BB
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 3a44d6c5 (hidden) (empty) AA
[EOF]
");
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir.run_jj(["describe", "-m", "CC"]).success();
work_dir.run_jj(["git", "fetch"]).success();
// We have the same conflict as `test_git_push_revert`. TODO: why did we get the
// same result in a seemingly different way?
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main (conflicted):
- qpvuntsm/2 3a44d6c5 (hidden) (empty) AA
+ qpvuntsm/0 1e742089 (divergent) (empty) CC
+ qpvuntsm/1 d9a9f6a0 (divergent) (empty) BB
@git (behind by 1 commits): qpvuntsm/0 1e742089 (divergent) (empty) CC
@origin (behind by 1 commits): qpvuntsm/1 d9a9f6a0 (divergent) (empty) BB
[EOF]
");
}
// This test is currently *identical* to `test_git_push_revert` except
// both the git_refs and the remote-tracking bookmarks are preserved by revert.
// TODO: Investigate the different outcome
#[test]
fn test_git_push_revert_repo_only() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
let git_repo_path = test_env.env_root().join("git-repo");
git::init_bare(git_repo_path);
test_env
.run_jj_in(".", ["git", "clone", "git-repo", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir
.run_jj(["bookmark", "create", "-r@", "main"])
.success();
work_dir.run_jj(["describe", "-m", "AA"]).success();
work_dir.run_jj(["git", "push", "--allow-new"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm 3a44d6c5 (empty) AA
@origin: qpvuntsm 3a44d6c5 (empty) AA
[EOF]
");
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir.run_jj(["describe", "-m", "BB"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 3a44d6c5 (hidden) (empty) AA
[EOF]
");
let pre_push_opid = work_dir.current_operation_id();
work_dir.run_jj(["git", "push"]).success();
// Revert the push, but keep both the git_refs and the remote-tracking bookmarks
work_dir
.run_jj(["op", "restore", "--what=repo", &pre_push_opid])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm d9a9f6a0 (empty) BB
@origin: qpvuntsm d9a9f6a0 (empty) BB
[EOF]
");
test_env.advance_test_rng_seed_to_multiple_of(100_000);
work_dir.run_jj(["describe", "-m", "CC"]).success();
work_dir.run_jj(["git", "fetch"]).success();
// This currently gives an identical result to `test_git_push_revert_import`.
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
main: qpvuntsm 1e742089 (empty) CC
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/1 d9a9f6a0 (hidden) (empty) BB
[EOF]
");
// Revert the remote-tracking, without modifying the repo
work_dir
.run_jj(["op", "restore", "--what=remote-tracking", &pre_push_opid])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @"
main: qpvuntsm 1e742089 (empty) CC
@origin (ahead by 1 commits, behind by 1 commits): qpvuntsm/2 3a44d6c5 (hidden) (empty) AA
[EOF]
");
}
#[test]
fn test_bookmark_track_untrack_revert() {
let test_env = TestEnvironment::default();
test_env.add_config(r#"revset-aliases."immutable_heads()" = "none()""#);
let git_repo_path = test_env.env_root().join("git-repo");
git::init_bare(git_repo_path);
test_env
.run_jj_in(".", ["git", "clone", "git-repo", "repo"])
.success();
let work_dir = test_env.work_dir("repo");
work_dir.run_jj(["describe", "-mcommit"]).success();
work_dir
.run_jj(["bookmark", "create", "-r@", "feature1", "feature2"])
.success();
work_dir.run_jj(["git", "push", "--allow-new"]).success();
work_dir
.run_jj(["bookmark", "delete", "feature2"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
feature1: qpvuntsm bab5b5ef (empty) commit
@origin: qpvuntsm bab5b5ef (empty) commit
feature2 (deleted)
@origin: qpvuntsm bab5b5ef (empty) commit
[EOF]
");
// Track/untrack can be reverted so long as states can be trivially merged.
work_dir
.run_jj(["bookmark", "untrack", "feature1 | feature2"])
.success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
feature1: qpvuntsm bab5b5ef (empty) commit
feature1@origin: qpvuntsm bab5b5ef (empty) commit
feature2@origin: qpvuntsm bab5b5ef (empty) commit
[EOF]
");
work_dir.run_jj(["op", "revert"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
feature1: qpvuntsm bab5b5ef (empty) commit
@origin: qpvuntsm bab5b5ef (empty) commit
feature2 (deleted)
@origin: qpvuntsm bab5b5ef (empty) commit
[EOF]
");
work_dir.run_jj(["op", "revert"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
feature1: qpvuntsm bab5b5ef (empty) commit
feature1@origin: qpvuntsm bab5b5ef (empty) commit
feature2@origin: qpvuntsm bab5b5ef (empty) commit
[EOF]
");
work_dir.run_jj(["bookmark", "track", "feature1"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
feature1: qpvuntsm bab5b5ef (empty) commit
@origin: qpvuntsm bab5b5ef (empty) commit
feature2@origin: qpvuntsm bab5b5ef (empty) commit
[EOF]
");
work_dir.run_jj(["op", "revert"]).success();
insta::assert_snapshot!(get_bookmark_output(&work_dir), @r"
feature1: qpvuntsm bab5b5ef (empty) commit
feature1@origin: qpvuntsm bab5b5ef (empty) commit
feature2@origin: qpvuntsm bab5b5ef (empty) commit
[EOF]
");
}
#[must_use]
fn get_bookmark_output(work_dir: &TestWorkDir) -> CommandOutput {
// --quiet to suppress deleted bookmarks hint
work_dir.run_jj(["bookmark", "list", "--all-remotes", "--quiet"])
}
| 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_builtin_aliases.rs | cli/tests/test_builtin_aliases.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::TestEnvironment;
fn set_up(trunk_name: &str) -> TestEnvironment {
let test_env = TestEnvironment::default();
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");
origin_dir
.run_jj(["describe", "-m=description 1"])
.success();
origin_dir
.run_jj(["bookmark", "create", "-r@", trunk_name])
.success();
origin_dir
.run_jj(["new", "root()", "-m=description 2"])
.success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "unrelated_bookmark"])
.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_env
}
#[test]
fn test_builtin_alias_trunk_matches_main() {
let test_env = set_up("main");
let work_dir = test_env.work_dir("local");
let output = work_dir.run_jj(["log", "-r", "trunk()"]);
insta::assert_snapshot!(output, @r"
◆ qpvuntsm test.user@example.com 2001-02-03 08:05:08 main 9b2e76de
│ (empty) description 1
~
[EOF]
");
}
#[test]
fn test_builtin_alias_trunk_matches_master() {
let test_env = set_up("master");
let work_dir = test_env.work_dir("local");
let output = work_dir.run_jj(["log", "-r", "trunk()"]);
insta::assert_snapshot!(output, @r"
◆ qpvuntsm test.user@example.com 2001-02-03 08:05:08 master 9b2e76de
│ (empty) description 1
~
[EOF]
");
}
#[test]
fn test_builtin_alias_trunk_matches_trunk() {
let test_env = set_up("trunk");
let work_dir = test_env.work_dir("local");
let output = work_dir.run_jj(["log", "-r", "trunk()"]);
insta::assert_snapshot!(output, @r"
◆ qpvuntsm test.user@example.com 2001-02-03 08:05:08 trunk 9b2e76de
│ (empty) description 1
~
[EOF]
");
}
#[test]
fn test_builtin_alias_trunk_matches_exactly_one_commit() {
let test_env = set_up("main");
let work_dir = test_env.work_dir("local");
let origin_dir = test_env.work_dir("origin");
origin_dir
.run_jj(["new", "root()", "-m=description 3"])
.success();
origin_dir
.run_jj(["bookmark", "create", "-r@", "master"])
.success();
let output = work_dir.run_jj(["log", "-r", "trunk()"]);
insta::assert_snapshot!(output, @r"
◆ qpvuntsm test.user@example.com 2001-02-03 08:05:08 main 9b2e76de
│ (empty) description 1
~
[EOF]
");
}
#[test]
fn test_builtin_alias_trunk_override_alias() {
let test_env = set_up("override-trunk");
let work_dir = test_env.work_dir("local");
test_env.add_config(
r#"revset-aliases.'trunk()' = 'latest(remote_bookmarks("override-trunk", "origin"))'"#,
);
let output = work_dir.run_jj(["log", "-r", "trunk()"]);
insta::assert_snapshot!(output, @r"
◆ qpvuntsm test.user@example.com 2001-02-03 08:05:08 override-trunk 9b2e76de
│ (empty) description 1
~
[EOF]
");
}
#[test]
fn test_builtin_alias_trunk_no_match() {
let test_env = set_up("no-match-trunk");
let work_dir = test_env.work_dir("local");
let output = work_dir.run_jj(["log", "-r", "trunk()"]);
insta::assert_snapshot!(output, @r"
◆ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_builtin_alias_trunk_no_match_only_exact() {
let test_env = set_up("maint");
let work_dir = test_env.work_dir("local");
let output = work_dir.run_jj(["log", "-r", "trunk()"]);
insta::assert_snapshot!(output, @r"
◆ zzzzzzzz root() 00000000
[EOF]
");
}
#[test]
fn test_builtin_user_redefines_builtin_immutable_heads() {
let test_env = set_up("main");
let work_dir = test_env.work_dir("local");
test_env.add_config(r#"revset-aliases.'builtin_immutable_heads()' = '@'"#);
test_env.add_config(r#"revset-aliases.'mutable()' = '@'"#);
test_env.add_config(r#"revset-aliases.'immutable()' = '@'"#);
let output = work_dir.run_jj(["log", "-r", "trunk()"]);
insta::assert_snapshot!(output, @r"
○ qpvuntsm test.user@example.com 2001-02-03 08:05:08 main 9b2e76de
│ (empty) description 1
~
[EOF]
------- stderr -------
Warning: Redefining `revset-aliases.builtin_immutable_heads()` is not recommended; redefine `immutable_heads()` instead
Warning: Redefining `revset-aliases.mutable()` is not recommended; redefine `immutable_heads()` instead
Warning: Redefining `revset-aliases.immutable()` is not recommended; redefine `immutable_heads()` instead
[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/common/config_schema_defaults.rs | cli/tests/common/config_schema_defaults.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.
/// Produce a synthetic JSON document containing a default config according to
/// the schema.
///
/// # Limitations
/// Defaults in `"additionalProperties"` are ignored, as are those in
/// `"definitions"` nodes (which might be referenced by `"$ref"`).
pub fn default_config_from_schema() -> serde_json::Value {
fn visit(schema: &serde_json::Value) -> Option<serde_json::Value> {
let schema = schema.as_object().expect("schemas to be objects");
if let Some(default) = schema.get("default") {
Some(default.clone())
} else if let Some(properties) = schema.get("properties") {
let prop_defaults: serde_json::Map<_, _> = properties
.as_object()
.expect("`properties` to be an object")
.iter()
.filter_map(|(prop_name, prop_schema)| {
visit(prop_schema).map(|prop_default| (prop_name.clone(), prop_default))
})
.collect();
(!prop_defaults.is_empty()).then_some(serde_json::Value::Object(prop_defaults))
} else {
None
}
}
visit(
&serde_json::from_str(include_str!("../../src/config-schema.json"))
.expect("`config-schema.json` to be valid JSON"),
)
.expect("some settings to have defaults")
}
| 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/common/command_output.rs | cli/tests/common/command_output.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;
use std::fmt::Debug;
use std::fmt::Display;
use std::process::ExitStatus;
/// Command output and exit status to be displayed in normalized form.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommandOutput {
pub stdout: CommandOutputString,
pub stderr: CommandOutputString,
pub status: ExitStatus,
}
impl CommandOutput {
/// Normalizes Windows directory separator to slash.
#[must_use]
pub fn normalize_backslash(self) -> Self {
Self {
stdout: self.stdout.normalize_backslash(),
stderr: self.stderr.normalize_backslash(),
status: self.status,
}
}
/// Normalizes [`ExitStatus`] message in stderr text.
#[must_use]
pub fn normalize_stderr_exit_status(self) -> Self {
Self {
stdout: self.stdout,
stderr: self.stderr.normalize_exit_status(),
status: self.status,
}
}
/// Removes the last line (such as platform-specific error message) from the
/// normalized stderr text.
#[must_use]
pub fn strip_stderr_last_line(self) -> Self {
Self {
stdout: self.stdout,
stderr: self.stderr.strip_last_line(),
status: self.status,
}
}
/// Removes all but the first `n` lines from normalized stdout text.
#[must_use]
pub fn take_stdout_n_lines(self, n: usize) -> Self {
Self {
stdout: self.stdout.take_n_lines(n),
stderr: self.stderr,
status: self.status,
}
}
#[must_use]
pub fn normalize_stdout_with(self, f: impl FnOnce(String) -> String) -> Self {
Self {
stdout: self.stdout.normalize_with(f),
stderr: self.stderr,
status: self.status,
}
}
#[must_use]
pub fn normalize_stderr_with(self, f: impl FnOnce(String) -> String) -> Self {
Self {
stdout: self.stdout,
stderr: self.stderr.normalize_with(f),
status: self.status,
}
}
/// Ensures that the command exits with success status.
#[track_caller]
pub fn success(self) -> Self {
assert!(self.status.success(), "{self}");
self
}
}
impl Display for CommandOutput {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
stdout,
stderr,
status,
} = self;
write!(f, "{stdout}")?;
if !stderr.is_empty() {
writeln!(f, "------- stderr -------")?;
write!(f, "{stderr}")?;
}
if !status.success() {
// If there is an exit code, `{status}` would get rendered as "exit
// code: N" on Windows, so we render it ourselves for compatibility.
if let Some(code) = status.code() {
writeln!(f, "[exit status: {code}]")?;
} else {
writeln!(f, "[{status}]")?;
}
}
Ok(())
}
}
/// Command output data to be displayed in normalized form.
#[derive(Clone)]
pub struct CommandOutputString {
// TODO: use BString?
pub(super) raw: String,
pub(super) normalized: String,
}
impl CommandOutputString {
/// Normalizes Windows directory separator to slash.
#[must_use]
pub fn normalize_backslash(self) -> Self {
self.normalize_with(|s| s.replace('\\', "/"))
}
/// Normalizes [`ExitStatus`] message.
///
/// On Windows, it prints "exit code" instead of "exit status".
#[must_use]
pub fn normalize_exit_status(self) -> Self {
self.normalize_with(|s| s.replace("exit code:", "exit status:"))
}
/// Removes the last line (such as platform-specific error message) from the
/// normalized text.
#[must_use]
pub fn strip_last_line(self) -> Self {
self.normalize_with(|mut s| {
s.truncate(strip_last_line(&s).len());
s
})
}
/// Removes all but the first `n` lines from the normalized text.
#[must_use]
pub fn take_n_lines(self, n: usize) -> Self {
self.normalize_with(|s| s.split_inclusive("\n").take(n).collect())
}
#[must_use]
pub fn normalize_with(mut self, f: impl FnOnce(String) -> String) -> Self {
self.normalized = f(self.normalized);
self
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.raw.is_empty()
}
/// Raw output data.
#[must_use]
pub fn raw(&self) -> &str {
&self.raw
}
/// Normalized text for snapshot testing.
#[must_use]
pub fn normalized(&self) -> &str {
&self.normalized
}
/// Extracts raw output data.
#[must_use]
pub fn into_raw(self) -> String {
self.raw
}
}
impl Debug for CommandOutputString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Print only raw data. Normalized string should be nearly identical.
Debug::fmt(&self.raw, f)
}
}
impl Display for CommandOutputString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_empty() {
return Ok(());
}
// Append "[EOF]" marker to test line ending
// https://github.com/mitsuhiko/insta/issues/384
writeln!(f, "{}[EOF]", self.normalized)
}
}
impl Eq for CommandOutputString {}
impl PartialEq for CommandOutputString {
fn eq(&self, other: &Self) -> bool {
// Compare only raw data. Normalized string is for displaying purpose.
self.raw == other.raw
}
}
/// Returns a string with the last line removed.
///
/// Use this to remove the root error message containing platform-specific
/// content for example.
pub fn strip_last_line(s: &str) -> &str {
s.trim_end_matches('\n')
.rsplit_once('\n')
.map_or(s, |(h, _)| &s[..h.len() + 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/common/mod.rs | cli/tests/common/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 command_output;
mod config_schema_defaults;
mod test_environment;
pub use self::command_output::CommandOutput;
pub use self::config_schema_defaults::default_config_from_schema;
pub use self::test_environment::TestEnvironment;
pub use self::test_environment::TestWorkDir;
pub fn fake_bisector_path() -> String {
let path = assert_cmd::cargo::cargo_bin!("fake-bisector");
assert!(path.is_file());
path.as_os_str().to_str().unwrap().to_owned()
}
pub fn fake_editor_path() -> String {
let path = assert_cmd::cargo::cargo_bin!("fake-editor");
assert!(path.is_file());
path.as_os_str().to_str().unwrap().to_owned()
}
pub fn fake_diff_editor_path() -> String {
let path = assert_cmd::cargo::cargo_bin!("fake-diff-editor");
assert!(path.is_file());
path.as_os_str().to_str().unwrap().to_owned()
}
/// Forcibly enable interactive prompt.
pub fn force_interactive(cmd: &mut assert_cmd::Command) -> &mut assert_cmd::Command {
cmd.env("JJ_INTERACTIVE", "1")
}
/// Coerces the value type to serialize it as TOML.
pub fn to_toml_value(value: impl Into<toml_edit::Value>) -> toml_edit::Value {
value.into()
}
pub fn create_commit(work_dir: &TestWorkDir, name: &str, parents: &[&str]) {
create_commit_with_files(work_dir, name, parents, &[(name, &format!("{name}\n"))]);
}
pub fn create_commit_with_files(
work_dir: &TestWorkDir,
name: &str,
parents: &[&str],
files: &[(&str, &str)],
) {
let parents = match parents {
[] => &["root()"],
parents => parents,
};
work_dir
.run_jj_with(|cmd| cmd.args(["new", "-m", name]).args(parents))
.success();
for (name, content) in files {
work_dir.write_file(name, content);
}
work_dir
.run_jj(["bookmark", "create", "-r@", name])
.success();
}
| 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/common/test_environment.rs | cli/tests/common/test_environment.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::cell::RefCell;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::path::Path;
use std::path::PathBuf;
use bstr::BString;
use indoc::formatdoc;
use itertools::Itertools as _;
use regex::Captures;
use regex::Regex;
use tempfile::TempDir;
use super::command_output::CommandOutput;
use super::command_output::CommandOutputString;
use super::fake_bisector_path;
use super::fake_diff_editor_path;
use super::fake_editor_path;
use super::to_toml_value;
pub struct TestEnvironment {
_env_dir: TempDir,
env_root: PathBuf,
home_dir: PathBuf,
tmp_dir: PathBuf,
config_path: PathBuf,
env_vars: HashMap<OsString, OsString>,
paths_to_normalize: Vec<(PathBuf, String)>,
config_file_number: RefCell<i64>,
command_number: RefCell<i64>,
}
impl Default for TestEnvironment {
fn default() -> Self {
testutils::hermetic_git();
let env_dir = testutils::new_temp_dir();
let env_root = dunce::canonicalize(env_dir.path()).unwrap();
let home_dir = env_root.join("home");
std::fs::create_dir(&home_dir).unwrap();
let tmp_dir = env_root.join("tmp");
std::fs::create_dir(&tmp_dir).unwrap();
let config_dir = env_root.join("config");
std::fs::create_dir(&config_dir).unwrap();
let env_vars = HashMap::new();
let paths_to_normalize = [(env_root.clone(), "$TEST_ENV".to_string())]
.into_iter()
.collect();
let env = Self {
_env_dir: env_dir,
env_root,
home_dir,
tmp_dir,
config_path: config_dir,
env_vars,
paths_to_normalize,
config_file_number: RefCell::new(0),
command_number: RefCell::new(0),
};
// Use absolute timestamps in the operation log to make tests independent of the
// current time. Use non-colocated workspaces by default for simplicity.
env.add_config(
r#"
[template-aliases]
'format_time_range(time_range)' = 'time_range.start() ++ " - " ++ time_range.end()'
[git]
colocate = false
"#,
);
env
}
}
impl TestEnvironment {
/// Returns test helper for the specified directory.
///
/// The `root` path usually points to the workspace root, but it may be
/// arbitrary path including non-existent directory.
#[must_use]
pub fn work_dir(&self, root: impl AsRef<Path>) -> TestWorkDir<'_> {
let root = self.env_root.join(root);
TestWorkDir { env: self, root }
}
/// Runs `jj args..` in the `current_dir`, returns the output.
#[must_use = "either snapshot the output or assert the exit status with .success()"]
pub fn run_jj_in<I>(&self, current_dir: impl AsRef<Path>, args: I) -> CommandOutput
where
I: IntoIterator,
I::Item: AsRef<OsStr>,
{
self.work_dir(current_dir).run_jj(args)
}
/// Runs `jj` command with additional configuration, returns the output.
#[must_use = "either snapshot the output or assert the exit status with .success()"]
pub fn run_jj_with(
&self,
configure: impl FnOnce(&mut assert_cmd::Command) -> &mut assert_cmd::Command,
) -> CommandOutput {
self.work_dir("").run_jj_with(configure)
}
/// Returns command builder to run `jj` in the test environment.
///
/// Use `run_jj_with()` to run command within customized environment.
#[must_use]
pub fn new_jj_cmd(&self) -> assert_cmd::Command {
let jj_path = assert_cmd::cargo::cargo_bin!("jj");
let mut cmd = assert_cmd::Command::new(jj_path);
cmd.current_dir(&self.env_root);
cmd.env_clear();
cmd.env("COLUMNS", "100");
cmd.env("RUST_BACKTRACE", "1");
// We want to keep the "PATH" environment variable to allow accessing
// executables like `git` from the PATH.
cmd.env("PATH", std::env::var_os("PATH").unwrap_or_default());
cmd.env("HOME", &self.home_dir);
if !cfg!(windows) {
// Override TMPDIR so editor-* files won't be left in global /tmp.
// https://doc.rust-lang.org/stable/std/env/fn.temp_dir.html
cmd.env("TMPDIR", &self.tmp_dir);
} else {
// On Windows, "/tmp" mounted in Git Bash appears to be leaked to
// other Git Bash processes running concurrently, so the TEMP path
// has to be stable.
cmd.env("TEMP", std::env::temp_dir());
}
// Prevent git.subprocess from reading outside git config
cmd.env("GIT_CONFIG_SYSTEM", "/dev/null");
cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");
for (i, (key, value)) in testutils::HERMETIC_GIT_CONFIGS.iter().enumerate() {
cmd.env(format!("GIT_CONFIG_KEY_{i}"), key);
cmd.env(format!("GIT_CONFIG_VALUE_{i}"), value);
}
cmd.env(
"GIT_CONFIG_COUNT",
testutils::HERMETIC_GIT_CONFIGS.len().to_string(),
);
cmd.env("JJ_CONFIG", &self.config_path);
cmd.env("JJ_USER", "Test User");
cmd.env("JJ_EMAIL", "test.user@example.com");
cmd.env("JJ_OP_HOSTNAME", "host.example.com");
cmd.env("JJ_OP_USERNAME", "test-username");
cmd.env("JJ_TZ_OFFSET_MINS", "660");
// Coverage files should not pollute the working directory
if let Some(cov_var) = std::env::var_os("LLVM_PROFILE_FILE") {
cmd.env("LLVM_PROFILE_FILE", cov_var);
}
let mut command_number = self.command_number.borrow_mut();
*command_number += 1;
cmd.env("JJ_RANDOMNESS_SEED", command_number.to_string());
let timestamp = chrono::DateTime::parse_from_rfc3339("2001-02-03T04:05:06+07:00").unwrap();
let timestamp = timestamp + chrono::Duration::try_seconds(*command_number).unwrap();
cmd.env("JJ_TIMESTAMP", timestamp.to_rfc3339());
cmd.env("JJ_OP_TIMESTAMP", timestamp.to_rfc3339());
for (key, value) in &self.env_vars {
cmd.env(key, value);
}
cmd
}
pub fn env_root(&self) -> &Path {
&self.env_root
}
pub fn home_dir(&self) -> &Path {
&self.home_dir
}
pub fn config_path(&self) -> &PathBuf {
&self.config_path
}
pub fn first_config_file_path(&self) -> PathBuf {
let config_file_number = 1;
self.config_path
.join(format!("config{config_file_number:04}.toml"))
}
pub fn last_config_file_path(&self) -> PathBuf {
let config_file_number = self.config_file_number.borrow();
self.config_path
.join(format!("config{config_file_number:04}.toml"))
}
pub fn set_config_path(&mut self, config_path: impl Into<PathBuf>) {
self.config_path = config_path.into();
}
pub fn add_config(&self, content: impl AsRef<[u8]>) {
if self.config_path.is_file() {
panic!("add_config not supported when config_path is a file");
}
// Concatenating two valid TOML files does not (generally) result in a valid
// TOML file, so we create a new file every time instead.
let mut config_file_number = self.config_file_number.borrow_mut();
*config_file_number += 1;
let config_file_number = *config_file_number;
std::fs::write(
self.config_path
.join(format!("config{config_file_number:04}.toml")),
content,
)
.unwrap();
}
pub fn add_env_var(&mut self, key: impl Into<OsString>, val: impl Into<OsString>) {
self.env_vars.insert(key.into(), val.into());
}
pub fn add_paths_to_normalize(
&mut self,
path: impl Into<PathBuf>,
replacement: impl Into<String>,
) {
self.paths_to_normalize
.push((path.into(), replacement.into()));
}
/// Sets up echo as a merge tool.
///
/// Windows machines may not have the echo executable installed.
pub fn set_up_fake_echo_merge_tool(&self) {
let echo_path = assert_cmd::cargo::cargo_bin!("fake-echo");
assert!(echo_path.is_file());
let echo_path = to_toml_value(echo_path.to_str().unwrap());
self.add_config(formatdoc!("merge-tools.fake-echo.program = {echo_path}"));
}
/// Sets up the fake bisection test command to read a script from the
/// returned path
pub fn set_up_fake_bisector(&mut self) -> PathBuf {
self.add_paths_to_normalize(fake_bisector_path(), "$FAKE_BISECTOR_PATH");
let bisection_script = self.env_root().join("bisection_script");
std::fs::write(&bisection_script, "").unwrap();
self.add_env_var("BISECTION_SCRIPT", &bisection_script);
bisection_script
}
/// Sets up the fake editor to read an edit script from the returned path
/// Also sets up the fake editor as a merge tool named "fake-editor"
pub fn set_up_fake_editor(&mut self) -> PathBuf {
let editor_path = to_toml_value(fake_editor_path());
self.add_config(formatdoc! {r#"
[ui]
editor = {editor_path}
merge-editor = "fake-editor"
[merge-tools]
fake-editor.program = {editor_path}
fake-editor.merge-args = ["$output"]
"#});
let edit_script = self.env_root().join("edit_script");
std::fs::write(&edit_script, "").unwrap();
self.add_env_var("EDIT_SCRIPT", &edit_script);
edit_script
}
/// Sets up the fake diff-editor to read an edit script from the returned
/// path
pub fn set_up_fake_diff_editor(&mut self) -> PathBuf {
let diff_editor_path = to_toml_value(fake_diff_editor_path());
self.add_config(formatdoc! {r#"
ui.diff-editor = "fake-diff-editor"
merge-tools.fake-diff-editor.program = {diff_editor_path}
"#});
let edit_script = self.env_root().join("diff_edit_script");
std::fs::write(&edit_script, "").unwrap();
self.add_env_var("DIFF_EDIT_SCRIPT", &edit_script);
edit_script
}
#[must_use]
fn normalize_output(&self, raw: String) -> CommandOutputString {
let mut normalized = raw.replace("jj.exe", "jj");
for (path, replacement) in &self.paths_to_normalize {
let path = path.display().to_string();
// Platform-native $TEST_ENV
let regex = Regex::new(&format!(r"{}((:?[/\\]\S+)?)", regex::escape(&path))).unwrap();
normalized = regex
.replace_all(&normalized, |caps: &Captures| {
format!("{}{}", replacement, caps[1].replace('\\', "/"))
})
.to_string();
// Slash-separated $TEST_ENV
if cfg!(windows) {
let regex = Regex::new(®ex::escape(&path.replace('\\', "/"))).unwrap();
normalized = regex
.replace_all(&normalized, regex::NoExpand(replacement))
.to_string();
};
}
CommandOutputString { raw, normalized }
}
/// Used before mutating operations to create more predictable commit ids
/// and change ids in tests
///
/// `test_env.advance_test_rng_seed_to_multiple_of(200_000)` can be inserted
/// wherever convenient throughout your test. If desired, you can have
/// "subheadings" with steps of (e.g.) 10_000, 500, 25.
pub fn advance_test_rng_seed_to_multiple_of(&self, step: i64) {
assert!(step > 0, "step must be >0, got {step}");
let mut command_number = self.command_number.borrow_mut();
*command_number = step * (*command_number / step) + step;
}
}
/// Helper to execute `jj` or file operation in sub directory.
pub struct TestWorkDir<'a> {
env: &'a TestEnvironment,
root: PathBuf,
}
impl TestWorkDir<'_> {
/// Path to the working directory.
pub fn root(&self) -> &Path {
&self.root
}
/// Runs `jj args..` in the working directory, returns the output.
#[must_use = "either snapshot the output or assert the exit status with .success()"]
pub fn run_jj<I>(&self, args: I) -> CommandOutput
where
I: IntoIterator,
I::Item: AsRef<OsStr>,
{
self.run_jj_with(|cmd| cmd.args(args))
}
/// Runs `jj` command with additional configuration, returns the output.
#[must_use = "either snapshot the output or assert the exit status with .success()"]
pub fn run_jj_with(
&self,
configure: impl FnOnce(&mut assert_cmd::Command) -> &mut assert_cmd::Command,
) -> CommandOutput {
let env = &self.env;
let mut cmd = env.new_jj_cmd();
let output = configure(cmd.current_dir(&self.root)).output().unwrap();
CommandOutput {
stdout: env.normalize_output(String::from_utf8(output.stdout).unwrap()),
stderr: env.normalize_output(String::from_utf8(output.stderr).unwrap()),
status: output.status,
}
}
/// Reads the current operation id without resolving divergence nor
/// snapshotting. `TestWorkDir` must be at the workspace root.
#[track_caller]
pub fn current_operation_id(&self) -> String {
let heads_dir = self
.root()
.join(PathBuf::from_iter([".jj", "repo", "op_heads", "heads"]));
let head_entry = heads_dir
.read_dir()
.expect("TestWorkDir must point to the workspace root")
.exactly_one()
.expect("divergence not supported")
.unwrap();
head_entry.file_name().into_string().unwrap()
}
/// Returns test helper for the specified sub directory.
#[must_use]
pub fn dir(&self, path: impl AsRef<Path>) -> Self {
let env = self.env;
let root = self.root.join(path);
TestWorkDir { env, root }
}
#[track_caller]
pub fn create_dir(&self, path: impl AsRef<Path>) -> Self {
let dir = self.dir(path);
std::fs::create_dir(&dir.root).unwrap();
dir
}
#[track_caller]
pub fn create_dir_all(&self, path: impl AsRef<Path>) -> Self {
let dir = self.dir(path);
std::fs::create_dir_all(&dir.root).unwrap();
dir
}
#[track_caller]
pub fn remove_dir_all(&self, path: impl AsRef<Path>) {
std::fs::remove_dir_all(self.root.join(path)).unwrap();
}
#[track_caller]
pub fn remove_file(&self, path: impl AsRef<Path>) {
std::fs::remove_file(self.root.join(path)).unwrap();
}
#[track_caller]
pub fn read_file(&self, path: impl AsRef<Path>) -> BString {
std::fs::read(self.root.join(path)).unwrap().into()
}
#[track_caller]
pub fn write_file(&self, path: impl AsRef<Path>, contents: impl AsRef<[u8]>) {
let path = path.as_ref();
if let Some(dir) = path.parent() {
self.create_dir_all(dir);
}
std::fs::write(self.root.join(path), contents).unwrap();
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/examples/custom-commit-templater/main.rs | cli/examples/custom-commit-templater/main.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::sync::Arc;
use jj_cli::cli_util::CliRunner;
use jj_cli::commit_templater::CommitTemplateBuildFnTable;
use jj_cli::commit_templater::CommitTemplateLanguageExtension;
use jj_cli::template_parser;
use jj_cli::template_parser::TemplateParseError;
use jj_cli::templater::TemplatePropertyExt as _;
use jj_lib::backend::CommitId;
use jj_lib::commit::Commit;
use jj_lib::extensions_map::ExtensionsMap;
use jj_lib::object_id::ObjectId as _;
use jj_lib::repo::Repo;
use jj_lib::revset::FunctionCallNode;
use jj_lib::revset::LoweringContext;
use jj_lib::revset::PartialSymbolResolver;
use jj_lib::revset::RevsetDiagnostics;
use jj_lib::revset::RevsetExpression;
use jj_lib::revset::RevsetFilterExtension;
use jj_lib::revset::RevsetFilterPredicate;
use jj_lib::revset::RevsetParseError;
use jj_lib::revset::RevsetResolutionError;
use jj_lib::revset::SymbolResolverExtension;
use jj_lib::revset::UserRevsetExpression;
use once_cell::sync::OnceCell;
struct HexCounter;
fn num_digits_in_id(id: &CommitId) -> i64 {
let mut count = 0;
for ch in id.hex().chars() {
if ch.is_ascii_digit() {
count += 1;
}
}
count
}
fn num_char_in_id(commit: Commit, ch_match: char) -> i64 {
let mut count = 0;
for ch in commit.id().hex().chars() {
if ch == ch_match {
count += 1;
}
}
count
}
#[derive(Default)]
struct MostDigitsInId {
count: OnceCell<i64>,
}
impl MostDigitsInId {
fn count(&self, repo: &dyn Repo) -> i64 {
*self.count.get_or_init(|| {
RevsetExpression::all()
.evaluate(repo)
.unwrap()
.iter()
.map(Result::unwrap)
.map(|id| num_digits_in_id(&id))
.max()
.unwrap_or(0)
})
}
}
#[derive(Default)]
struct TheDigitestResolver {
cache: MostDigitsInId,
}
impl PartialSymbolResolver for TheDigitestResolver {
fn resolve_symbol(
&self,
repo: &dyn Repo,
symbol: &str,
) -> Result<Option<CommitId>, RevsetResolutionError> {
if symbol != "thedigitest" {
return Ok(None);
}
Ok(RevsetExpression::all()
.evaluate(repo)
.map_err(|err| RevsetResolutionError::Other(err.into()))?
.iter()
.map(Result::unwrap)
.find(|id| num_digits_in_id(id) == self.cache.count(repo)))
}
}
struct TheDigitest;
impl SymbolResolverExtension for TheDigitest {
fn new_resolvers<'a>(&self, _repo: &'a dyn Repo) -> Vec<Box<dyn PartialSymbolResolver + 'a>> {
vec![Box::<TheDigitestResolver>::default()]
}
}
impl CommitTemplateLanguageExtension for HexCounter {
fn build_fn_table<'repo>(&self) -> CommitTemplateBuildFnTable<'repo> {
let mut table = CommitTemplateBuildFnTable::empty();
table.commit_methods.insert(
"has_most_digits",
|language, _diagnostics, _build_context, property, call| {
call.expect_no_arguments()?;
let most_digits = language
.cache_extension::<MostDigitsInId>()
.unwrap()
.count(language.repo());
let out_property =
property.map(move |commit| num_digits_in_id(commit.id()) == most_digits);
Ok(out_property.into_dyn_wrapped())
},
);
table.commit_methods.insert(
"num_digits_in_id",
|_language, _diagnostics, _build_context, property, call| {
call.expect_no_arguments()?;
let out_property = property.map(|commit| num_digits_in_id(commit.id()));
Ok(out_property.into_dyn_wrapped())
},
);
table.commit_methods.insert(
"num_char_in_id",
|_language, diagnostics, _build_context, property, call| {
let [string_arg] = call.expect_exact_arguments()?;
let char_arg = template_parser::catch_aliases(
diagnostics,
string_arg,
|_diagnostics, arg| {
let string = template_parser::expect_string_literal(arg)?;
let chars: Vec<_> = string.chars().collect();
match chars[..] {
[ch] => Ok(ch),
_ => Err(TemplateParseError::expression(
"Expected singular character argument",
arg.span,
)),
}
},
)?;
let out_property = property.map(move |commit| num_char_in_id(commit, char_arg));
Ok(out_property.into_dyn_wrapped())
},
);
table
}
fn build_cache_extensions(&self, extensions: &mut ExtensionsMap) {
extensions.insert(MostDigitsInId::default());
}
}
#[derive(Debug)]
struct EvenDigitsFilter;
impl RevsetFilterExtension for EvenDigitsFilter {
fn matches_commit(&self, commit: &Commit) -> bool {
num_digits_in_id(commit.id()) % 2 == 0
}
}
fn even_digits(
_diagnostics: &mut RevsetDiagnostics,
function: &FunctionCallNode,
_context: &LoweringContext,
) -> Result<Arc<UserRevsetExpression>, RevsetParseError> {
function.expect_no_arguments()?;
Ok(RevsetExpression::filter(RevsetFilterPredicate::Extension(
Arc::new(EvenDigitsFilter),
)))
}
fn main() -> std::process::ExitCode {
CliRunner::init()
.add_symbol_resolver_extension(Box::new(TheDigitest))
.add_revset_function_extension("even_digits", even_digits)
.add_commit_template_extension(Box::new(HexCounter))
.run()
.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/examples/custom-operation-templater/main.rs | cli/examples/custom-operation-templater/main.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_cli::cli_util::CliRunner;
use jj_cli::operation_templater::OperationTemplateLanguageBuildFnTable;
use jj_cli::operation_templater::OperationTemplateLanguageExtension;
use jj_cli::template_parser;
use jj_cli::template_parser::TemplateParseError;
use jj_cli::templater::TemplatePropertyExt as _;
use jj_lib::extensions_map::ExtensionsMap;
use jj_lib::object_id::ObjectId as _;
use jj_lib::op_store::OperationId;
use jj_lib::operation::Operation;
struct HexCounter;
fn num_digits_in_id(id: &OperationId) -> i64 {
let mut count = 0;
for ch in id.hex().chars() {
if ch.is_ascii_digit() {
count += 1;
}
}
count
}
fn num_char_in_id(operation: Operation, ch_match: char) -> i64 {
let mut count = 0;
for ch in operation.id().hex().chars() {
if ch == ch_match {
count += 1;
}
}
count
}
impl OperationTemplateLanguageExtension for HexCounter {
fn build_fn_table(&self) -> OperationTemplateLanguageBuildFnTable {
let mut table = OperationTemplateLanguageBuildFnTable::empty();
table.operation.operation_methods.insert(
"num_digits_in_id",
|_language, _diagnostics, _build_context, property, call| {
call.expect_no_arguments()?;
let out_property = property.map(|operation| num_digits_in_id(operation.id()));
Ok(out_property.into_dyn_wrapped())
},
);
table.operation.operation_methods.insert(
"num_char_in_id",
|_language, diagnostics, _build_context, property, call| {
let [string_arg] = call.expect_exact_arguments()?;
let char_arg = template_parser::catch_aliases(
diagnostics,
string_arg,
|_diagnostics, arg| {
let string = template_parser::expect_string_literal(arg)?;
let chars: Vec<_> = string.chars().collect();
match chars[..] {
[ch] => Ok(ch),
_ => Err(TemplateParseError::expression(
"Expected singular character argument",
arg.span,
)),
}
},
)?;
let out_property =
property.map(move |operation| num_char_in_id(operation, char_arg));
Ok(out_property.into_dyn_wrapped())
},
);
table
}
fn build_cache_extensions(&self, _extensions: &mut ExtensionsMap) {}
}
fn main() -> std::process::ExitCode {
CliRunner::init()
.add_operation_template_extension(Box::new(HexCounter))
.run()
.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/examples/custom-command/main.rs | cli/examples/custom-command/main.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::io::Write as _;
use jj_cli::cli_util::CliRunner;
use jj_cli::cli_util::CommandHelper;
use jj_cli::cli_util::RevisionArg;
use jj_cli::command_error::CommandError;
use jj_cli::ui::Ui;
#[derive(clap::Parser, Clone, Debug)]
enum CustomCommand {
Frobnicate(FrobnicateArgs),
}
/// Frobnicate a revisions
#[derive(clap::Args, Clone, Debug)]
struct FrobnicateArgs {
/// The revision to frobnicate
#[arg(default_value = "@")]
revision: RevisionArg,
}
fn run_custom_command(
ui: &mut Ui,
command_helper: &CommandHelper,
command: CustomCommand,
) -> Result<(), CommandError> {
match command {
CustomCommand::Frobnicate(args) => {
let mut workspace_command = command_helper.workspace_helper(ui)?;
let commit = workspace_command.resolve_single_rev(ui, &args.revision)?;
let mut tx = workspace_command.start_transaction();
let new_commit = tx
.repo_mut()
.rewrite_commit(&commit)
.set_description("Frobnicated!")
.write()?;
tx.finish(ui, "frobnicate")?;
writeln!(
ui.status(),
"Frobnicated revision: {}",
workspace_command.format_commit_summary(&new_commit)
)?;
Ok(())
}
}
}
fn main() -> std::process::ExitCode {
CliRunner::init()
.add_subcommand(run_custom_command)
.run()
.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/examples/custom-working-copy/main.rs | cli/examples/custom-working-copy/main.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::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use async_trait::async_trait;
use itertools::Itertools as _;
use jj_cli::cli_util::CliRunner;
use jj_cli::cli_util::CommandHelper;
use jj_cli::command_error::CommandError;
use jj_cli::ui::Ui;
use jj_lib::backend::Backend;
use jj_lib::commit::Commit;
use jj_lib::git_backend::GitBackend;
use jj_lib::local_working_copy::LocalWorkingCopy;
use jj_lib::merged_tree::MergedTree;
use jj_lib::op_store::OperationId;
use jj_lib::ref_name::WorkspaceName;
use jj_lib::ref_name::WorkspaceNameBuf;
use jj_lib::repo::ReadonlyRepo;
use jj_lib::repo_path::RepoPathBuf;
use jj_lib::settings::UserSettings;
use jj_lib::signing::Signer;
use jj_lib::store::Store;
use jj_lib::working_copy::CheckoutError;
use jj_lib::working_copy::CheckoutStats;
use jj_lib::working_copy::LockedWorkingCopy;
use jj_lib::working_copy::ResetError;
use jj_lib::working_copy::SnapshotError;
use jj_lib::working_copy::SnapshotOptions;
use jj_lib::working_copy::SnapshotStats;
use jj_lib::working_copy::WorkingCopy;
use jj_lib::working_copy::WorkingCopyFactory;
use jj_lib::working_copy::WorkingCopyStateError;
use jj_lib::workspace::WorkingCopyFactories;
use jj_lib::workspace::Workspace;
use jj_lib::workspace::WorkspaceInitError;
#[derive(clap::Parser, Clone, Debug)]
enum CustomCommand {
/// Initialize a workspace using the "conflicts" working copy
InitConflicts,
}
fn run_custom_command(
_ui: &mut Ui,
command_helper: &CommandHelper,
command: CustomCommand,
) -> Result<(), CommandError> {
match command {
CustomCommand::InitConflicts => {
let wc_path = command_helper.cwd();
let settings = command_helper.settings_for_new_workspace(wc_path)?;
let backend_initializer = |settings: &UserSettings, store_path: &Path| {
let backend: Box<dyn Backend> =
Box::new(GitBackend::init_internal(settings, store_path)?);
Ok(backend)
};
Workspace::init_with_factories(
&settings,
wc_path,
&backend_initializer,
Signer::from_settings(&settings).map_err(WorkspaceInitError::SignInit)?,
&ReadonlyRepo::default_op_store_initializer(),
&ReadonlyRepo::default_op_heads_store_initializer(),
&ReadonlyRepo::default_index_store_initializer(),
&ReadonlyRepo::default_submodule_store_initializer(),
&ConflictsWorkingCopyFactory {},
WorkspaceName::DEFAULT.to_owned(),
)?;
Ok(())
}
}
}
fn main() -> std::process::ExitCode {
let mut working_copy_factories = WorkingCopyFactories::new();
working_copy_factories.insert(
ConflictsWorkingCopy::name().to_owned(),
Box::new(ConflictsWorkingCopyFactory {}),
);
CliRunner::init()
.add_working_copy_factories(working_copy_factories)
.add_subcommand(run_custom_command)
.run()
.into()
}
/// A working copy that adds a .conflicts file with a list of unresolved
/// conflicts.
///
/// Most functions below just delegate to the inner working-copy backend. The
/// only interesting functions are `snapshot()` and `check_out()`. The former
/// adds `.conflicts` to the .gitignores. The latter writes the `.conflicts`
/// file to the working copy.
struct ConflictsWorkingCopy {
inner: Box<dyn WorkingCopy>,
working_copy_path: PathBuf,
}
impl ConflictsWorkingCopy {
fn name() -> &'static str {
"conflicts"
}
fn init(
store: Arc<Store>,
working_copy_path: PathBuf,
state_path: PathBuf,
operation_id: OperationId,
workspace_name: WorkspaceNameBuf,
user_settings: &UserSettings,
) -> Result<Self, WorkingCopyStateError> {
let inner = LocalWorkingCopy::init(
store,
working_copy_path.clone(),
state_path,
operation_id,
workspace_name,
user_settings,
)?;
Ok(Self {
inner: Box::new(inner),
working_copy_path,
})
}
fn load(
store: Arc<Store>,
working_copy_path: PathBuf,
state_path: PathBuf,
user_settings: &UserSettings,
) -> Result<Self, WorkingCopyStateError> {
let inner =
LocalWorkingCopy::load(store, working_copy_path.clone(), state_path, user_settings)?;
Ok(Self {
inner: Box::new(inner),
working_copy_path,
})
}
}
impl WorkingCopy for ConflictsWorkingCopy {
fn name(&self) -> &str {
Self::name()
}
fn workspace_name(&self) -> &WorkspaceName {
self.inner.workspace_name()
}
fn operation_id(&self) -> &OperationId {
self.inner.operation_id()
}
fn tree(&self) -> Result<&MergedTree, WorkingCopyStateError> {
self.inner.tree()
}
fn sparse_patterns(&self) -> Result<&[RepoPathBuf], WorkingCopyStateError> {
self.inner.sparse_patterns()
}
fn start_mutation(&self) -> Result<Box<dyn LockedWorkingCopy>, WorkingCopyStateError> {
let inner = self.inner.start_mutation()?;
Ok(Box::new(LockedConflictsWorkingCopy {
wc_path: self.working_copy_path.clone(),
inner,
}))
}
}
struct ConflictsWorkingCopyFactory {}
impl WorkingCopyFactory for ConflictsWorkingCopyFactory {
fn init_working_copy(
&self,
store: Arc<Store>,
working_copy_path: PathBuf,
state_path: PathBuf,
operation_id: OperationId,
workspace_name: WorkspaceNameBuf,
settings: &UserSettings,
) -> Result<Box<dyn WorkingCopy>, WorkingCopyStateError> {
Ok(Box::new(ConflictsWorkingCopy::init(
store,
working_copy_path,
state_path,
operation_id,
workspace_name,
settings,
)?))
}
fn load_working_copy(
&self,
store: Arc<Store>,
working_copy_path: PathBuf,
state_path: PathBuf,
settings: &UserSettings,
) -> Result<Box<dyn WorkingCopy>, WorkingCopyStateError> {
Ok(Box::new(ConflictsWorkingCopy::load(
store,
working_copy_path,
state_path,
settings,
)?))
}
}
struct LockedConflictsWorkingCopy {
wc_path: PathBuf,
inner: Box<dyn LockedWorkingCopy + Send>,
}
#[async_trait]
impl LockedWorkingCopy for LockedConflictsWorkingCopy {
fn old_operation_id(&self) -> &OperationId {
self.inner.old_operation_id()
}
fn old_tree(&self) -> &MergedTree {
self.inner.old_tree()
}
async fn snapshot(
&mut self,
options: &SnapshotOptions,
) -> Result<(MergedTree, SnapshotStats), SnapshotError> {
let options = SnapshotOptions {
base_ignores: options.base_ignores.chain(
"",
Path::new(""),
"/.conflicts".as_bytes(),
)?,
..options.clone()
};
self.inner.snapshot(&options).await
}
async fn check_out(&mut self, commit: &Commit) -> Result<CheckoutStats, CheckoutError> {
let conflicts = commit
.tree()
.conflicts()
.map(|(path, _value)| format!("{}\n", path.as_internal_file_string()))
.join("");
std::fs::write(self.wc_path.join(".conflicts"), conflicts).unwrap();
self.inner.check_out(commit).await
}
fn rename_workspace(&mut self, new_name: WorkspaceNameBuf) {
self.inner.rename_workspace(new_name);
}
async fn reset(&mut self, commit: &Commit) -> Result<(), ResetError> {
self.inner.reset(commit).await
}
async fn recover(&mut self, commit: &Commit) -> Result<(), ResetError> {
self.inner.recover(commit).await
}
fn sparse_patterns(&self) -> Result<&[RepoPathBuf], WorkingCopyStateError> {
self.inner.sparse_patterns()
}
async fn set_sparse_patterns(
&mut self,
new_sparse_patterns: Vec<RepoPathBuf>,
) -> Result<CheckoutStats, CheckoutError> {
self.inner.set_sparse_patterns(new_sparse_patterns).await
}
async fn finish(
self: Box<Self>,
operation_id: OperationId,
) -> Result<Box<dyn WorkingCopy>, WorkingCopyStateError> {
let inner = self.inner.finish(operation_id).await?;
Ok(Box::new(ConflictsWorkingCopy {
inner,
working_copy_path: self.wc_path,
}))
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/examples/custom-backend/main.rs | cli/examples/custom-backend/main.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::pin::Pin;
use std::time::SystemTime;
use async_trait::async_trait;
use futures::stream::BoxStream;
use jj_cli::cli_util::CliRunner;
use jj_cli::cli_util::CommandHelper;
use jj_cli::command_error::CommandError;
use jj_cli::ui::Ui;
use jj_lib::backend::Backend;
use jj_lib::backend::BackendInitError;
use jj_lib::backend::BackendLoadError;
use jj_lib::backend::BackendResult;
use jj_lib::backend::ChangeId;
use jj_lib::backend::Commit;
use jj_lib::backend::CommitId;
use jj_lib::backend::CopyHistory;
use jj_lib::backend::CopyId;
use jj_lib::backend::CopyRecord;
use jj_lib::backend::FileId;
use jj_lib::backend::SigningFn;
use jj_lib::backend::SymlinkId;
use jj_lib::backend::Tree;
use jj_lib::backend::TreeId;
use jj_lib::git_backend::GitBackend;
use jj_lib::index::Index;
use jj_lib::repo::StoreFactories;
use jj_lib::repo_path::RepoPath;
use jj_lib::repo_path::RepoPathBuf;
use jj_lib::settings::UserSettings;
use jj_lib::signing::Signer;
use jj_lib::workspace::Workspace;
use jj_lib::workspace::WorkspaceInitError;
use tokio::io::AsyncRead;
#[derive(clap::Parser, Clone, Debug)]
enum CustomCommand {
/// Initialize a workspace using the Jit backend
InitJit,
}
fn create_store_factories() -> StoreFactories {
let mut store_factories = StoreFactories::empty();
// Register the backend so it can be loaded when the repo is loaded. The name
// must match `Backend::name()`.
store_factories.add_backend(
"jit",
Box::new(|settings, store_path| Ok(Box::new(JitBackend::load(settings, store_path)?))),
);
store_factories
}
fn run_custom_command(
_ui: &mut Ui,
command_helper: &CommandHelper,
command: CustomCommand,
) -> Result<(), CommandError> {
match command {
CustomCommand::InitJit => {
let wc_path = command_helper.cwd();
let settings = command_helper.settings_for_new_workspace(wc_path)?;
// Initialize a workspace with the custom backend
Workspace::init_with_backend(
&settings,
wc_path,
&|settings, store_path| Ok(Box::new(JitBackend::init(settings, store_path)?)),
Signer::from_settings(&settings).map_err(WorkspaceInitError::SignInit)?,
)?;
Ok(())
}
}
}
fn main() -> std::process::ExitCode {
CliRunner::init()
.add_store_factories(create_store_factories())
.add_subcommand(run_custom_command)
.run()
.into()
}
/// A commit backend that's extremely similar to the Git backend
#[derive(Debug)]
struct JitBackend {
inner: GitBackend,
}
impl JitBackend {
fn init(settings: &UserSettings, store_path: &Path) -> Result<Self, BackendInitError> {
let inner = GitBackend::init_internal(settings, store_path)?;
Ok(Self { inner })
}
fn load(settings: &UserSettings, store_path: &Path) -> Result<Self, BackendLoadError> {
let inner = GitBackend::load(settings, store_path)?;
Ok(Self { inner })
}
}
#[async_trait]
impl Backend for JitBackend {
fn name(&self) -> &'static str {
"jit"
}
fn commit_id_length(&self) -> usize {
self.inner.commit_id_length()
}
fn change_id_length(&self) -> usize {
self.inner.change_id_length()
}
fn root_commit_id(&self) -> &CommitId {
self.inner.root_commit_id()
}
fn root_change_id(&self) -> &ChangeId {
self.inner.root_change_id()
}
fn empty_tree_id(&self) -> &TreeId {
self.inner.empty_tree_id()
}
fn concurrency(&self) -> usize {
1
}
async fn read_file(
&self,
path: &RepoPath,
id: &FileId,
) -> BackendResult<Pin<Box<dyn AsyncRead + Send>>> {
self.inner.read_file(path, id).await
}
async fn write_file(
&self,
path: &RepoPath,
contents: &mut (dyn AsyncRead + Send + Unpin),
) -> BackendResult<FileId> {
self.inner.write_file(path, contents).await
}
async fn read_symlink(&self, path: &RepoPath, id: &SymlinkId) -> BackendResult<String> {
self.inner.read_symlink(path, id).await
}
async fn write_symlink(&self, path: &RepoPath, target: &str) -> BackendResult<SymlinkId> {
self.inner.write_symlink(path, target).await
}
async fn read_copy(&self, id: &CopyId) -> BackendResult<CopyHistory> {
self.inner.read_copy(id).await
}
async fn write_copy(&self, contents: &CopyHistory) -> BackendResult<CopyId> {
self.inner.write_copy(contents).await
}
async fn get_related_copies(&self, copy_id: &CopyId) -> BackendResult<Vec<CopyHistory>> {
self.inner.get_related_copies(copy_id).await
}
async fn read_tree(&self, path: &RepoPath, id: &TreeId) -> BackendResult<Tree> {
self.inner.read_tree(path, id).await
}
async fn write_tree(&self, path: &RepoPath, contents: &Tree) -> BackendResult<TreeId> {
self.inner.write_tree(path, contents).await
}
async fn read_commit(&self, id: &CommitId) -> BackendResult<Commit> {
self.inner.read_commit(id).await
}
async fn write_commit(
&self,
contents: Commit,
sign_with: Option<&mut SigningFn>,
) -> BackendResult<(CommitId, Commit)> {
self.inner.write_commit(contents, sign_with).await
}
fn get_copy_records(
&self,
paths: Option<&[RepoPathBuf]>,
root: &CommitId,
head: &CommitId,
) -> BackendResult<BoxStream<'_, BackendResult<CopyRecord>>> {
self.inner.get_copy_records(paths, root, head)
}
fn gc(&self, index: &dyn Index, keep_newer: SystemTime) -> BackendResult<()> {
self.inner.gc(index, keep_newer)
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/examples/custom-global-flag/main.rs | cli/examples/custom-global-flag/main.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::io::Write as _;
use jj_cli::cli_util::CliRunner;
use jj_cli::command_error::CommandError;
use jj_cli::ui::Ui;
#[derive(clap::Args, Clone, Debug)]
struct CustomGlobalArgs {
/// Show a greeting before each command
#[arg(long, global = true)]
greet: bool,
}
fn process_before(ui: &mut Ui, custom_global_args: CustomGlobalArgs) -> Result<(), CommandError> {
if custom_global_args.greet {
writeln!(ui.stdout(), "Hello!")?;
}
Ok(())
}
fn main() -> std::process::ExitCode {
CliRunner::init()
.add_global_args(process_before)
.run()
.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/testing/fake-formatter.rs | cli/testing/fake-formatter.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::fs::OpenOptions;
use std::io::Read as _;
use std::io::Write as _;
use std::path::PathBuf;
use std::process::ExitCode;
use bstr::ByteSlice as _;
use clap::Parser;
use itertools::Itertools as _;
/// A fake code formatter, useful for testing
///
/// `fake-formatter` is similar to `cat`.
/// `fake-formatter --reverse` is similar to `rev` (not `tac`).
/// `fake-formatter --stdout foo` is similar to `echo foo`.
/// `fake-formatter --stdout foo --stderr bar --fail` is similar to
/// `echo foo; echo bar >&2; false`.
/// `fake-formatter --tee foo` is similar to `tee foo`).
///
/// This program acts as a portable alternative to that class of shell commands.
#[derive(Parser, Debug)]
struct Args {
/// Exit with non-successful status.
#[arg(long, default_value_t = false)]
fail: bool,
/// Abort instead of exiting
#[arg(long, default_value_t = false, conflicts_with = "fail")]
abort: bool,
/// Reverse the characters in each line when reading stdin.
#[arg(long, default_value_t = false)]
reverse: bool,
/// Convert all characters to uppercase when reading stdin.
#[arg(long, default_value_t = false)]
uppercase: bool,
/// Convert all characters to lowercase when reading stdin.
#[arg(long, default_value_t = false)]
lowercase: bool,
/// Adds a line to the end of the file
#[arg(long)]
append: Option<String>,
/// Write this string to stdout, and ignore stdin.
#[arg(long)]
stdout: Option<String>,
/// Write this string to stderr.
#[arg(long)]
stderr: Option<String>,
/// Duplicate stdout into this file.
#[arg(long)]
tee: Option<PathBuf>,
/// Read one byte at a time, and send one byte to the stdout before reading
/// the next byte.
#[arg(long, default_value_t = false)]
byte_mode: bool,
}
fn main() -> ExitCode {
let args: Args = Args::parse();
// Code formatters tend to print errors before printing the result.
if let Some(data) = args.stderr {
eprint!("{data}");
}
let stdout = if let Some(data) = args.stdout {
// Other content-altering flags don't apply to --stdout.
assert!(!args.reverse);
assert!(!args.uppercase);
assert!(!args.lowercase);
assert!(args.append.is_none());
print!("{data}");
data
} else if args.byte_mode {
assert!(!args.reverse);
assert!(args.append.is_none());
let mut stdout = vec![];
#[expect(clippy::unbuffered_bytes)]
for byte in std::io::stdin().bytes() {
let byte = byte.expect("Failed to read from stdin");
let output = if args.uppercase {
byte.to_ascii_uppercase()
} else if args.lowercase {
assert!(!args.uppercase);
byte.to_ascii_lowercase()
} else {
byte
};
stdout.push(output);
std::io::stdout()
.write_all(&[output])
.expect("Failed to write to stdout");
}
stdout
.to_str()
.expect("Output is not a valid UTF-8 string")
.to_owned()
} else {
let mut input = vec![];
std::io::stdin()
.read_to_end(&mut input)
.expect("Failed to read from stdin");
let mut stdout = input
.lines_with_terminator()
.map(|line| {
let line = line
.to_str()
.expect("The input is not valid UTF-8 string")
.to_owned();
let line = if args.reverse {
line.chars().rev().collect()
} else {
line
};
if args.uppercase {
assert!(!args.lowercase);
line.to_uppercase()
} else if args.lowercase {
assert!(!args.uppercase);
line.to_lowercase()
} else {
line
}
})
.join("");
if let Some(line) = args.append {
stdout.push_str(&line);
}
print!("{stdout}");
stdout
};
if let Some(path) = args.tee {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.unwrap();
write!(file, "{stdout}").unwrap();
}
if args.abort {
std::process::abort()
} else if args.fail {
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/testing/fake-bisector.rs | cli/testing/fake-bisector.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::env;
use std::fs;
use std::path::PathBuf;
use std::process::exit;
use clap::Parser;
use itertools::Itertools as _;
/// A fake diff-editor, useful for testing
#[derive(Parser, Debug)]
#[clap()]
struct Args {
/// Fail if the given file doesn't exist
#[arg(long)]
require_file: Option<String>,
}
fn main() {
let args: Args = Args::parse();
let edit_script_path = PathBuf::from(env::var_os("BISECTION_SCRIPT").unwrap());
let commit_to_test = env::var_os("JJ_BISECT_TARGET")
.unwrap()
.to_str()
.unwrap()
.to_owned();
println!("fake-bisector testing commit {commit_to_test}");
let edit_script = fs::read_to_string(&edit_script_path).unwrap();
if let Some(path) = args.require_file
&& !std::fs::exists(&path).unwrap()
{
exit(1)
}
let mut instructions = edit_script.split('\0').collect_vec();
if let Some(pos) = instructions.iter().position(|&i| i == "next invocation\n") {
// Overwrite the edit script. The next time `fake-bisector` is called, it will
// only see the part after the `next invocation` command.
fs::write(&edit_script_path, instructions[pos + 1..].join("\0")).unwrap();
instructions.truncate(pos);
}
for instruction in instructions {
let (command, payload) = instruction.split_once('\n').unwrap_or((instruction, ""));
let parts = command.split(' ').collect_vec();
match parts.as_slice() {
[""] => {}
["abort"] => exit(127),
["skip"] => exit(125),
["fail"] => exit(1),
["fail-if-target-is", bad_target_commit] => {
if commit_to_test == *bad_target_commit {
exit(1)
}
}
["write", path] => {
fs::write(path, payload).unwrap_or_else(|_| panic!("Failed to write file {path}"));
}
["jj", args @ ..] => {
let jj_executable_path = PathBuf::from(env::var_os("JJ_EXECUTABLE_PATH").unwrap());
let status = std::process::Command::new(&jj_executable_path)
.args(args)
.status()
.unwrap();
if !status.success() {
eprintln!("fake-bisector: failed to run jj: {status:?}");
exit(1)
}
}
_ => {
eprintln!("fake-bisector: unexpected command: {command}");
exit(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/testing/fake-editor.rs | cli/testing/fake-editor.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;
use std::fs;
use std::path::PathBuf;
use std::process::exit;
use clap::Parser;
use itertools::Itertools as _;
/// A fake editor, useful for testing
// It's overkill to use clap for a single argument, but we already use it in many other places...
#[derive(Parser, Debug)]
#[clap()]
struct Args {
/// Path to the file to edit
file: PathBuf,
/// Other arguments to the editor
other_args: Vec<String>,
}
fn main() {
let args: Args = Args::parse();
let edit_script_path = PathBuf::from(env::var_os("EDIT_SCRIPT").unwrap());
let edit_script = fs::read_to_string(&edit_script_path).unwrap();
let mut instructions = edit_script.split('\0').collect_vec();
if let Some(pos) = instructions.iter().position(|&i| i == "next invocation\n") {
// Overwrite the edit script. The next time `fake-editor` is called, it will
// only see the part after the `next invocation` command.
fs::write(&edit_script_path, instructions[pos + 1..].join("\0")).unwrap();
instructions.truncate(pos);
}
for instruction in instructions {
let (command, payload) = instruction.split_once('\n').unwrap_or((instruction, ""));
let parts = command.split(' ').collect_vec();
match parts.as_slice() {
[""] => {}
["fail"] => exit(1),
["dump", dest] => {
let dest_path = edit_script_path.parent().unwrap().join(dest);
fs::copy(&args.file, dest_path).unwrap();
}
["dump-path", dest] => {
let dest_path = edit_script_path.parent().unwrap().join(dest);
fs::write(&dest_path, args.file.to_str().unwrap())
.unwrap_or_else(|err| panic!("Failed to write file {dest_path:?}: {err}"));
}
["expect"] => {
let actual = String::from_utf8(fs::read(&args.file).unwrap()).unwrap();
if actual != payload {
eprintln!("fake-editor: Unexpected content.\n");
eprintln!("EXPECTED: <{payload}>\nRECEIVED: <{actual}>");
exit(1)
}
}
["expect-arg", index] => {
let index = index.parse::<usize>().unwrap();
let Some(actual) = args.other_args.get(index) else {
eprintln!("fake-editor: Missing argument at index {index}.\n");
eprintln!("EXPECTED: <{payload}>");
exit(1)
};
if actual != payload {
eprintln!("fake-editor: Unexpected argument at index {index}.\n");
eprintln!("EXPECTED: <{payload}>\nRECEIVED: <{actual}>");
exit(1)
}
}
["write"] => {
fs::write(&args.file, payload).unwrap_or_else(|_| {
panic!("Failed to write file {}", args.file.to_str().unwrap())
});
}
_ => {
eprintln!("fake-editor: unexpected command: {command}");
exit(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/testing/fake-echo.rs | cli/testing/fake-echo.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 _;
fn main() {
let mut args_os = std::env::args_os().skip(1).peekable();
while let Some(arg_os) = args_os.next() {
std::io::stdout()
.write_all(arg_os.as_encoded_bytes())
.unwrap_or_else(|e| {
panic!(
"Failed to write the argument \"{}\" to stdout: {e}",
arg_os.display()
)
});
if args_os.peek().is_some() {
write!(std::io::stdout(), " ").unwrap_or_else(|e| {
panic!("Failed to write the space separator to stdout: {e}");
});
}
}
writeln!(std::io::stdout())
.unwrap_or_else(|e| panic!("Failed to write the terminating newline to stdout: {e}"));
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
jj-vcs/jj | https://github.com/jj-vcs/jj/blob/10efcf35613c9c2076278f1721b5e6826e77c144/cli/testing/fake-diff-editor.rs | cli/testing/fake-diff-editor.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::collections::HashSet;
use std::env;
use std::path::Path;
use std::path::PathBuf;
use std::process::exit;
use clap::Parser;
use itertools::Itertools as _;
/// A fake diff-editor, useful for testing
#[derive(Parser, Debug)]
#[clap()]
struct Args {
/// Path to the "before" directory
before: PathBuf,
/// Path to the "after" directory
after: PathBuf,
/// Ignored argument
#[arg(long)]
_ignore: Vec<String>,
}
fn files_recursively(p: &Path) -> HashSet<String> {
let mut files = HashSet::new();
if !p.is_dir() {
files.insert(p.file_name().unwrap().to_str().unwrap().to_string());
} else {
for dir_entry in std::fs::read_dir(p).unwrap() {
let dir_entry = dir_entry.unwrap();
let base_name = dir_entry.file_name().to_str().unwrap().to_string();
if !dir_entry.path().is_dir() {
files.insert(base_name);
} else {
for sub_path in files_recursively(&dir_entry.path()) {
files.insert(format!("{base_name}/{sub_path}"));
}
}
}
}
files
}
fn main() {
let args: Args = Args::parse();
let edit_script_path = PathBuf::from(std::env::var_os("DIFF_EDIT_SCRIPT").unwrap());
let edit_script = String::from_utf8(std::fs::read(&edit_script_path).unwrap()).unwrap();
for instruction in edit_script.split('\0') {
let (command, payload) = instruction.split_once('\n').unwrap_or((instruction, ""));
let parts = command.split(' ').collect_vec();
match parts.as_slice() {
[""] => {}
["fail"] => exit(1),
["files-before", ..] => {
let expected = parts[1..].iter().copied().map(str::to_string).collect();
let actual = files_recursively(&args.before);
if actual != expected {
eprintln!(
"fake-diff-editor: unexpected files before. EXPECTED: {:?} ACTUAL: {:?}",
expected.iter().sorted().collect_vec(),
actual.iter().sorted().collect_vec(),
);
exit(1)
}
}
["files-after", ..] => {
let expected = parts[1..].iter().copied().map(str::to_string).collect();
let actual = files_recursively(&args.after);
if actual != expected {
eprintln!(
"fake-diff-editor: unexpected files after. EXPECTED: {:?} ACTUAL: {:?}",
expected.iter().sorted().collect_vec(),
actual.iter().sorted().collect_vec(),
);
exit(1)
}
}
["print", message] => {
println!("{message}");
}
["print-current-dir"] => {
println!("{}", env::current_dir().unwrap().display());
}
["print-files-before"] => {
for base_name in files_recursively(&args.before).iter().sorted() {
println!("{base_name}");
}
}
["print-files-after"] => {
for base_name in files_recursively(&args.after).iter().sorted() {
println!("{base_name}");
}
}
["rm", file] => {
std::fs::remove_file(args.after.join(file)).unwrap();
}
["reset", file] => {
if args.before.join(file).exists() {
std::fs::copy(args.before.join(file), args.after.join(file)).unwrap();
} else {
std::fs::remove_file(args.after.join(file)).unwrap();
}
}
["dump", file, dest] => {
let dest_path = edit_script_path.parent().unwrap().join(dest);
std::fs::copy(args.after.join(file), dest_path).unwrap();
}
["write", file] => {
std::fs::write(args.after.join(file), payload).unwrap();
}
_ => {
eprintln!("fake-diff-editor: unexpected command: {command}");
exit(1)
}
}
}
}
| rust | Apache-2.0 | 10efcf35613c9c2076278f1721b5e6826e77c144 | 2026-01-04T15:37:48.912814Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/build-templated-pages/src/main.rs | tools/build-templated-pages/src/main.rs | //! Tool used to build the templated pages of the Bevy website.
use bitflags::bitflags;
mod examples;
mod features;
bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Command: u32 {
const CHECK_MISSING = 0b00000001;
const UPDATE = 0b00000010;
}
}
bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Target: u32 {
const EXAMPLES = 0b00000001;
const FEATURES = 0b00000010;
}
}
fn main() {
let what_to_run = match std::env::args().nth(1).as_deref() {
Some("check-missing") => Command::CHECK_MISSING,
Some("update") => Command::UPDATE,
_ => Command::all(),
};
let target = match std::env::args().nth(2).as_deref() {
Some("examples") => Target::EXAMPLES,
Some("features") => Target::FEATURES,
_ => Target::all(),
};
if target.contains(Target::EXAMPLES) {
examples::check(what_to_run);
}
if target.contains(Target::FEATURES) {
features::check(what_to_run);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/build-templated-pages/src/features.rs | tools/build-templated-pages/src/features.rs | use core::cmp::Ordering;
use std::fs::File;
use serde::Serialize;
use tera::{Context, Tera};
use toml_edit::DocumentMut;
use crate::Command;
#[derive(Debug, Serialize, PartialEq, Eq, Clone)]
struct Feature {
name: String,
description: String,
is_profile: bool,
is_collection: bool,
}
impl Ord for Feature {
fn cmp(&self, other: &Self) -> Ordering {
self.name.cmp(&other.name)
}
}
impl PartialOrd for Feature {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn parse_features(panic_on_missing: bool) -> Vec<Feature> {
let manifest_file = std::fs::read_to_string("Cargo.toml").unwrap();
let manifest = manifest_file.parse::<DocumentMut>().unwrap();
let features = manifest["features"].as_table().unwrap();
features
.get_values()
.iter()
.flat_map(|(key, value)| {
let key = key[0];
if key == "default" {
let values = value.as_array().unwrap().iter().flat_map(|v| v.as_str()).collect::<Vec<_>>().join(", ");
let description = format!("The full default Bevy experience. This is a combination of the following profiles: {values}");
Some(Feature {
is_profile: true,
is_collection: false,
name: "default".to_string(),
description,
})
} else {
let name = key
.as_repr()
.unwrap()
.as_raw()
.as_str()
.unwrap()
.to_string();
if let Some(description) = key.leaf_decor().prefix() {
let description = description.as_str().unwrap().to_string();
if !description.starts_with("\n# ") || !description.ends_with('\n') {
panic!("Missing description for feature {name}");
}
let mut description = description
.strip_prefix("\n# ")
.unwrap()
.strip_suffix('\n')
.unwrap()
.to_string();
let is_profile = if let Some(trimmed) = description.strip_prefix("PROFILE: ") {
description = trimmed.to_string();
true
} else {
false
};
let is_collection =
if let Some(trimmed) = description.strip_prefix("COLLECTION: ") {
description = trimmed.to_string();
true
} else {
false
};
Some(Feature {
is_profile,
is_collection,
name,
description,
})
} else if panic_on_missing {
panic!("Missing description for feature {name}");
} else {
None
}
}
})
.collect()
}
pub(crate) fn check(what_to_run: Command) {
let features = parse_features(what_to_run.contains(Command::CHECK_MISSING));
let mut sorted_features = features.clone();
sorted_features.sort();
if what_to_run.contains(Command::UPDATE) {
let mut context = Context::new();
context.insert("features", &features);
context.insert("sorted_features", &sorted_features);
Tera::new("docs-template/*.md.tpl")
.expect("error parsing template")
.render_to(
"features.md.tpl",
&context,
File::create("docs/cargo_features.md").expect("error creating file"),
)
.expect("error rendering template");
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/build-templated-pages/src/examples.rs | tools/build-templated-pages/src/examples.rs | use core::cmp::Ordering;
use std::fs::File;
use hashbrown::HashMap;
use serde::Serialize;
use tera::{Context, Tera};
use toml_edit::{DocumentMut, Item};
use crate::Command;
#[derive(Debug, Serialize, PartialEq, Eq)]
struct Category {
description: Option<String>,
examples: Vec<Example>,
}
#[derive(Debug, Serialize, PartialEq, Eq)]
struct Example {
technical_name: String,
path: String,
name: String,
description: String,
category: String,
wasm: bool,
}
impl Ord for Example {
fn cmp(&self, other: &Self) -> Ordering {
(&self.category, &self.name).cmp(&(&other.category, &other.name))
}
}
impl PartialOrd for Example {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn parse_examples(panic_on_missing: bool) -> Vec<Example> {
let manifest_file = std::fs::read_to_string("Cargo.toml").unwrap();
let manifest = manifest_file.parse::<DocumentMut>().unwrap();
let metadatas = manifest
.get("package")
.unwrap()
.get("metadata")
.as_ref()
.unwrap()["example"]
.clone();
manifest["example"]
.as_array_of_tables()
.unwrap()
.iter()
.flat_map(|val| {
let technical_name = val.get("name").unwrap().as_str().unwrap().to_string();
if panic_on_missing && metadatas.get(&technical_name).is_none() {
panic!("Missing metadata for example {technical_name}");
}
if panic_on_missing && val.get("doc-scrape-examples").is_none() {
panic!("Example {technical_name} is missing doc-scrape-examples");
}
if metadatas
.get(&technical_name)
.and_then(|metadata| metadata.get("hidden"))
.and_then(Item::as_bool)
.unwrap_or(false)
{
return None;
}
metadatas.get(&technical_name).map(|metadata| Example {
technical_name,
path: val["path"].as_str().unwrap().to_string(),
name: metadata["name"].as_str().unwrap().to_string(),
description: metadata["description"].as_str().unwrap().to_string(),
category: metadata["category"].as_str().unwrap().to_string(),
wasm: metadata["wasm"].as_bool().unwrap(),
})
})
.collect()
}
fn parse_categories() -> HashMap<Box<str>, String> {
let manifest_file = std::fs::read_to_string("Cargo.toml").unwrap();
let manifest = manifest_file.parse::<DocumentMut>().unwrap();
manifest
.get("package")
.unwrap()
.get("metadata")
.as_ref()
.unwrap()["example_category"]
.clone()
.as_array_of_tables()
.unwrap()
.iter()
.map(|v| {
(
v.get("name").unwrap().as_str().unwrap().into(),
v.get("description").unwrap().as_str().unwrap().to_string(),
)
})
.collect()
}
pub(crate) fn check(what_to_run: Command) {
let examples = parse_examples(what_to_run.contains(Command::CHECK_MISSING));
if what_to_run.contains(Command::UPDATE) {
let categories = parse_categories();
let examples_by_category: HashMap<Box<str>, Category> = examples
.into_iter()
.fold(HashMap::<Box<str>, Vec<Example>>::new(), |mut v, ex| {
v.entry_ref(ex.category.as_str()).or_default().push(ex);
v
})
.into_iter()
.map(|(key, mut examples)| {
examples.sort();
let description = categories.get(&key).cloned();
(
key,
Category {
description,
examples,
},
)
})
.collect();
let mut context = Context::new();
context.insert("all_examples", &examples_by_category);
Tera::new("docs-template/*.md.tpl")
.expect("error parsing template")
.render_to(
"EXAMPLE_README.md.tpl",
&context,
File::create("examples/README.md").expect("error creating file"),
)
.expect("error rendering template");
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/ci.rs | tools/ci/src/ci.rs | use crate::{
args::Args,
commands,
prepare::{Prepare, PreparedCommand},
};
use argh::FromArgs;
/// The CI command line tool for Bevy.
#[derive(FromArgs)]
pub struct CI {
#[argh(subcommand)]
command: Option<Commands>,
/// continue running commands even if one fails
#[argh(switch)]
pub(crate) keep_going: bool,
/// parallelism of `cargo test`
#[argh(option)]
pub(crate) test_threads: Option<usize>,
/// number of build jobs
#[argh(option)]
pub(crate) build_jobs: Option<usize>,
}
impl CI {
/// Runs the specified commands or all commands if none are specified.
///
/// When run locally, results may differ from actual CI runs triggered by `.github/workflows/ci.yml`.
/// This is usually related to differing toolchains and configuration.
pub fn run(self) {
let sh = xshell::Shell::new().unwrap();
let prepared_commands = self.prepare(&sh);
let mut failures = vec![];
for command in prepared_commands {
// If the CI test is to be executed in a subdirectory, we move there before running the command.
// This will automatically move back to the original directory once dropped.
let _subdir_hook = command.subdir.map(|path| sh.push_dir(path));
// Execute each command, checking if it returned an error.
if command.command.envs(command.env_vars).run().is_err() {
let name = command.name;
let message = command.failure_message;
if self.keep_going {
// We use bullet points here because there can be more than one error.
failures.push(format!("- {name}: {message}"));
} else {
failures.push(format!("{name}: {message}"));
break;
}
}
}
// Log errors at the very end.
if !failures.is_empty() {
let failures = failures.join("\n");
panic!(
"One or more CI commands failed:\n\
{failures}"
);
}
}
fn prepare<'a>(&self, sh: &'a xshell::Shell) -> Vec<PreparedCommand<'a>> {
let args = self.into();
match &self.command {
Some(command) => command.prepare(sh, args),
None => {
// Note that we are running the subcommands directly rather than using any aliases
let mut cmds = vec![];
cmds.append(&mut commands::FormatCommand::default().prepare(sh, args));
cmds.append(&mut commands::ClippyCommand::default().prepare(sh, args));
cmds.append(&mut commands::TestCommand::default().prepare(sh, args));
cmds.append(&mut commands::TestCheckCommand::default().prepare(sh, args));
cmds.append(&mut commands::IntegrationTestCommand::default().prepare(sh, args));
cmds.append(
&mut commands::IntegrationTestCheckCommand::default().prepare(sh, args),
);
cmds.append(
&mut commands::IntegrationTestCleanCommand::default().prepare(sh, args),
);
cmds.append(&mut commands::DocCheckCommand::default().prepare(sh, args));
cmds.append(&mut commands::DocTestCommand::default().prepare(sh, args));
cmds.append(&mut commands::CompileCheckCommand::default().prepare(sh, args));
cmds.append(&mut commands::CompileFailCommand::default().prepare(sh, args));
cmds.append(&mut commands::BenchCheckCommand::default().prepare(sh, args));
cmds.append(&mut commands::ExampleCheckCommand::default().prepare(sh, args));
cmds
}
}
}
}
/// The subcommands that can be run by the CI script.
#[derive(FromArgs)]
#[argh(subcommand)]
enum Commands {
// Aliases (subcommands that run other subcommands)
Lints(commands::LintsCommand),
Doc(commands::DocCommand),
Compile(commands::CompileCommand),
// Actual subcommands
Format(commands::FormatCommand),
Clippy(commands::ClippyCommand),
Test(commands::TestCommand),
TestCheck(commands::TestCheckCommand),
IntegrationTest(commands::IntegrationTestCommand),
IntegrationTestCheck(commands::IntegrationTestCheckCommand),
IntegrationTestClean(commands::IntegrationTestCleanCommand),
DocCheck(commands::DocCheckCommand),
DocTest(commands::DocTestCommand),
CompileCheck(commands::CompileCheckCommand),
CompileFail(commands::CompileFailCommand),
BenchCheck(commands::BenchCheckCommand),
ExampleCheck(commands::ExampleCheckCommand),
}
impl Prepare for Commands {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
match self {
Commands::Lints(subcommand) => subcommand.prepare(sh, args),
Commands::Doc(subcommand) => subcommand.prepare(sh, args),
Commands::Compile(subcommand) => subcommand.prepare(sh, args),
Commands::Format(subcommand) => subcommand.prepare(sh, args),
Commands::Clippy(subcommand) => subcommand.prepare(sh, args),
Commands::Test(subcommand) => subcommand.prepare(sh, args),
Commands::TestCheck(subcommand) => subcommand.prepare(sh, args),
Commands::IntegrationTest(subcommand) => subcommand.prepare(sh, args),
Commands::IntegrationTestCheck(subcommand) => subcommand.prepare(sh, args),
Commands::IntegrationTestClean(subcommand) => subcommand.prepare(sh, args),
Commands::DocCheck(subcommand) => subcommand.prepare(sh, args),
Commands::DocTest(subcommand) => subcommand.prepare(sh, args),
Commands::CompileCheck(subcommand) => subcommand.prepare(sh, args),
Commands::CompileFail(subcommand) => subcommand.prepare(sh, args),
Commands::BenchCheck(subcommand) => subcommand.prepare(sh, args),
Commands::ExampleCheck(subcommand) => subcommand.prepare(sh, args),
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/args.rs | tools/ci/src/args.rs | use crate::CI;
/// Arguments that are available to CI commands.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Args {
keep_going: bool,
test_threads: Option<usize>,
build_jobs: Option<usize>,
}
impl Args {
#[inline(always)]
pub fn keep_going(&self) -> Option<&'static str> {
self.keep_going.then_some("--no-fail-fast")
}
#[inline(always)]
pub fn build_jobs(&self) -> Option<String> {
self.build_jobs.map(|jobs| format!("--jobs={jobs}"))
}
#[inline(always)]
pub fn test_threads(&self) -> Option<String> {
self.test_threads
.map(|threads| format!("--test-threads={threads}"))
}
}
impl From<&CI> for Args {
fn from(value: &CI) -> Self {
Args {
keep_going: value.keep_going,
test_threads: value.test_threads,
build_jobs: value.build_jobs,
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/main.rs | tools/ci/src/main.rs | //! CI script used for Bevy.
mod args;
mod ci;
mod commands;
mod prepare;
pub use self::{ci::*, prepare::*};
fn main() {
argh::from_env::<CI>().run();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/prepare.rs | tools/ci/src/prepare.rs | use crate::args::Args;
/// Trait for preparing a subcommand to be run.
pub trait Prepare {
/// A method that returns a list of [`PreparedCommand`]s to be run for a given shell and flags.
///
/// # Example
///
/// ```
/// # use crate::{args::Args, Prepare, PreparedCommand};
/// # use argh::FromArgs;
/// # use xshell::Shell;
/// #
/// #[derive(FromArgs)]
/// #[argh(subcommand, name = "check")]
/// struct CheckCommand {}
///
/// impl Prepare for CheckCommand {
/// fn prepare<'a>(&self, sh: &'a Shell, args: Args) -> Vec<PreparedCommand<'a>> {
/// vec![PreparedCommand::new::<Self>(
/// cmd!(sh, "cargo check --workspace"),
/// "Please fix linter errors",
/// )]
/// }
/// }
/// ```
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>>;
}
/// A command with associated metadata, created from a command that implements [`Prepare`].
#[derive(Debug)]
pub struct PreparedCommand<'a> {
/// The name of the command.
pub name: &'static str,
/// The command to execute
pub command: xshell::Cmd<'a>,
/// The message to display if the test command fails
pub failure_message: &'static str,
/// The subdirectory path to run the test command within
pub subdir: Option<&'static str>,
/// Environment variables that need to be set before the test runs
pub env_vars: Vec<(&'static str, &'static str)>,
}
impl<'a> PreparedCommand<'a> {
/// Creates a new [`PreparedCommand`] from a [`Cmd`] and a failure message.
///
/// The other fields of [`PreparedCommand`] are filled in with their default values.
///
/// For more information about creating a [`Cmd`], please see the [`cmd!`](xshell::cmd) macro.
///
/// [`Cmd`]: xshell::Cmd
pub fn new<T: argh::SubCommand>(
command: xshell::Cmd<'a>,
failure_message: &'static str,
) -> Self {
Self {
command,
name: T::COMMAND.name,
failure_message,
subdir: None,
env_vars: vec![],
}
}
/// A builder that overwrites the current sub-directory with a new value.
pub fn with_subdir(mut self, subdir: &'static str) -> Self {
self.subdir = Some(subdir);
self
}
/// A builder that adds a new environmental variable to the list.
pub fn with_env_var(mut self, key: &'static str, value: &'static str) -> Self {
self.env_vars.push((key, value));
self
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/doc_check.rs | tools/ci/src/commands/doc_check.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Checks that all docs compile.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "doc-check")]
pub struct DocCheckCommand {}
impl Prepare for DocCheckCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let jobs = args.build_jobs();
vec![PreparedCommand::new::<Self>(
cmd!(
sh,
"cargo doc --workspace --all-features --no-deps --document-private-items {jobs...} --keep-going"
),
"Please fix doc warnings in output above.",
)
.with_env_var("RUSTDOCFLAGS", "-D warnings")]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/bench_check.rs | tools/ci/src/commands/bench_check.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Checks that the benches compile.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "bench-check")]
pub struct BenchCheckCommand {}
impl Prepare for BenchCheckCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let jobs = args.build_jobs();
vec![PreparedCommand::new::<Self>(
cmd!(
sh,
"cargo check --benches {jobs...} --target-dir ../target --manifest-path ./benches/Cargo.toml"
),
"Failed to check the benches.",
)]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/test.rs | tools/ci/src/commands/test.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Runs all tests (except for doc tests).
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "test")]
pub struct TestCommand {}
impl Prepare for TestCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let no_fail_fast = args.keep_going();
let jobs = args.build_jobs();
let test_threads = args.test_threads();
let jobs_ref = &jobs;
let test_threads_ref = &test_threads;
vec![
PreparedCommand::new::<Self>(
cmd!(
sh,
"cargo test --workspace --lib --bins --tests --features bevy_ecs/track_location {no_fail_fast...} {jobs_ref...} -- {test_threads_ref...}"
),
"Please fix failing tests in output above.",
),
PreparedCommand::new::<Self>(
cmd!(
sh,
// `--benches` runs each benchmark once in order to verify that they behave
// correctly and do not panic.
"cargo test --workspace --benches {no_fail_fast...} {jobs...}"
),
"Please fix failing tests in output above.",
)
]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/compile_check.rs | tools/ci/src/commands/compile_check.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Checks that the project compiles.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "compile-check")]
pub struct CompileCheckCommand {}
impl Prepare for CompileCheckCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let jobs = args.build_jobs();
vec![PreparedCommand::new::<Self>(
cmd!(sh, "cargo check --workspace {jobs...}"),
"Please fix compiler errors in output above.",
)]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/integration_test_clean.rs | tools/ci/src/commands/integration_test_clean.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
use super::get_integration_tests;
/// Cleans the build artifacts for all integration tests.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "integration-test-clean")]
pub struct IntegrationTestCleanCommand {}
impl Prepare for IntegrationTestCleanCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, _args: Args) -> Vec<PreparedCommand<'a>> {
get_integration_tests(sh)
.into_iter()
.map(|path| {
PreparedCommand::new::<Self>(
cmd!(sh, "cargo clean --manifest-path {path}/Cargo.toml"),
"Failed to clean integration test.",
)
})
.collect()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/compile_fail.rs | tools/ci/src/commands/compile_fail.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Runs the compile-fail tests.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "compile-fail")]
pub struct CompileFailCommand {}
impl Prepare for CompileFailCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let no_fail_fast = args.keep_going();
let jobs = args.build_jobs();
let test_threads = args.test_threads();
let jobs_ref = jobs.as_ref();
let test_threads_ref = test_threads.as_ref();
let mut commands = vec![];
// Macro Compile Fail Tests
// Run tests (they do not get executed with the workspace tests)
// - See crates/bevy_macros_compile_fail_tests/README.md
commands.push(
PreparedCommand::new::<Self>(
cmd!(sh, "cargo test --target-dir ../../../target {no_fail_fast...} {jobs_ref...} -- {test_threads_ref...}"),
"Compiler errors of the macros compile fail tests seem to be different than expected! Check locally and compare rust versions.",
)
.with_subdir("crates/bevy_derive/compile_fail"),
);
// ECS Compile Fail Tests
// Run UI tests (they do not get executed with the workspace tests)
// - See crates/bevy_ecs_compile_fail_tests/README.md
commands.push(
PreparedCommand::new::<Self>(
cmd!(sh, "cargo test --target-dir ../../../target {no_fail_fast...} {jobs_ref...} -- {test_threads_ref...}"),
"Compiler errors of the ECS compile fail tests seem to be different than expected! Check locally and compare rust versions.",
)
.with_subdir("crates/bevy_ecs/compile_fail"),
);
// Reflect Compile Fail Tests
// Run tests (they do not get executed with the workspace tests)
// - See crates/bevy_reflect_compile_fail_tests/README.md
commands.push(
PreparedCommand::new::<Self>(
cmd!(sh, "cargo test --target-dir ../../../target {no_fail_fast...} {jobs...} -- {test_threads...}"),
"Compiler errors of the Reflect compile fail tests seem to be different than expected! Check locally and compare rust versions.",
)
.with_subdir("crates/bevy_reflect/compile_fail"),
);
commands
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/compile.rs | tools/ci/src/commands/compile.rs | use crate::{
args::Args,
commands::{
BenchCheckCommand, CompileCheckCommand, CompileFailCommand, ExampleCheckCommand,
IntegrationTestCheckCommand, TestCheckCommand,
},
Prepare, PreparedCommand,
};
use argh::FromArgs;
/// Alias for running the `compile-fail`, `bench-check`, `example-check`, `compile-check`, `test-check` and `test-integration-check` subcommands.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "compile")]
pub struct CompileCommand {}
impl Prepare for CompileCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let mut commands = vec![];
commands.append(&mut CompileFailCommand::default().prepare(sh, args));
commands.append(&mut BenchCheckCommand::default().prepare(sh, args));
commands.append(&mut ExampleCheckCommand::default().prepare(sh, args));
commands.append(&mut CompileCheckCommand::default().prepare(sh, args));
commands.append(&mut TestCheckCommand::default().prepare(sh, args));
commands.append(&mut IntegrationTestCheckCommand::default().prepare(sh, args));
commands
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/doc.rs | tools/ci/src/commands/doc.rs | use crate::{
args::Args,
commands::{DocCheckCommand, DocTestCommand},
Prepare, PreparedCommand,
};
use argh::FromArgs;
/// Alias for running the `doc-test` and `doc-check` subcommands.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "doc")]
pub struct DocCommand {}
impl Prepare for DocCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let mut commands = vec![];
commands.append(&mut DocTestCommand::default().prepare(sh, args));
commands.append(&mut DocCheckCommand::default().prepare(sh, args));
commands
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/integration_test.rs | tools/ci/src/commands/integration_test.rs | use crate::{args::Args, commands::get_integration_tests, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Runs all integration tests (except for doc tests).
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "integration-test")]
pub struct IntegrationTestCommand {}
impl Prepare for IntegrationTestCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let no_fail_fast = args.keep_going();
let jobs = args.build_jobs();
let test_threads = args.test_threads();
let jobs_ref = jobs.as_ref();
let test_threads_ref = test_threads.as_ref();
get_integration_tests(sh)
.into_iter()
.map(|path| {
PreparedCommand::new::<Self>(
cmd!(
sh,
"cargo test --manifest-path {path}/Cargo.toml --tests {no_fail_fast...} {jobs_ref...} -- {test_threads_ref...}"
),
"Please fix failing integration tests in output above.",
)
})
.collect()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/test_check.rs | tools/ci/src/commands/test_check.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Checks that all tests compile.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "test-check")]
pub struct TestCheckCommand {}
impl Prepare for TestCheckCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let jobs = args.build_jobs();
vec![PreparedCommand::new::<Self>(
cmd!(sh, "cargo check --workspace --tests {jobs...}"),
"Please fix compiler errors for tests in output above.",
)]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/mod.rs | tools/ci/src/commands/mod.rs | pub use bench_check::*;
pub use clippy::*;
pub use compile::*;
pub use compile_check::*;
pub use compile_fail::*;
pub use doc::*;
pub use doc_check::*;
pub use doc_test::*;
pub use example_check::*;
pub use format::*;
pub use integration_test::*;
pub use integration_test_check::*;
pub use integration_test_clean::*;
pub use lints::*;
pub use test::*;
pub use test_check::*;
mod bench_check;
mod clippy;
mod compile;
mod compile_check;
mod compile_fail;
mod doc;
mod doc_check;
mod doc_test;
mod example_check;
mod format;
mod integration_test;
mod integration_test_check;
mod integration_test_clean;
mod lints;
mod test;
mod test_check;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/format.rs | tools/ci/src/commands/format.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Check code formatting.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "format")]
pub struct FormatCommand {}
impl Prepare for FormatCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, _args: Args) -> Vec<PreparedCommand<'a>> {
vec![PreparedCommand::new::<Self>(
cmd!(sh, "cargo fmt --all -- --check"),
"Please run 'cargo fmt --all' to format your code.",
)]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/doc_test.rs | tools/ci/src/commands/doc_test.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Runs all doc tests.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "doc-test")]
pub struct DocTestCommand {}
impl Prepare for DocTestCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let no_fail_fast = args.keep_going();
let jobs = args.build_jobs();
let test_threads = args.test_threads();
vec![PreparedCommand::new::<Self>(
cmd!(
sh,
"cargo test --workspace --doc {no_fail_fast...} {jobs...} -- {test_threads...}"
),
"Please fix failing doc tests in output above.",
)]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/integration_test_check.rs | tools/ci/src/commands/integration_test_check.rs | use std::path::Path;
use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
pub fn get_integration_tests(sh: &xshell::Shell) -> Vec<String> {
let integration_test_paths = sh.read_dir(Path::new("./tests-integration")).unwrap();
// Filter out non-directories
integration_test_paths
.into_iter()
.filter(|path| path.is_dir())
.map(|path| path.to_string_lossy().to_string())
.collect()
}
/// Checks that all integration tests compile.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "integration-test-check")]
pub struct IntegrationTestCheckCommand {}
impl Prepare for IntegrationTestCheckCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let jobs = args.build_jobs();
let jobs_ref = jobs.as_ref();
get_integration_tests(sh)
.into_iter()
.map(|path| {
PreparedCommand::new::<Self>(
cmd!(
sh,
"cargo check --manifest-path {path}/Cargo.toml --tests {jobs_ref...}"
),
"Please fix compiler errors for tests in output above.",
)
})
.collect()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/lints.rs | tools/ci/src/commands/lints.rs | use crate::{
args::Args,
commands::{ClippyCommand, FormatCommand},
Prepare, PreparedCommand,
};
use argh::FromArgs;
/// Alias for running the `format` and `clippy` subcommands.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "lints")]
pub struct LintsCommand {}
impl Prepare for LintsCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let mut commands = vec![];
commands.append(&mut FormatCommand::default().prepare(sh, args));
commands.append(&mut ClippyCommand::default().prepare(sh, args));
commands
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/clippy.rs | tools/ci/src/commands/clippy.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Check for clippy warnings and errors.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "clippy")]
pub struct ClippyCommand {}
impl Prepare for ClippyCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let jobs = args.build_jobs();
vec![PreparedCommand::new::<Self>(
cmd!(
sh,
"cargo clippy --workspace --all-targets --all-features {jobs...} -- -Dwarnings"
),
"Please fix clippy errors in output above.",
)]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/ci/src/commands/example_check.rs | tools/ci/src/commands/example_check.rs | use crate::{args::Args, Prepare, PreparedCommand};
use argh::FromArgs;
use xshell::cmd;
/// Checks that the examples compile.
#[derive(FromArgs, Default)]
#[argh(subcommand, name = "example-check")]
pub struct ExampleCheckCommand {}
impl Prepare for ExampleCheckCommand {
fn prepare<'a>(&self, sh: &'a xshell::Shell, args: Args) -> Vec<PreparedCommand<'a>> {
let jobs = args.build_jobs();
vec![PreparedCommand::new::<Self>(
cmd!(sh, "cargo check --workspace --examples {jobs...}"),
"Please fix compiler errors for examples in output above.",
)]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/example-showcase/src/main.rs | tools/example-showcase/src/main.rs | //! Tool to run all examples or generate a showcase page for the Bevy website.
#![expect(clippy::print_stdout, reason = "Allowed in tools.")]
use core::{
fmt::Display,
hash::{Hash, Hasher},
time::Duration,
};
use std::{
collections::{hash_map::DefaultHasher, HashMap},
fs::{self, File},
io::Write,
path::{Path, PathBuf},
process::exit,
thread,
time::Instant,
};
use clap::{error::ErrorKind, CommandFactory, Parser, ValueEnum};
use pbr::ProgressBar;
use regex::Regex;
use toml_edit::{DocumentMut, Item};
use xshell::{cmd, Shell};
#[derive(Parser, Debug)]
struct Args {
#[arg(long, default_value = "release")]
/// Compilation profile to use
profile: String,
#[command(subcommand)]
action: Action,
#[arg(long)]
/// Pagination control - page number. To use with --per-page
page: Option<usize>,
#[arg(long)]
/// Pagination control - number of examples per page. To use with --page
per_page: Option<usize>,
}
#[derive(clap::Subcommand, Debug)]
enum Action {
/// Run all the examples
Run {
#[arg(long)]
/// WGPU backend to use
wgpu_backend: Option<String>,
#[arg(long, default_value = "250")]
/// Which frame to automatically stop the example at.
///
/// This defaults to frame 250. Set it to 0 to not stop the example automatically.
stop_frame: u32,
#[arg(long, default_value = "false")]
/// Automatically ends after taking a screenshot
///
/// Only works if `screenshot-frame` is set to non-0, and overrides `stop-frame`.
auto_stop_frame: bool,
#[arg(long)]
/// Which frame to take a screenshot at. Set to 0 for no screenshot.
screenshot_frame: u32,
#[arg(long, default_value = "0.05")]
/// Fixed duration of a frame, in seconds. Only used when taking a screenshot, default to 0.05
fixed_frame_time: f32,
#[arg(long)]
/// Running in CI (some adaptation to the code)
in_ci: bool,
#[arg(long)]
/// Do not run stress test examples
ignore_stress_tests: bool,
#[arg(long)]
/// Report execution details in files
report_details: bool,
#[arg(long)]
/// Show the logs during execution
show_logs: bool,
#[arg(long)]
/// File containing the list of examples to run, incompatible with pagination
example_list: Option<String>,
#[arg(long)]
/// Only run examples that don't need extra features
only_default_features: bool,
},
/// Build the markdown files for the website
BuildWebsiteList {
#[arg(long)]
/// Path to the folder where the content should be created
content_folder: String,
#[arg(value_enum, long, default_value_t = WebApi::Webgpu)]
/// Which API to use for rendering
api: WebApi,
},
/// Build the examples in wasm
BuildWasmExamples {
#[arg(long)]
/// Path to the folder where the content should be created
content_folder: String,
#[arg(long)]
/// Enable hacks for Bevy website integration
website_hacks: bool,
#[arg(long)]
/// Optimize the wasm file for size with wasm-opt
optimize_size: bool,
#[arg(value_enum, long)]
/// Which API to use for rendering
api: WebApi,
},
}
#[derive(Debug, Copy, Clone, ValueEnum)]
enum WebApi {
Webgl2,
Webgpu,
}
impl Display for WebApi {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
WebApi::Webgl2 => write!(f, "webgl2"),
WebApi::Webgpu => write!(f, "webgpu"),
}
}
}
fn main() {
let cli = Args::parse();
if cli.page.is_none() != cli.per_page.is_none() {
let mut cmd = Args::command();
cmd.error(
ErrorKind::MissingRequiredArgument,
"page and per-page must be used together",
)
.exit();
}
let profile = cli.profile;
match cli.action {
Action::Run {
wgpu_backend,
stop_frame,
auto_stop_frame,
screenshot_frame,
fixed_frame_time,
in_ci,
ignore_stress_tests,
report_details,
show_logs,
example_list,
only_default_features,
} => {
if example_list.is_some() && cli.page.is_some() {
let mut cmd = Args::command();
cmd.error(
ErrorKind::ArgumentConflict,
"example-list can't be used with pagination",
)
.exit();
}
let example_filter = example_list
.as_ref()
.map(|path| {
let file = fs::read_to_string(path).unwrap();
file.lines().map(ToString::to_string).collect::<Vec<_>>()
})
.unwrap_or_default();
let mut examples_to_run = parse_examples();
let mut failed_examples = vec![];
let mut successful_examples = vec![];
let mut no_screenshot_examples = vec![];
let mut extra_parameters = vec![];
match (stop_frame, screenshot_frame, auto_stop_frame) {
// When the example does not automatically stop nor take a screenshot.
(0, 0, _) => (),
// When the example automatically stops at an automatic frame.
(0, _, true) => {
let mut file = File::create("example_showcase_config.ron").unwrap();
file.write_all(
format!("(setup: (fixed_frame_time: Some({fixed_frame_time})), events: [({screenshot_frame}, ScreenshotAndExit)])").as_bytes(),
)
.unwrap();
extra_parameters.push("--features");
extra_parameters.push("bevy_ci_testing");
}
// When the example does not automatically stop.
(0, _, false) => {
let mut file = File::create("example_showcase_config.ron").unwrap();
file.write_all(
format!("(setup: (fixed_frame_time: Some({fixed_frame_time})), events: [({screenshot_frame}, Screenshot)])").as_bytes(),
)
.unwrap();
extra_parameters.push("--features");
extra_parameters.push("bevy_ci_testing");
}
// When the example does not take a screenshot.
(_, 0, _) => {
let mut file = File::create("example_showcase_config.ron").unwrap();
file.write_all(format!("(events: [({stop_frame}, AppExit)])").as_bytes())
.unwrap();
extra_parameters.push("--features");
extra_parameters.push("bevy_ci_testing");
}
// When the example both automatically stops at an automatic frame and takes a screenshot.
(_, _, true) => {
let mut file = File::create("example_showcase_config.ron").unwrap();
file.write_all(
format!("(setup: (fixed_frame_time: Some({fixed_frame_time})), events: [({screenshot_frame}, ScreenshotAndExit)])").as_bytes(),
)
.unwrap();
extra_parameters.push("--features");
extra_parameters.push("bevy_ci_testing");
}
// When the example both automatically stops and takes a screenshot.
(_, _, false) => {
let mut file = File::create("example_showcase_config.ron").unwrap();
file.write_all(
format!("(setup: (fixed_frame_time: Some({fixed_frame_time})), events: [({screenshot_frame}, Screenshot), ({stop_frame}, AppExit)])").as_bytes(),
)
.unwrap();
extra_parameters.push("--features");
extra_parameters.push("bevy_ci_testing");
}
}
if in_ci {
// Removing desktop mode as is slows down too much in CI
let sh = Shell::new().unwrap();
cmd!(
sh,
"git apply --ignore-whitespace tools/example-showcase/remove-desktop-app-mode.patch"
)
.run()
.unwrap();
// Don't use automatic position as it's "random" on Windows and breaks screenshot comparison
// using the cursor position
let sh = Shell::new().unwrap();
cmd!(
sh,
"git apply --ignore-whitespace tools/example-showcase/fixed-window-position.patch"
)
.run()
.unwrap();
// Setting lights ClusterConfig to have less clusters by default
// This is needed as the default config is too much for the CI runner
cmd!(
sh,
"git apply --ignore-whitespace tools/example-showcase/reduce-light-cluster-config.patch"
)
.run()
.unwrap();
// Sending extra WindowResize events. They are not sent on CI with xvfb x11 server
// This is needed for example split_screen that uses the window size to set the panels
cmd!(
sh,
"git apply --ignore-whitespace tools/example-showcase/extra-window-resized-events.patch"
)
.run()
.unwrap();
// Don't try to get an audio output stream in CI as there isn't one
// On macOS m1 runner in GitHub Actions, getting one timeouts after 15 minutes
cmd!(
sh,
"git apply --ignore-whitespace tools/example-showcase/disable-audio.patch"
)
.run()
.unwrap();
// Sort the examples so that they are not run by category
examples_to_run.sort_by_key(|example| {
let mut hasher = DefaultHasher::new();
example.hash(&mut hasher);
hasher.finish()
});
}
let work_to_do = || {
examples_to_run
.iter()
.filter(|example| example.category != "Stress Tests" || !ignore_stress_tests)
.filter(|example| example.example_type == ExampleType::Bin)
.filter(|example| {
example_list.is_none() || example_filter.contains(&example.technical_name)
})
.filter(|example| {
!only_default_features || example.required_features.is_empty()
})
.skip(cli.page.unwrap_or(0) * cli.per_page.unwrap_or(0))
.take(cli.per_page.unwrap_or(usize::MAX))
};
let mut pb = ProgressBar::new(work_to_do().count() as u64);
let reports_path = "example-showcase-reports";
if report_details {
fs::create_dir(reports_path)
.expect("Failed to create example-showcase-reports directory");
}
for to_run in work_to_do() {
let sh = Shell::new().unwrap();
let example = &to_run.technical_name;
let required_features = if to_run.required_features.is_empty() {
vec![]
} else {
vec!["--features".to_string(), to_run.required_features.join(",")]
};
let local_extra_parameters = extra_parameters
.iter()
.map(ToString::to_string)
.chain(required_features.iter().cloned())
.collect::<Vec<_>>();
let _ = cmd!(
sh,
"cargo build --profile {profile} --example {example} {local_extra_parameters...}"
).run();
let local_extra_parameters = extra_parameters
.iter()
.map(ToString::to_string)
.chain(required_features.iter().cloned())
.collect::<Vec<_>>();
let mut cmd = cmd!(
sh,
"cargo run --profile {profile} --example {example} {local_extra_parameters...}"
);
if let Some(backend) = wgpu_backend.as_ref() {
cmd = cmd.env("WGPU_BACKEND", backend);
}
if stop_frame > 0 || screenshot_frame > 0 {
cmd = cmd.env("CI_TESTING_CONFIG", "example_showcase_config.ron");
}
let before = Instant::now();
if report_details || show_logs {
cmd = cmd.ignore_status();
}
let result = cmd.output();
let duration = before.elapsed();
if (!report_details && result.is_ok())
|| (report_details && result.as_ref().unwrap().status.success())
{
if screenshot_frame > 0 {
let _ = fs::create_dir_all(Path::new("screenshots").join(&to_run.category));
let renamed_screenshot = fs::rename(
format!("screenshot-{screenshot_frame}.png"),
Path::new("screenshots")
.join(&to_run.category)
.join(format!("{}.png", to_run.technical_name)),
);
if let Err(err) = renamed_screenshot {
println!("Failed to rename screenshot: {err}");
no_screenshot_examples.push((to_run, duration));
} else {
successful_examples.push((to_run, duration));
}
} else {
successful_examples.push((to_run, duration));
}
} else {
failed_examples.push((to_run, duration));
}
if report_details || show_logs {
let result = result.unwrap();
let stdout = String::from_utf8_lossy(&result.stdout);
let stderr = String::from_utf8_lossy(&result.stderr);
if show_logs {
println!("{stdout}");
println!("{stderr}");
}
if report_details {
let mut file =
File::create(format!("{reports_path}/{example}.log")).unwrap();
file.write_all(b"==== stdout ====\n").unwrap();
file.write_all(stdout.as_bytes()).unwrap();
file.write_all(b"\n==== stderr ====\n").unwrap();
file.write_all(stderr.as_bytes()).unwrap();
}
}
thread::sleep(Duration::from_secs(1));
pb.inc();
}
pb.finish_print("done");
if report_details {
let _ = fs::write(
format!("{reports_path}/successes"),
successful_examples
.iter()
.map(|(example, duration)| {
format!(
"{}/{} - {}",
example.category,
example.technical_name,
duration.as_secs_f32()
)
})
.collect::<Vec<_>>()
.join("\n"),
);
let _ = fs::write(
format!("{reports_path}/failures"),
failed_examples
.iter()
.map(|(example, duration)| {
format!(
"{}/{} - {}",
example.category,
example.technical_name,
duration.as_secs_f32()
)
})
.collect::<Vec<_>>()
.join("\n"),
);
if screenshot_frame > 0 {
let _ = fs::write(
format!("{reports_path}/no_screenshots"),
no_screenshot_examples
.iter()
.map(|(example, duration)| {
format!(
"{}/{} - {}",
example.category,
example.technical_name,
duration.as_secs_f32()
)
})
.collect::<Vec<_>>()
.join("\n"),
);
}
}
println!(
"total: {} / passed: {}, failed: {}, no screenshot: {}",
work_to_do().count(),
successful_examples.len(),
failed_examples.len(),
no_screenshot_examples.len()
);
if failed_examples.is_empty() {
println!("All examples passed!");
} else {
println!("Failed examples:");
for (example, _) in failed_examples {
println!(
" {} / {} ({})",
example.category, example.name, example.technical_name
);
}
exit(1);
}
}
Action::BuildWebsiteList {
content_folder,
api,
} => {
let mut examples_to_run = parse_examples();
examples_to_run.sort_by_key(|e| format!("{}-{}", e.category, e.name));
let root_path = Path::new(&content_folder);
let _ = fs::create_dir_all(root_path);
let mut index = File::create(root_path.join("_index.md")).unwrap();
if matches!(api, WebApi::Webgpu) {
index
.write_all(
"+++
title = \"Bevy Examples in WebGPU\"
template = \"examples-webgpu.html\"
sort_by = \"weight\"
[extra]
header_message = \"Examples (WebGPU)\"
+++"
.as_bytes(),
)
.unwrap();
} else {
index
.write_all(
"+++
title = \"Bevy Examples in WebGL2\"
template = \"examples.html\"
sort_by = \"weight\"
[extra]
header_message = \"Examples (WebGL2)\"
+++"
.as_bytes(),
)
.unwrap();
}
let mut categories = HashMap::new();
for to_show in examples_to_run {
if to_show.example_type != ExampleType::Bin {
continue;
}
if !to_show.wasm {
continue;
}
// This beautifies the category name
// to make it a good looking URL
// rather than having weird whitespace
// and other characters that don't
// work well in a URL path.
let beautified_category = to_show
.category
.replace(['(', ')'], "")
.replace(' ', "-")
.to_lowercase();
let category_path = root_path.join(&beautified_category);
if !categories.contains_key(&to_show.category) {
let _ = fs::create_dir_all(&category_path);
let mut category_index = File::create(category_path.join("_index.md")).unwrap();
category_index
.write_all(
format!(
"+++
title = \"{}\"
sort_by = \"weight\"
weight = {}
+++",
to_show.category,
categories.len()
)
.as_bytes(),
)
.unwrap();
categories.insert(to_show.category.clone(), 0);
}
let example_path = category_path.join(to_show.technical_name.replace('_', "-"));
let _ = fs::create_dir_all(&example_path);
let code_path = example_path.join(Path::new(&to_show.path).file_name().unwrap());
let code = fs::read_to_string(&to_show.path).unwrap();
let (docblock, code) = split_docblock_and_code(&code);
let _ = fs::write(&code_path, code);
let mut example_index = File::create(example_path.join("index.md")).unwrap();
example_index
.write_all(
format!(
"+++
title = \"{}\"
template = \"example{}.html\"
weight = {}
description = \"{}\"
# This creates redirection pages
# for the old URLs which used
# uppercase letters and whitespace.
aliases = [\"/examples{}/{}/{}\"]
[extra]
technical_name = \"{}\"
link = \"/examples{}/{}/{}/\"
image = \"../static/screenshots/{}/{}.png\"
code_path = \"content/examples{}/{}\"
shader_code_paths = {:?}
github_code_path = \"{}\"
header_message = \"Examples ({})\"
required_features = {:?}
+++
{}
",
to_show.name,
match api {
WebApi::Webgpu => "-webgpu",
WebApi::Webgl2 => "",
},
categories.get(&to_show.category).unwrap(),
to_show.description.replace('"', "'"),
match api {
WebApi::Webgpu => "-webgpu",
WebApi::Webgl2 => "",
},
to_show.category,
&to_show.technical_name.replace('_', "-"),
&to_show.technical_name.replace('_', "-"),
match api {
WebApi::Webgpu => "-webgpu",
WebApi::Webgl2 => "",
},
&beautified_category,
&to_show.technical_name.replace('_', "-"),
&to_show.category,
&to_show.technical_name,
match api {
WebApi::Webgpu => "-webgpu",
WebApi::Webgl2 => "",
},
code_path
.components()
.skip(1)
.collect::<PathBuf>()
.display(),
to_show.shader_paths,
&to_show.path,
match api {
WebApi::Webgpu => "WebGPU",
WebApi::Webgl2 => "WebGL2",
},
to_show.required_features,
docblock,
)
.as_bytes(),
)
.unwrap();
}
}
Action::BuildWasmExamples {
content_folder,
website_hacks,
optimize_size,
api,
} => {
let api = format!("{api}");
let examples_to_build = parse_examples();
let root_path = Path::new(&content_folder);
let _ = fs::create_dir_all(root_path);
if website_hacks {
// setting up the headers file for cloudflare for the correct Content-Type
let mut headers = File::create(root_path.join("_headers")).unwrap();
headers
.write_all(
"/*/wasm_example_bg.wasm
Content-Type: application/wasm
"
.as_bytes(),
)
.unwrap();
let sh = Shell::new().unwrap();
// setting a canvas by default to help with integration
cmd!(
sh,
"git apply --ignore-whitespace tools/example-showcase/window-settings-wasm.patch"
)
.run()
.unwrap();
// setting the asset folder root to the root url of this domain
cmd!(
sh,
"git apply --ignore-whitespace tools/example-showcase/asset-source-website.patch"
)
.run()
.unwrap();
}
let work_to_do = || {
examples_to_build
.iter()
.filter(|to_build| to_build.wasm)
.filter(|to_build| to_build.example_type == ExampleType::Bin)
.skip(cli.page.unwrap_or(0) * cli.per_page.unwrap_or(0))
.take(cli.per_page.unwrap_or(usize::MAX))
};
let mut pb = ProgressBar::new(work_to_do().count() as u64);
for to_build in work_to_do() {
let sh = Shell::new().unwrap();
let example = &to_build.technical_name;
let required_features = if to_build.required_features.is_empty() {
vec![]
} else {
vec![
"--features".to_string(),
to_build.required_features.join(","),
]
};
if optimize_size {
cmd!(
sh,
"cargo run -p build-wasm-example -- --api {api} {example} --optimize-size {required_features...}"
)
.run()
.unwrap();
} else {
cmd!(
sh,
"cargo run -p build-wasm-example -- --api {api} {example} {required_features...}"
)
.run()
.unwrap();
}
let category_path = root_path.join(&to_build.category);
let _ = fs::create_dir_all(&category_path);
let example_path = category_path.join(to_build.technical_name.replace('_', "-"));
let _ = fs::create_dir_all(&example_path);
if website_hacks {
// set up the loader bar for asset loading
cmd!(sh, "sed -i.bak -e 's/getObject(arg0).fetch(/window.bevyLoadingBarFetch(/' -e 's/input = fetch(/input = window.bevyLoadingBarFetch(/' examples/wasm/target/wasm_example.js").run().unwrap();
}
let _ = fs::rename(
Path::new("examples/wasm/target/wasm_example.js"),
example_path.join("wasm_example.js"),
);
if optimize_size {
let _ = fs::rename(
Path::new("examples/wasm/target/wasm_example_bg.wasm.optimized"),
example_path.join("wasm_example_bg.wasm"),
);
} else {
let _ = fs::rename(
Path::new("examples/wasm/target/wasm_example_bg.wasm"),
example_path.join("wasm_example_bg.wasm"),
);
}
pb.inc();
}
pb.finish_print("done");
}
}
}
fn split_docblock_and_code(code: &str) -> (String, &str) {
let mut docblock_lines = Vec::new();
let mut code_byte_start = 0;
for line in code.lines() {
if line.starts_with("//!") {
docblock_lines.push(line.trim_start_matches("//!").trim());
} else if !line.trim().is_empty() {
break;
}
code_byte_start += line.len() + 1;
}
(docblock_lines.join("\n"), &code[code_byte_start..])
}
fn parse_examples() -> Vec<Example> {
let manifest_file = fs::read_to_string("Cargo.toml").unwrap();
let manifest = manifest_file.parse::<DocumentMut>().unwrap();
let metadatas = manifest
.get("package")
.unwrap()
.get("metadata")
.as_ref()
.unwrap()["example"]
.clone();
manifest["example"]
.as_array_of_tables()
.unwrap()
.iter()
.flat_map(|val| {
let technical_name = val.get("name").unwrap().as_str().unwrap().to_string();
let source_code = fs::read_to_string(val["path"].as_str().unwrap()).unwrap();
let shader_regex = Regex::new(r"shaders\/\w+\.(wgsl|frag|vert|wesl)").unwrap();
// Find all instances of references to shader files, and keep them in an ordered and deduped vec.
let mut shader_paths = vec![];
for path in shader_regex
.find_iter(&source_code)
.map(|matches| matches.as_str().to_owned())
{
if !shader_paths.contains(&path) {
shader_paths.push(path);
}
}
if metadatas
.get(&technical_name)
.and_then(|metadata| metadata.get("hidden"))
.and_then(Item::as_bool)
.and_then(|hidden| hidden.then_some(()))
.is_some()
{
return None;
}
metadatas.get(&technical_name).map(|metadata| Example {
technical_name,
path: val["path"].as_str().unwrap().to_string(),
shader_paths,
name: metadata["name"].as_str().unwrap().to_string(),
description: metadata["description"].as_str().unwrap().to_string(),
category: metadata["category"].as_str().unwrap().to_string(),
wasm: metadata["wasm"].as_bool().unwrap(),
required_features: val
.get("required-features")
.map(|rf| {
rf.as_array()
.unwrap()
.into_iter()
.map(|v| v.as_str().unwrap().to_string())
.collect()
})
.unwrap_or_default(),
example_type: match val.get("crate-type") {
Some(crate_type) => {
match crate_type
.as_array()
.unwrap()
.get(0)
.unwrap()
.as_str()
.unwrap()
{
"lib" => ExampleType::Lib,
_ => ExampleType::Bin,
}
}
None => ExampleType::Bin,
},
})
})
.collect()
}
/// Data for this struct comes from both the entry for an example in the Cargo.toml file, and its associated metadata.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
struct Example {
// From the example entry
/// Name of the example, used to start it from the cargo CLI with `--example`
technical_name: String,
/// Path to the example file
path: String,
/// Path to the associated wgsl file if it exists
shader_paths: Vec<String>,
/// List of non default required features
required_features: Vec<String>,
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/export-content/src/app.rs | tools/export-content/src/app.rs | #![expect(
unused_assignments,
reason = "Warnings from inside miette due to a rustc bug: https://github.com/rust-lang/rust/issues/147648"
)]
use std::{env, fs, io::Write, path::PathBuf};
use miette::{diagnostic, Context, Diagnostic, IntoDiagnostic, NamedSource, Result};
use ratatui::{
crossterm::event::{self, Event, KeyCode, KeyModifiers},
prelude::*,
widgets::*,
};
use regex::Regex;
use serde::Deserialize;
use thiserror::Error;
enum Mode {
ReleaseNotes,
MigrationGuides,
}
pub struct App {
content_dir: PathBuf,
release_notes: Vec<Entry>,
release_notes_state: ListState,
migration_guides: Vec<Entry>,
migration_guide_state: ListState,
text_entry: Option<String>,
mode: Mode,
exit: bool,
}
pub struct Content {
content_dir: PathBuf,
migration_guides: Vec<Entry>,
release_notes: Vec<Entry>,
}
impl Content {
pub fn load() -> Result<Self> {
let exe_dir = env::current_exe()
.into_diagnostic()
.wrap_err("failed to determine path to binary")?;
let content_dir = exe_dir
.ancestors()
.nth(3)
.ok_or(diagnostic!("failed to determine path to repo root"))?
.join("release-content");
let release_notes_dir = content_dir.join("release-notes");
let release_notes = load_content(release_notes_dir, "release note")?;
let migration_guides_dir = content_dir.join("migration-guides");
let migration_guides = load_content(migration_guides_dir, "migration guide")?;
Ok(Content {
content_dir,
migration_guides,
release_notes,
})
}
}
impl App {
pub fn new() -> Result<App> {
let Content {
content_dir,
release_notes,
migration_guides,
} = Content::load()?;
Ok(App {
content_dir,
release_notes,
release_notes_state: ListState::default().with_selected(Some(0)),
migration_guides,
migration_guide_state: ListState::default().with_selected(Some(0)),
text_entry: None,
mode: Mode::ReleaseNotes,
exit: false,
})
}
pub fn run<B: Backend>(mut self, terminal: &mut Terminal<B>) -> Result<()> {
while !self.exit {
terminal
.draw(|frame| self.render(frame))
.into_diagnostic()?;
let (mode_state, mode_entries) = match self.mode {
Mode::ReleaseNotes => (&mut self.release_notes_state, &mut self.release_notes),
Mode::MigrationGuides => {
(&mut self.migration_guide_state, &mut self.migration_guides)
}
};
if let Event::Key(key) = event::read().into_diagnostic()? {
// If text entry is enabled, capture all input events
if let Some(text) = &mut self.text_entry {
match key.code {
KeyCode::Esc => self.text_entry = None,
KeyCode::Backspace => {
text.pop();
}
KeyCode::Enter => {
if !text.is_empty()
&& let Some(index) = mode_state.selected()
{
mode_entries.insert(
index,
Entry::Section {
title: text.clone(),
},
);
}
self.text_entry = None;
}
KeyCode::Char(c) => text.push(c),
_ => {}
}
continue;
}
match key.code {
KeyCode::Esc => self.exit = true,
KeyCode::Tab => match self.mode {
Mode::ReleaseNotes => self.mode = Mode::MigrationGuides,
Mode::MigrationGuides => self.mode = Mode::ReleaseNotes,
},
KeyCode::Down => {
if key.modifiers.contains(KeyModifiers::SHIFT)
&& let Some(index) = mode_state.selected()
&& index < mode_entries.len() - 1
{
mode_entries.swap(index, index + 1);
}
mode_state.select_next();
}
KeyCode::Up => {
if key.modifiers.contains(KeyModifiers::SHIFT)
&& let Some(index) = mode_state.selected()
&& index > 0
{
mode_entries.swap(index, index - 1);
}
mode_state.select_previous();
}
KeyCode::Char('+') => {
self.text_entry = Some(String::new());
}
KeyCode::Char('d') => {
if let Some(index) = mode_state.selected()
&& let Entry::Section { .. } = mode_entries[index]
{
mode_entries.remove(index);
}
}
_ => {}
}
}
}
self.write_output()
}
pub fn render(&mut self, frame: &mut Frame) {
use Constraint::*;
let page_area = frame.area().inner(Margin::new(1, 1));
let [header_area, instructions_area, _, block_area, _, typing_area] = Layout::vertical([
Length(2), // header
Length(2), // instructions
Length(1), // gap
Fill(1), // blocks
Length(1), // gap
Length(2), // text input
])
.areas(page_area);
frame.render_widget(self.header(), header_area);
frame.render_widget(self.instructions(), instructions_area);
let (title, mode_state, mode_entries) = match self.mode {
Mode::ReleaseNotes => (
"Release Notes",
&mut self.release_notes_state,
&self.release_notes,
),
Mode::MigrationGuides => (
"Migration Guides",
&mut self.migration_guide_state,
&self.migration_guides,
),
};
let items = mode_entries.iter().map(|e| e.as_list_entry());
let list = List::new(items)
.block(Block::new().title(title).padding(Padding::uniform(1)))
.highlight_symbol(">>")
.highlight_style(Color::Green);
frame.render_stateful_widget(list, block_area, mode_state);
if let Some(text) = &self.text_entry {
let text_entry = Paragraph::new(format!("Section Title: {}", text)).fg(Color::Blue);
frame.render_widget(text_entry, typing_area);
}
}
fn header(&self) -> impl Widget {
let text = "Content Exporter Tool";
text.bold().underlined().into_centered_line()
}
fn instructions(&self) -> impl Widget {
let text =
"▲ ▼ : navigate shift + ▲ ▼ : re-order + : insert section d : delete section tab : change focus esc : save and quit";
Paragraph::new(text)
.fg(Color::Magenta)
.centered()
.wrap(Wrap { trim: false })
}
fn write_output(self) -> Result<()> {
// Write release notes
let mut file =
fs::File::create(self.content_dir.join("merged_release_notes.md")).into_diagnostic()?;
for entry in self.release_notes {
match entry {
Entry::Section { title } => write!(file, "# {title}\n\n").into_diagnostic()?,
Entry::File { metadata, content } => {
let title = metadata.title;
let authors = metadata
.authors
.iter()
.flatten()
.map(|a| format!("\"{a}\""))
.collect::<Vec<_>>()
.join(", ");
let pull_requests = metadata
.pull_requests
.iter()
.map(|n| format!("{}", n))
.collect::<Vec<_>>()
.join(", ");
write!(
file,
"## {title}\n\n{{{{ heading_metadata(authors=[{authors}] prs=[{pull_requests}]) }}}}\n\n{content}\n"
)
.into_diagnostic()?;
}
}
}
// Write migration guide
let mut file = fs::File::create(self.content_dir.join("merged_migration_guides.md"))
.into_diagnostic()?;
for entry in self.migration_guides {
match entry {
Entry::Section { title } => write!(file, "## {title}\n\n").into_diagnostic()?,
Entry::File { metadata, content } => {
let title = metadata.title;
let pull_requests = metadata
.pull_requests
.iter()
.map(|n| format!("{}", n))
.collect::<Vec<_>>()
.join(", ");
write!(
file,
"### {title}\n\n{{{{ heading_metadata(prs=[{pull_requests}]) }}}}\n\n{content}\n"
)
.into_diagnostic()?;
}
}
}
Ok(())
}
}
#[derive(Deserialize, Debug)]
struct Metadata {
title: String,
authors: Option<Vec<String>>,
pull_requests: Vec<u32>,
}
#[derive(Debug)]
enum Entry {
Section { title: String },
File { metadata: Metadata, content: String },
}
impl Entry {
fn as_list_entry(&'_ self) -> ListItem<'_> {
match self {
Entry::Section { title } => ListItem::new(title.as_str()).underlined().fg(Color::Blue),
Entry::File { metadata, .. } => ListItem::new(metadata.title.as_str()),
}
}
}
/// Loads release content from files in the specified directory
fn load_content(dir: PathBuf, kind: &'static str) -> Result<Vec<Entry>> {
let re = Regex::new(r"(?s)^---\s*\n(?<frontmatter>.*?)\s*\n---\s*\n(?<content>.*)").unwrap();
let mut entries = vec![];
for dir_entry in fs::read_dir(dir)
.into_diagnostic()
.wrap_err("unable to read directory")?
{
let dir_entry = dir_entry
.into_diagnostic()
.wrap_err(format!("unable to access {} file", kind))?;
// Skip directories
if !dir_entry.path().is_file() {
continue;
}
// Skip files with invalid names
let Ok(file_name) = dir_entry.file_name().into_string() else {
continue;
};
// Skip hidden files (like .gitkeep or .DS_Store)
if file_name.starts_with(".") {
continue;
}
let file_content = fs::read_to_string(dir_entry.path())
.into_diagnostic()
.wrap_err(format!("unable to read {} file", kind))?;
let caps = re.captures(&file_content).ok_or(diagnostic!(
"failed to find frontmatter in {} file {}",
kind,
file_name
))?;
let frontmatter = caps.name("frontmatter").unwrap().as_str();
let metadata = serde_yml::from_str::<Metadata>(frontmatter).map_err(|e| ParseError {
src: NamedSource::new(
format!("{}", dir_entry.path().display()),
frontmatter.to_owned(),
),
kind,
file_name,
err_span: e.location().map(|l| l.index()),
error: e,
})?;
let content = caps.name("content").unwrap().as_str().to_owned();
entries.push(Entry::File { metadata, content });
}
Ok(entries)
}
#[derive(Diagnostic, Debug, Error)]
#[error("failed to parse metadata in {kind} file {file_name}")]
pub struct ParseError {
#[source_code]
src: NamedSource<String>,
kind: &'static str,
file_name: String,
#[label("{error}")]
err_span: Option<usize>,
error: serde_yml::Error,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/export-content/src/main.rs | tools/export-content/src/main.rs | //! A tool for exporting release content.
//!
//! This terminal-based tool generates a release content file
//! from the content of the `release-content` directory.
//!
//! To run this tool, use the following command from the `bevy` repository root:
//!
//! ```sh
//! cargo run -p export-content
//! ```
use std::{
io,
panic::{set_hook, take_hook},
};
use app::App;
use miette::{IntoDiagnostic, Result};
use ratatui::{
crossterm::{
event::{DisableMouseCapture, EnableMouseCapture},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
},
prelude::*,
};
use crate::app::Content;
mod app;
fn main() -> Result<()> {
let check = std::env::args().any(|arg| arg == "--check");
if check {
Content::load().unwrap();
return Ok(());
}
init_panic_hook();
let mut terminal = init_terminal().unwrap();
let res = run_app(&mut terminal);
restore_terminal().unwrap();
res
}
fn run_app<B: Backend>(terminal: &mut Terminal<B>) -> Result<()> {
let app = App::new()?;
app.run(terminal)
}
fn init_panic_hook() {
let original_hook = take_hook();
set_hook(Box::new(move |panic_info| {
// intentionally ignore errors here since we're already in a panic
let _ = restore_terminal();
original_hook(panic_info);
}));
}
fn init_terminal() -> Result<Terminal<impl Backend>> {
enable_raw_mode().into_diagnostic()?;
execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture).into_diagnostic()?;
let backend = CrosstermBackend::new(io::stdout());
let terminal = Terminal::new(backend).into_diagnostic()?;
Ok(terminal)
}
fn restore_terminal() -> Result<()> {
disable_raw_mode().into_diagnostic()?;
execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture).into_diagnostic()?;
Ok(())
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/compile_fail_utils/src/lib.rs | tools/compile_fail_utils/src/lib.rs | use std::{
env,
path::{Path, PathBuf},
};
// Re-export ui_test so all the tests use the same version.
pub use ui_test;
use ui_test::{
bless_output_files,
color_eyre::eyre::eyre,
default_file_filter, default_per_file_config,
dependencies::DependencyBuilder,
ignore_output_conflict, run_tests_generic,
spanned::Spanned,
status_emitter::{Gha, StatusEmitter, Text},
Args, Config,
};
/// Use this instead of hand rolling configs.
///
/// `root_dir` is the directory your tests are contained in. Needs to be a path from crate root.
/// This config will build dependencies and will assume that the cargo manifest is placed at the
/// current working directory.
fn basic_config(root_dir: impl Into<PathBuf>, args: &Args) -> ui_test::Result<Config> {
let root_dir = root_dir.into();
match root_dir.try_exists() {
Ok(true) => { /* success */ }
Ok(false) => {
return Err(eyre!("path does not exist: {}", root_dir.display()));
}
Err(error) => {
return Err(eyre!(
"failed to read path: {} ({})",
root_dir.display(),
error
));
}
}
let mut config = Config {
bless_command: Some(
"`cargo test` with the BLESS environment variable set to any non empty value"
.to_string(),
),
output_conflict_handling: if env::var_os("BLESS").is_some() {
bless_output_files
} else {
// stderr output changes between rust versions so we just rely on annotations
ignore_output_conflict
},
..Config::rustc(root_dir)
};
config.with_args(args);
let bevy_root = "..";
// Don't leak contributor filesystem paths
config.path_stderr_filter(Path::new(bevy_root), b"$BEVY_ROOT");
if let Some(path) = option_env!("RUSTUP_HOME") {
config.path_stderr_filter(Path::new(path), b"$RUSTUP_HOME");
}
// ui_test doesn't compile regex with perl character classes.
// \pL = unicode class for letters, \pN = unicode class for numbers
config.stderr_filter(r"\/home\/[\pL\pN_@#\-\. ]+", "$HOME");
// Paths in .stderr seem to always be normalized to use /. Handle both anyway.
config.stderr_filter(
r"[a-zA-Z]:(?:\\|\/)users(?:\\|\/)[\pL\pN_@#\-\. ]+", // NOTE: [\pL\pN_@#\-\. ] is a poor attempt at handling usernames
"$HOME",
);
// Manually insert @aux-build:<dep> comments into test files. This needs to
// be done to build and link dependencies. Dependencies will be pulled from a
// Cargo.toml file.
config.comment_defaults.base().custom.insert(
"dependencies",
Spanned::dummy(vec![Box::new(DependencyBuilder::default())]),
);
Ok(config)
}
/// Runs ui tests for a single directory.
///
/// `root_dir` is the directory your tests are contained in. Needs to be a path from crate root.
pub fn test(test_name: impl Into<String>, test_root: impl Into<PathBuf>) -> ui_test::Result<()> {
test_multiple(test_name, [test_root])
}
/// Run ui tests with the given config
pub fn test_with_config(test_name: impl Into<String>, config: Config) -> ui_test::Result<()> {
test_with_multiple_configs(test_name, [Ok(config)])
}
/// Runs ui tests for a multiple directories.
///
/// `root_dirs` paths need to come from crate root.
pub fn test_multiple(
test_name: impl Into<String>,
test_roots: impl IntoIterator<Item = impl Into<PathBuf>>,
) -> ui_test::Result<()> {
let args = Args::test()?;
let configs = test_roots.into_iter().map(|root| basic_config(root, &args));
test_with_multiple_configs(test_name, configs)
}
/// Run ui test with the given configs.
///
/// Tests for configs are run in parallel.
pub fn test_with_multiple_configs(
test_name: impl Into<String>,
configs: impl IntoIterator<Item = ui_test::Result<Config>>,
) -> ui_test::Result<()> {
let configs = configs
.into_iter()
.collect::<ui_test::Result<Vec<Config>>>()?;
let emitter: Box<dyn StatusEmitter + Send> = if env::var_os("CI").is_some() {
Box::new((
Text::verbose(),
Gha {
group: true,
name: test_name.into(),
},
))
} else {
Box::new(Text::quiet())
};
run_tests_generic(
configs,
default_file_filter,
default_per_file_config,
emitter,
)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/compile_fail_utils/tests/example.rs | tools/compile_fail_utils/tests/example.rs | fn main() -> compile_fail_utils::ui_test::Result<()> {
// Run all tests in the tests/example_tests folder.
// If we had more tests we could either call this function
// on every single one or use test_multiple and past it an array
// of paths.
//
// Don't forget that when running tests the working directory
// is set to the crate root.
compile_fail_utils::test("example_tests", "tests/example_tests")
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/compile_fail_utils/tests/example_tests/pass_test.rs | tools/compile_fail_utils/tests/example_tests/pass_test.rs | //@check-pass
// This code is expected to compile correctly.
fn correct_borrowing() {
let x = String::new();
let y = &x;
println!("{x}");
println!("{y}");
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/compile_fail_utils/tests/example_tests/basic_test.rs | tools/compile_fail_utils/tests/example_tests/basic_test.rs | // Compiler warnings also need to be annotated. We don't
// want to annotate all the unused variables so let's instruct
// the compiler to ignore them.
#![allow(unused_variables)]
fn bad_moves() {
let x = String::new();
// Help diagnostics need to be annotated
let y = x;
//~^ HELP: consider cloning
// We expect a failure on this line
println!("{x}"); //~ ERROR: borrow
let x = String::new();
// We expect the help message to mention cloning.
//~v HELP: consider cloning
let y = x;
// Check error message using a regex
println!("{x}");
//~^ ERROR: /(move)|(borrow)/
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/compile_fail_utils/tests/example_tests/import.rs | tools/compile_fail_utils/tests/example_tests/import.rs | // You can import anything defined in the dependencies table of the crate.
use ui_test::Config;
fn wrong_type() {
let _ = Config::this_function_does_not_exist();
//~^ E0599
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/build-wasm-example/src/main.rs | tools/build-wasm-example/src/main.rs | //! Tool used to build Bevy examples for wasm.
use std::{fs::File, io::Write};
use clap::{Parser, ValueEnum};
use xshell::{cmd, Shell};
#[derive(Debug, Copy, Clone, ValueEnum)]
enum WebApi {
Webgl2,
Webgpu,
}
#[derive(Parser, Debug)]
struct Args {
/// Examples to build
examples: Vec<String>,
#[arg(short, long)]
/// Run tests
test: bool,
#[arg(short, long)]
/// Run on the given browsers. By default, chromium, firefox, webkit
browsers: Vec<String>,
#[arg(short, long)]
/// Stop after this number of frames
frames: Option<usize>,
#[arg(value_enum, short, long, default_value_t = WebApi::Webgl2)]
/// Browser API to use for rendering
api: WebApi,
#[arg(short, long)]
/// Optimize the wasm file for size with wasm-opt
optimize_size: bool,
#[arg(long)]
/// Additional features to enable
features: Vec<String>,
#[arg(long)]
/// Build the example in debug mode instead of release
debug: bool,
}
fn main() {
let cli = Args::parse();
assert!(!cli.examples.is_empty(), "must have at least one example");
let default_features = true;
let mut features: Vec<&str> = cli.features.iter().map(String::as_str).collect();
if let Some(frames) = cli.frames {
let mut file = File::create("ci_testing_config.ron").unwrap();
file.write_fmt(format_args!("(events: [({frames}, AppExit)])"))
.unwrap();
features.push("bevy_ci_testing");
}
match cli.api {
WebApi::Webgl2 => (),
WebApi::Webgpu => {
features.push("webgpu");
}
}
for example in cli.examples {
let sh = Shell::new().unwrap();
let features_string = features.join(",");
let mut parameters = vec![];
if !default_features {
parameters.push("--no-default-features");
}
if !features.is_empty() {
parameters.push("--features");
parameters.push(&features_string);
}
let profile = if cli.debug {
"debug"
} else if cli.optimize_size {
"wasm-release"
} else {
"release"
};
let cmd = cmd!(
sh,
"cargo build {parameters...} --profile {profile} --target wasm32-unknown-unknown --example {example}"
);
cmd.env("RUSTFLAGS", "--cfg getrandom_backend=\"wasm_js\"")
.run()
.expect("Error building example");
cmd!(
sh,
"wasm-bindgen --out-dir examples/wasm/target --out-name wasm_example --target web target/wasm32-unknown-unknown/{profile}/examples/{example}.wasm"
)
.run()
.expect("Error creating wasm binding");
if cli.optimize_size {
cmd!(sh, "wasm-opt -Oz --output examples/wasm/target/wasm_example_bg.wasm.optimized examples/wasm/target/wasm_example_bg.wasm")
.run().expect("Failed to optimize for size. Do you have wasm-opt correctly set up?");
}
if cli.test {
let _dir = sh.push_dir(".github/start-wasm-example");
let mut browsers = cli.browsers.clone();
if !browsers.is_empty() {
browsers.insert(0, "--project".to_string());
}
cmd!(sh, "npx playwright test --headed {browsers...}")
.env("SCREENSHOT_PREFIX", format!("screenshot-{example}"))
.run()
.expect("Error running playwright test");
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tools/build-easefunction-graphs/src/main.rs | tools/build-easefunction-graphs/src/main.rs | //! Generates graphs for the `EaseFunction` docs.
#![expect(clippy::print_stdout, reason = "Allowed in tools.")]
use std::path::PathBuf;
use bevy_math::curve::{CurveExt, EaseFunction, EasingCurve, JumpAt};
use svg::{
node::element::{self, path::Data},
Document,
};
fn main() {
let root_dir = PathBuf::from(
std::env::var("CARGO_MANIFEST_DIR")
.expect("Please run via cargo or set CARGO_MANIFEST_DIR"),
);
let directory = root_dir
.join("../../crates/bevy_math/images/easefunction")
.canonicalize()
.unwrap();
for function in [
EaseFunction::SineIn,
EaseFunction::SineOut,
EaseFunction::SineInOut,
EaseFunction::QuadraticIn,
EaseFunction::QuadraticOut,
EaseFunction::QuadraticInOut,
EaseFunction::CubicIn,
EaseFunction::CubicOut,
EaseFunction::CubicInOut,
EaseFunction::QuarticIn,
EaseFunction::QuarticOut,
EaseFunction::QuarticInOut,
EaseFunction::QuinticIn,
EaseFunction::QuinticOut,
EaseFunction::QuinticInOut,
EaseFunction::SmoothStepIn,
EaseFunction::SmoothStepOut,
EaseFunction::SmoothStep,
EaseFunction::SmootherStepIn,
EaseFunction::SmootherStepOut,
EaseFunction::SmootherStep,
EaseFunction::CircularIn,
EaseFunction::CircularOut,
EaseFunction::CircularInOut,
EaseFunction::ExponentialIn,
EaseFunction::ExponentialOut,
EaseFunction::ExponentialInOut,
EaseFunction::ElasticIn,
EaseFunction::ElasticOut,
EaseFunction::ElasticInOut,
EaseFunction::BackIn,
EaseFunction::BackOut,
EaseFunction::BackInOut,
EaseFunction::BounceIn,
EaseFunction::BounceOut,
EaseFunction::BounceInOut,
EaseFunction::Linear,
EaseFunction::Steps(4, JumpAt::Start),
EaseFunction::Steps(4, JumpAt::End),
EaseFunction::Steps(4, JumpAt::None),
EaseFunction::Steps(4, JumpAt::Both),
EaseFunction::Elastic(50.0),
] {
let curve = EasingCurve::new(0.0, 1.0, function);
let samples = curve
.map(|y| {
// Fit into svg coordinate system
1. - y
})
.graph()
.samples(100)
.unwrap()
.collect::<Vec<_>>();
// Curve can go out past endpoints
let mut min = 0.0f32;
let mut max = 1.0f32;
for &(_, y) in &samples {
min = min.min(y);
max = max.max(y);
}
let graph = element::Polyline::new()
.set("points", samples)
.set("fill", "none")
.set("stroke", "red")
.set("stroke-width", 0.04);
let guides = element::Path::new()
.set("fill", "none")
.set("stroke", "var(--main-color)")
.set("stroke-width", 0.02)
.set("d", {
// Interval
let mut data = Data::new()
.move_to((0, 0))
.line_to((0, 1))
.move_to((1, 0))
.line_to((1, 1));
// Dotted lines y=0 | y=1
for y in 0..=1 {
data = data.move_to((0, y));
for _ in 0..5 {
data = data.move_by((0.1, 0.)).line_by((0.1, 0.));
}
}
data
});
let opt_tag = match function {
EaseFunction::Steps(_n, jump_at) => format!("{jump_at:?}"),
_ => String::new(),
};
let name = format!("{opt_tag}{function:?}");
let tooltip = element::Title::new(&name);
const MARGIN: f32 = 0.04;
let document = Document::new()
.set("width", "6em")
.set(
"viewBox",
(
-MARGIN,
min - MARGIN,
1. + 2. * MARGIN,
max - min + 2. * MARGIN,
),
)
.add(tooltip)
.add(guides)
.add(graph);
let file_path = directory
.join(name.split('(').next().unwrap())
.with_extension("svg");
println!("saving {file_path:?}");
svg::save(file_path, &document).unwrap();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests-integration/simple-ecs-test/src/lib.rs | tests-integration/simple-ecs-test/src/lib.rs | #![allow(dead_code)]
use bevy::prelude::*;
#[derive(Component)]
struct MyComponent {
value: f32,
}
#[derive(Resource)]
struct MyResource {
value: f32,
}
fn hello_world(query: Query<&MyComponent>, resource: Res<MyResource>) {
let component = query.iter().next().unwrap();
let comp_value = component.value; // rust-analyzer suggestions work
let res_value_deref = resource.value; // rust-analyzer suggestions don't work but ctrl+click works once it's written, also type inlay hints work correctly
let res_value_direct = resource.into_inner().value; // rust-analyzer suggestions work
println!(
"hello world! Value: {} {} {}",
comp_value, res_value_deref, res_value_direct
);
}
fn spawn_component(mut commands: Commands) {
commands.spawn(MyComponent { value: 10.0 });
}
#[test]
fn simple_ecs_test() {
App::new()
.insert_resource(MyResource { value: 5.0 })
.add_systems(Startup, spawn_component)
.add_systems(Update, hello_world)
.run();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/errors/src/lib.rs | errors/src/lib.rs | //! Definitions of Bevy's error codes that might occur at runtime.
//!
//! These either manifest as a warning or a panic.
#[doc = include_str!("../B0001.md")]
pub struct B0001;
#[doc = include_str!("../B0002.md")]
pub struct B0002;
#[doc = include_str!("../B0003.md")]
pub struct B0003;
#[doc = include_str!("../B0004.md")]
pub struct B0004;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/src/lib.rs | src/lib.rs | #![cfg_attr(docsrs, feature(doc_cfg))]
#![expect(
clippy::doc_markdown,
reason = "Clippy lints for un-backticked identifiers within the cargo features list, which we don't want."
)]
//! [](https://bevy.org)
//!
//! Bevy is an open-source, modular game engine built in Rust, with a focus on developer productivity
//! and performance.
//!
//! Check out the [Bevy website](https://bevy.org) for more information, read the
//! [Quick Start Guide](https://bevy.org/learn/quick-start/introduction) for a step-by-step introduction, and [engage with our
//! community](https://bevy.org/community/) if you have any questions or ideas!
//!
//! ## Example
//!
//! Here is a simple "Hello, World!" Bevy app:
//! ```
//! use bevy::prelude::*;
//!
//! fn main() {
//! App::new()
//! .add_systems(Update, hello_world_system)
//! .run();
//! }
//!
//! fn hello_world_system() {
//! println!("hello world");
//! }
//! ```
//!
//! Don't let the simplicity of the example above fool you. Bevy is a [fully featured game engine](https://bevy.org),
//! and it gets more powerful every day!
//!
//! ## This Crate
//!
//! The `bevy` crate is a container crate that makes it easier to consume Bevy subcrates.
//! The defaults provide a "full engine" experience, but you can easily enable or disable features
//! in your project's `Cargo.toml` to meet your specific needs. See Bevy's `Cargo.toml` for a full
//! list of available features.
//!
//! If you prefer, you can also use the individual Bevy crates directly.
//! Each module in the root of this crate, except for the prelude, can be found on crates.io
//! with `bevy_` appended to the front, e.g., `app` -> [`bevy_app`](https://docs.rs/bevy_app/*/bevy_app/).
#![doc = include_str!("../docs/cargo_features.md")]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
#![no_std]
pub use bevy_internal::*;
// Wasm does not support dynamic linking.
#[cfg(all(feature = "dynamic_linking", not(target_family = "wasm")))]
#[expect(
unused_imports,
clippy::single_component_path_imports,
reason = "This causes Bevy to be compiled as a dylib when using dynamic linking and therefore cannot be removed or changed without affecting dynamic linking."
)]
use bevy_dylib;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests/how_to_test_systems.rs | tests/how_to_test_systems.rs | #![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
use bevy::prelude::*;
#[derive(Component, Default)]
struct Enemy {
hit_points: u32,
score_value: u32,
}
#[derive(Message)]
struct EnemyDied(u32);
#[derive(Resource)]
struct Score(u32);
fn update_score(mut dead_enemies: MessageReader<EnemyDied>, mut score: ResMut<Score>) {
for value in dead_enemies.read() {
score.0 += value.0;
}
}
fn despawn_dead_enemies(
mut commands: Commands,
mut dead_enemies: MessageWriter<EnemyDied>,
enemies: Query<(Entity, &Enemy)>,
) {
for (entity, enemy) in &enemies {
if enemy.hit_points == 0 {
commands.entity(entity).despawn();
dead_enemies.write(EnemyDied(enemy.score_value));
}
}
}
fn hurt_enemies(mut enemies: Query<&mut Enemy>) {
for mut enemy in &mut enemies {
enemy.hit_points -= 1;
}
}
fn spawn_enemy(mut commands: Commands, keyboard_input: Res<ButtonInput<KeyCode>>) {
if keyboard_input.just_pressed(KeyCode::Space) {
commands.spawn(Enemy {
hit_points: 5,
score_value: 3,
});
}
}
#[test]
fn did_hurt_enemy() {
// Setup app
let mut app = App::new();
// Add Score resource
app.insert_resource(Score(0));
// Add `EnemyDied` event
app.add_message::<EnemyDied>();
// Add our two systems
app.add_systems(Update, (hurt_enemies, despawn_dead_enemies).chain());
// Setup test entities
let enemy_id = app
.world_mut()
.spawn(Enemy {
hit_points: 5,
score_value: 3,
})
.id();
// Run systems
app.update();
// Check resulting changes
assert!(app.world().get::<Enemy>(enemy_id).is_some());
assert_eq!(app.world().get::<Enemy>(enemy_id).unwrap().hit_points, 4);
}
#[test]
fn did_despawn_enemy() {
// Setup app
let mut app = App::new();
// Add Score resource
app.insert_resource(Score(0));
// Add `EnemyDied` event
app.add_message::<EnemyDied>();
// Add our two systems
app.add_systems(Update, (hurt_enemies, despawn_dead_enemies).chain());
// Setup test entities
let enemy_id = app
.world_mut()
.spawn(Enemy {
hit_points: 1,
score_value: 1,
})
.id();
// Run systems
app.update();
// Check enemy was despawned
assert!(app.world().get::<Enemy>(enemy_id).is_none());
// Get `EnemyDied` message reader
let enemy_died_messages = app.world().resource::<Messages<EnemyDied>>();
let mut enemy_died_cursor = enemy_died_messages.get_cursor();
let enemy_died = enemy_died_cursor.read(enemy_died_messages).next().unwrap();
// Check the event has been sent
assert_eq!(enemy_died.0, 1);
}
#[test]
fn spawn_enemy_using_input_resource() {
// Setup app
let mut app = App::new();
// Add our systems
app.add_systems(Update, spawn_enemy);
// Setup test resource
let mut input = ButtonInput::<KeyCode>::default();
input.press(KeyCode::Space);
app.insert_resource(input);
// Run systems
app.update();
// Check resulting changes, one entity has been spawned with `Enemy` component
assert_eq!(app.world_mut().query::<&Enemy>().iter(app.world()).len(), 1);
// Clear the `just_pressed` status for all `KeyCode`s
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.clear();
// Run systems
app.update();
// Check resulting changes, no new entity has been spawned
assert_eq!(app.world_mut().query::<&Enemy>().iter(app.world()).len(), 1);
}
#[test]
fn update_score_on_event() {
// Setup app
let mut app = App::new();
// Add Score resource
app.insert_resource(Score(0));
// Add `EnemyDied` message
app.add_message::<EnemyDied>();
// Add our systems
app.add_systems(Update, update_score);
// Write an `EnemyDied` event
app.world_mut()
.resource_mut::<Messages<EnemyDied>>()
.write(EnemyDied(3));
// Run systems
app.update();
// Check resulting changes
assert_eq!(app.world().resource::<Score>().0, 3);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests/how_to_test_apps.rs | tests/how_to_test_apps.rs | //! Demonstrates simple integration testing of Bevy applications.
//!
//! By substituting [`DefaultPlugins`] with [`MinimalPlugins`], Bevy can run completely headless.
//!
//! The list of minimal plugins does not include things like window or input handling. The downside
//! of this is that resources or entities associated with those systems (for example:
//! `ButtonInput::<KeyCode>`) need to be manually added, either directly or via e.g.
//! [`InputPlugin`]. The upside, however, is that the test has complete control over these
//! resources, meaning we can fake user input, fake the window being moved around, and more.
use bevy::prelude::*;
#[derive(Component)]
struct Player {
mana: u32,
}
impl Default for Player {
fn default() -> Self {
Self { mana: 10 }
}
}
/// Splitting a Bevy project into multiple smaller plugins can make it more testable. We can
/// write tests for individual plugins in isolation, as well as for the entire project.
fn game_plugin(app: &mut App) {
app.add_systems(Startup, (spawn_player, window_title_system).chain());
app.add_systems(Update, spell_casting);
}
fn window_title_system(mut windows: Query<&mut Window>) {
for (index, mut window) in windows.iter_mut().enumerate() {
window.title = format!("This is window {index}!");
}
}
fn spawn_player(mut commands: Commands) {
commands.spawn(Player::default());
}
fn spell_casting(mut player: Query<&mut Player>, keyboard_input: Res<ButtonInput<KeyCode>>) {
if keyboard_input.just_pressed(KeyCode::Space) {
let Ok(mut player) = player.single_mut() else {
return;
};
if player.mana > 0 {
player.mana -= 1;
}
}
}
fn create_test_app() -> App {
let mut app = App::new();
// Note the use of `MinimalPlugins` instead of `DefaultPlugins`, as described above.
app.add_plugins(MinimalPlugins);
// Inserting a `KeyCode` input resource allows us to inject keyboard inputs, as if the user had
// pressed them.
app.insert_resource(ButtonInput::<KeyCode>::default());
// Spawning a fake window allows testing systems that require a window.
app.world_mut().spawn(Window::default());
app
}
#[test]
fn test_player_spawn() {
let mut app = create_test_app();
app.add_plugins(game_plugin);
// The `update` function needs to be called at least once for the startup
// systems to run.
app.update();
// Now that the startup systems have run, we can check if the player has
// spawned as expected.
let expected = Player::default();
let actual = app.world_mut().query::<&Player>().single(app.world());
assert!(actual.is_ok(), "There should be exactly 1 player.");
assert_eq!(
expected.mana,
actual.unwrap().mana,
"Player does not have expected starting mana."
);
}
#[test]
fn test_spell_casting() {
let mut app = create_test_app();
app.add_plugins(game_plugin);
// Simulate pressing space to trigger the spell casting system.
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(KeyCode::Space);
// Allow the systems to recognize the input event.
app.update();
let expected = Player::default();
let actual = app
.world_mut()
.query::<&Player>()
.single(app.world())
.unwrap();
assert_eq!(
expected.mana - 1,
actual.mana,
"A single mana point should have been used."
);
// Clear the `just_pressed` status for all `KeyCode`s
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.clear();
app.update();
// No extra spells have been cast, so no mana should have been used.
let after_keypress_event = app
.world_mut()
.query::<&Player>()
.single(app.world())
.unwrap();
assert_eq!(
expected.mana - 1,
after_keypress_event.mana,
"No further mana should have been used."
);
}
#[test]
fn test_window_title() {
let mut app = create_test_app();
app.add_plugins(game_plugin);
app.update();
let window = app
.world_mut()
.query::<&Window>()
.single(app.world())
.unwrap();
assert_eq!(window.title, "This is window 0!");
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests/3d/test_invalid_skinned_mesh.rs | tests/3d/test_invalid_skinned_mesh.rs | //! Test that the renderer can handle various invalid skinned meshes
use bevy::{
asset::RenderAssetUsages,
camera::ScalingMode,
math::ops,
mesh::{
skinning::{SkinnedMesh, SkinnedMeshInverseBindposes},
Indices, PrimitiveTopology, VertexAttributeValues,
},
post_process::motion_blur::MotionBlur,
prelude::*,
};
use core::f32::consts::TAU;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(GlobalAmbientLight {
brightness: 20_000.0,
..default()
})
.add_systems(Startup, (setup_environment, setup_meshes))
.add_systems(Update, update_animated_joints)
.run();
}
fn setup_environment(
mut commands: Commands,
mut mesh_assets: ResMut<Assets<Mesh>>,
mut material_assets: ResMut<Assets<StandardMaterial>>,
) {
let description = "(left to right)\n\
0: Normal skinned mesh.\n\
1: Mesh asset is missing skinning attributes.\n\
2: One joint entity is missing.\n\
3: Mesh entity is missing SkinnedMesh component.";
commands.spawn((
Text::new(description),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
));
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 0.0, 1.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
Projection::Orthographic(OrthographicProjection {
scaling_mode: ScalingMode::AutoMin {
min_width: 19.0,
min_height: 6.0,
},
..OrthographicProjection::default_3d()
}),
// Add motion blur so we can check if it's working for skinned meshes.
// This also exercises the renderer's prepass path.
MotionBlur {
// Use an unrealistically large shutter angle so that motion blur is clearly visible.
shutter_angle: 3.0,
samples: 2,
},
// MSAA and MotionBlur together are not compatible on WebGL.
#[cfg(all(feature = "webgl2", target_arch = "wasm32", not(feature = "webgpu")))]
Msaa::Off,
));
// Add a directional light to make sure we exercise the renderer's shadow path.
commands.spawn((
Transform::from_xyz(1.0, 1.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
DirectionalLight {
shadows_enabled: true,
..default()
},
));
// Add a plane behind the meshes so we can see the shadows.
commands.spawn((
Transform::from_xyz(0.0, 0.0, -1.0),
Mesh3d(mesh_assets.add(Plane3d::default().mesh().size(100.0, 100.0).normal(Dir3::Z))),
MeshMaterial3d(material_assets.add(StandardMaterial {
base_color: Color::srgb(0.05, 0.05, 0.15),
reflectance: 0.2,
..default()
})),
));
}
fn setup_meshes(
mut commands: Commands,
mut mesh_assets: ResMut<Assets<Mesh>>,
mut material_assets: ResMut<Assets<StandardMaterial>>,
mut inverse_bindposes_assets: ResMut<Assets<SkinnedMeshInverseBindposes>>,
) {
// Create a mesh with two rectangles.
let unskinned_mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
)
.with_inserted_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![
[-0.3, -0.3, 0.0],
[0.3, -0.3, 0.0],
[-0.3, 0.3, 0.0],
[0.3, 0.3, 0.0],
[-0.4, 0.8, 0.0],
[0.4, 0.8, 0.0],
[-0.4, 1.8, 0.0],
[0.4, 1.8, 0.0],
],
)
.with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, vec![[0.0, 0.0, 1.0]; 8])
.with_inserted_indices(Indices::U16(vec![0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6]));
// Copy the mesh and add skinning attributes that bind each rectangle to a joint.
let skinned_mesh = unskinned_mesh
.clone()
.with_inserted_attribute(
Mesh::ATTRIBUTE_JOINT_INDEX,
VertexAttributeValues::Uint16x4(vec![
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 0],
[1, 0, 0, 0],
[1, 0, 0, 0],
[1, 0, 0, 0],
]),
)
.with_inserted_attribute(
Mesh::ATTRIBUTE_JOINT_WEIGHT,
vec![[1.00, 0.00, 0.0, 0.0]; 8],
);
let unskinned_mesh_handle = mesh_assets.add(unskinned_mesh);
let skinned_mesh_handle = mesh_assets.add(skinned_mesh);
let inverse_bindposes_handle = inverse_bindposes_assets.add(vec![
Mat4::IDENTITY,
Mat4::from_translation(Vec3::new(0.0, -1.3, 0.0)),
]);
let mesh_material_handle = material_assets.add(StandardMaterial::default());
let background_material_handle = material_assets.add(StandardMaterial {
base_color: Color::srgb(0.05, 0.15, 0.05),
reflectance: 0.2,
..default()
});
#[derive(PartialEq)]
enum Variation {
Normal,
MissingMeshAttributes,
MissingJointEntity,
MissingSkinnedMeshComponent,
}
for (index, variation) in [
Variation::Normal,
Variation::MissingMeshAttributes,
Variation::MissingJointEntity,
Variation::MissingSkinnedMeshComponent,
]
.into_iter()
.enumerate()
{
// Skip variations that are currently broken. See https://github.com/bevyengine/bevy/issues/16929,
// https://github.com/bevyengine/bevy/pull/18074.
if (variation == Variation::MissingSkinnedMeshComponent)
|| (variation == Variation::MissingMeshAttributes)
{
continue;
}
let transform = Transform::from_xyz(((index as f32) - 1.5) * 4.5, 0.0, 0.0);
let joint_0 = commands.spawn(transform).id();
let joint_1 = commands
.spawn((ChildOf(joint_0), AnimatedJoint, Transform::IDENTITY))
.id();
if variation == Variation::MissingJointEntity {
commands.entity(joint_1).despawn();
}
let mesh_handle = match variation {
Variation::MissingMeshAttributes => &unskinned_mesh_handle,
_ => &skinned_mesh_handle,
};
let mut entity_commands = commands.spawn((
Mesh3d(mesh_handle.clone()),
MeshMaterial3d(mesh_material_handle.clone()),
transform,
));
if variation != Variation::MissingSkinnedMeshComponent {
entity_commands.insert(SkinnedMesh {
inverse_bindposes: inverse_bindposes_handle.clone(),
joints: vec![joint_0, joint_1],
});
}
// Add a square behind the mesh to distinguish it from the other meshes.
commands.spawn((
Transform::from_xyz(transform.translation.x, transform.translation.y, -0.8),
Mesh3d(mesh_assets.add(Plane3d::default().mesh().size(4.3, 4.3).normal(Dir3::Z))),
MeshMaterial3d(background_material_handle.clone()),
));
}
}
#[derive(Component)]
struct AnimatedJoint;
fn update_animated_joints(time: Res<Time>, query: Query<&mut Transform, With<AnimatedJoint>>) {
for mut transform in query {
let angle = TAU * 4.0 * ops::cos((time.elapsed_secs() / 8.0) * TAU);
let rotation = Quat::from_rotation_z(angle);
transform.rotation = rotation;
transform.translation = rotation.mul_vec3(Vec3::new(0.0, 1.3, 0.0));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests/3d/no_prepass.rs | tests/3d/no_prepass.rs | //! A test to confirm that `bevy` allows disabling the prepass of the standard material.
//! This is run in CI to ensure that this doesn't regress again.
use bevy::{pbr::PbrPlugin, prelude::*};
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(PbrPlugin {
prepass_enabled: false,
..default()
}))
.run();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests/window/resizing.rs | tests/window/resizing.rs | //! A test to confirm that `bevy` allows setting the window to arbitrary small sizes
//! This is run in CI to ensure that this doesn't regress again.
use bevy::{prelude::*, window::WindowResolution};
// The smallest size reached is 1x1, as X11 doesn't support windows with a 0 dimension
// TODO: Add a check for platforms other than X11 for 0xk and kx0, despite those currently unsupported on CI.
const MAX_WIDTH: u16 = 401;
const MAX_HEIGHT: u16 = 401;
const MIN_WIDTH: u16 = 1;
const MIN_HEIGHT: u16 = 1;
const RESIZE_STEP: u16 = 4;
#[derive(Resource)]
struct Dimensions {
width: u16,
height: u16,
}
fn main() {
App::new()
.add_plugins(
DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
resolution: WindowResolution::new(MAX_WIDTH as u32, MAX_HEIGHT as u32)
.with_scale_factor_override(1.0),
title: "Resizing".into(),
..default()
}),
..default()
}),
)
.insert_resource(Dimensions {
width: MAX_WIDTH,
height: MAX_HEIGHT,
})
.insert_resource(ContractingY)
.add_systems(Startup, (setup_3d, setup_2d))
.add_systems(Update, (change_window_size, sync_dimensions))
.run();
}
#[derive(Resource)]
enum Phase {
ContractingY,
ContractingX,
ExpandingY,
ExpandingX,
}
use Phase::*;
fn change_window_size(
mut windows: ResMut<Dimensions>,
mut phase: ResMut<Phase>,
mut first_complete: Local<bool>,
) {
// Put off rendering for one frame, as currently for a frame where
// resizing happens, nothing is presented.
// TODO: Debug and fix this if feasible
if !*first_complete {
*first_complete = true;
return;
}
let height = windows.height;
let width = windows.width;
match *phase {
ContractingY => {
if height <= MIN_HEIGHT {
*phase = ContractingX;
} else {
windows.height -= RESIZE_STEP;
}
}
ContractingX => {
if width <= MIN_WIDTH {
*phase = ExpandingY;
} else {
windows.width -= RESIZE_STEP;
}
}
ExpandingY => {
if height >= MAX_HEIGHT {
*phase = ExpandingX;
} else {
windows.height += RESIZE_STEP;
}
}
ExpandingX => {
if width >= MAX_WIDTH {
*phase = ContractingY;
} else {
windows.width += RESIZE_STEP;
}
}
}
}
fn sync_dimensions(dim: Res<Dimensions>, mut window: Single<&mut Window>) {
if dim.is_changed() {
window.resolution.set(dim.width as f32, dim.height as f32);
}
}
/// A simple 3d scene, taken from the `3d_scene` example
fn setup_3d(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// plane
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
));
// cube
commands.spawn((
Mesh3d(meshes.add(Cuboid::default())),
MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))),
Transform::from_xyz(0.0, 0.5, 0.0),
));
// light
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
/// A simple 2d scene, taken from the `rect` example
fn setup_2d(mut commands: Commands) {
commands.spawn((
Camera2d,
Camera {
// render the 2d camera after the 3d camera
order: 1,
// do not use a clear color
clear_color: ClearColorConfig::None,
..default()
},
));
commands.spawn(Sprite::from_color(
Color::srgb(0.25, 0.25, 0.75),
Vec2::new(50.0, 50.0),
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.