Debian Codegraph @

lib/testutils/src/lib.rs

raw
1 // Copyright 2020 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::collections::HashMap;
16 use std::collections::HashSet;
17 use std::env;
18 use std::ffi::OsStr;
19 use std::fs;
20 use std::fs::OpenOptions;
21 use std::io::Write as _;
22 use std::path::Path;
23 use std::path::PathBuf;
24 use std::process::Command;
25 use std::process::Stdio;
26 use std::sync::Arc;
27
28 use futures::AsyncReadExt as _;
29 use itertools::Itertools as _;
30 use jj_lib::backend;
31 use jj_lib::backend::Backend;
32 use jj_lib::backend::BackendInitError;
33 use jj_lib::backend::ChangeId;
34 use jj_lib::backend::CommitId;
35 use jj_lib::backend::CopyHistory;
36 use jj_lib::backend::CopyId;
37 use jj_lib::backend::FileId;
38 use jj_lib::backend::MillisSinceEpoch;
39 use jj_lib::backend::Signature;
40 use jj_lib::backend::Timestamp;
41 use jj_lib::backend::TreeValue;
42 use jj_lib::commit::Commit;
43 use jj_lib::commit_builder::CommitBuilder;
44 use jj_lib::config::ConfigLayer;
45 use jj_lib::config::ConfigSource;
46 use jj_lib::config::StackedConfig;
47 use jj_lib::conflict_labels::ConflictLabels;
48 use jj_lib::default_backend_factories::default_backend_factories;
49 use jj_lib::git_backend::GitBackend;
50 use jj_lib::gitignore::GitIgnoreFile;
51 use jj_lib::matchers::EverythingMatcher;
52 use jj_lib::matchers::NothingMatcher;
53 use jj_lib::merge::Merge;
54 use jj_lib::merged_tree::MergedTree;
55 use jj_lib::object_id::ObjectId as _;
56 use jj_lib::repo::MutableRepo;
57 use jj_lib::repo::ReadonlyRepo;
58 use jj_lib::repo::Repo;
59 use jj_lib::repo::RepoLoader;
60 use jj_lib::repo::StoreFactories;
61 use jj_lib::repo_path::RepoPath;
62 use jj_lib::repo_path::RepoPathBuf;
63 use jj_lib::repo_path::RepoPathComponent;
64 use jj_lib::revset::RevsetExpression;
65 use jj_lib::rewrite::RebaseOptions;
66 use jj_lib::rewrite::RebasedCommit;
67 use jj_lib::secret_backend::SecretBackend;
68 use jj_lib::settings::UserSettings;
69 use jj_lib::signing::Signer;
70 use jj_lib::simple_backend::SimpleBackend;
71 use jj_lib::store::Store;
72 use jj_lib::transaction::Transaction;
73 use jj_lib::tree::Tree;
74 use jj_lib::tree_builder::TreeBuilder;
75 use jj_lib::working_copy::SnapshotError;
76 use jj_lib::working_copy::SnapshotOptions;
77 use jj_lib::working_copy::SnapshotStats;
78 use jj_lib::workspace::Workspace;
79 use pollster::FutureExt as _;
80 use tempfile::TempDir;
81
82 use crate::test_backend::TestBackendFactory;
83
84 pub mod git;
85 pub mod proptest;
86 pub mod test_backend;
87
88 /// Convenient return type for test functions.
89 pub type TestResult<T = ()> = eyre::Result<T>;
90
91 pub const HERMETIC_GIT_CONFIGS: &[(&str, &str)] = &[
92 // gitoxide uses "main" as the default branch name, whereas git uses "master". This also
93 // prevents git CLI from issuing the initial branch name advice.
94 ("init.defaultBranch", "master"),
95 ];
96
97 // TODO: Consider figuring out a way to make `GitBackend` and `git(1)` calls in
98 // tests ignore external configuration and removing this function. This is
99 // somewhat tricky because `gix` looks at system and user configuration, and
100 // `GitBackend` also calls into `git(1)` for things like garbage collection.
101 pub fn hermetic_git() {
102 let mut envs = [
103 // Prevent GitBackend from loading user and system configurations. For
104 // gitoxide API use in tests, Config::isolated() is probably better.
105 ("GIT_CONFIG_SYSTEM", "/dev/null"),
106 ("GIT_CONFIG_GLOBAL", "/dev/null"),
107 ]
108 .map(|(key, value)| (key.to_string(), value.to_string()))
109 .to_vec();
110 for (i, (key, value)) in HERMETIC_GIT_CONFIGS.iter().enumerate() {
111 envs.push((format!("GIT_CONFIG_KEY_{i}"), key.to_string()));
112 envs.push((format!("GIT_CONFIG_VALUE_{i}"), value.to_string()));
113 }
114 envs.push((
115 "GIT_CONFIG_COUNT".to_string(),
116 HERMETIC_GIT_CONFIGS.len().to_string(),
117 ));
118 for (key, value) in envs {
119 // SAFETY: This is actually not safe. `getenv` and `setenv` are not thread safe,
120 // and we can't guarantee that the following call won't have race conditions.
121 unsafe { env::set_var(key, value) };
122 }
123 }
124
125 pub fn new_temp_dir() -> TempDir {
126 hermetic_git();
127 tempfile::Builder::new()
128 .prefix("jj-test-")
129 .tempdir()
130 .unwrap()
131 }
132
133 /// Returns new low-level config object that includes fake user configuration
134 /// needed to run basic operations.
135 pub fn base_user_config() -> StackedConfig {
136 let config_text = r#"
137 user.name = "Test User"
138 user.email = "[email protected]"
139 operation.username = "test-username"
140 operation.hostname = "host.example.com"
141 debug.randomness-seed = 42
142 "#;
143 let mut config = StackedConfig::with_defaults();
144 config.add_layer(ConfigLayer::parse(ConfigSource::User, config_text).unwrap());
145 config
146 }
147
148 /// Returns new immutable settings object that includes fake user configuration
149 /// needed to run basic operations.
150 pub fn user_settings() -> UserSettings {
151 UserSettings::from_config(base_user_config()).unwrap()
152 }
153
154 /// Creates [`SnapshotOptions`] for use in tests.
155 pub fn empty_snapshot_options() -> SnapshotOptions<'static> {
156 SnapshotOptions {
157 base_ignores: GitIgnoreFile::empty(),
158 progress: None,
159 start_tracking_matcher: &EverythingMatcher,
160 force_tracking_matcher: &NothingMatcher,
161 max_new_file_size: u64::MAX,
162 }
163 }
164
165 /// Panic if `CI` environment variable is set to a non-empty value
166 ///
167 /// Most CI environments set this variable automatically. See e.g.
168 /// <https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables#default-environment-variables>
169 #[track_caller]
170 pub fn ensure_running_outside_ci(reason: &str) {
171 let running_in_ci = std::env::var("CI").is_ok_and(|value| !value.is_empty());
172 assert!(!running_in_ci, "Running in CI, {reason}.");
173 }
174
175 /// Tests if an external tool is installed and in the PATH
176 pub fn is_external_tool_installed(program_name: impl AsRef<OsStr>) -> bool {
177 Command::new(program_name)
178 .arg("--version")
179 .stdout(Stdio::null())
180 .status()
181 .is_ok()
182 }
183
184 #[derive(Debug)]
185 pub struct TestEnvironment {
186 temp_dir: TempDir,
187 test_backend_factory: TestBackendFactory,
188 }
189
190 impl TestEnvironment {
191 pub fn init() -> Self {
192 Self {
193 temp_dir: new_temp_dir(),
194 test_backend_factory: TestBackendFactory::default(),
195 }
196 }
197
198 pub fn root(&self) -> &Path {
199 self.temp_dir.path()
200 }
201
202 pub fn default_backend_factories(&self) -> StoreFactories {
203 let mut factories = default_backend_factories();
204 factories.add_backend("test", {
205 let factory = self.test_backend_factory.clone();
206 Box::new(move |_settings, store_path| Ok(Box::new(factory.load(store_path))))
207 });
208 factories.add_backend(
209 SecretBackend::name(),
210 Box::new(|settings, store_path| {
211 Ok(Box::new(SecretBackend::load(settings, store_path)?))
212 }),
213 );
214 factories
215 }
216
217 pub fn load_repo_at_head(
218 &self,
219 settings: &UserSettings,
220 repo_path: &Path,
221 ) -> Arc<ReadonlyRepo> {
222 RepoLoader::init_from_file_system(settings, repo_path, &self.default_backend_factories())
223 .unwrap()
224 .load_at_head()
225 .block_on()
226 .unwrap()
227 }
228 }
229
230 pub struct TestRepo {
231 pub env: TestEnvironment,
232 pub repo: Arc<ReadonlyRepo>,
233 repo_path: PathBuf,
234 }
235
236 #[derive(PartialEq, Eq, Copy, Clone)]
237 pub enum TestRepoBackend {
238 Git,
239 Simple,
240 Test,
241 }
242
243 impl TestRepoBackend {
244 fn init_backend(
245 &self,
246 env: &TestEnvironment,
247 settings: &UserSettings,
248 store_path: &Path,
249 ) -> Result<Box<dyn Backend>, BackendInitError> {
250 match self {
251 Self::Git => Ok(Box::new(GitBackend::init_internal(
252 settings,
253 store_path,
254 gix::hash::Kind::default(),
255 )?)),
256 Self::Simple => Ok(Box::new(SimpleBackend::init(store_path))),
257 Self::Test => Ok(Box::new(env.test_backend_factory.init(store_path))),
258 }
259 }
260 }
261
262 impl TestRepo {
263 pub fn init() -> Self {
264 Self::init_with_backend(TestRepoBackend::Test)
265 }
266
267 pub fn init_with_backend(backend: TestRepoBackend) -> Self {
268 Self::init_with_backend_and_settings(backend, &user_settings())
269 }
270
271 pub fn init_with_settings(settings: &UserSettings) -> Self {
272 Self::init_with_backend_and_settings(TestRepoBackend::Test, settings)
273 }
274
275 pub fn init_with_backend_and_settings(
276 backend: TestRepoBackend,
277 settings: &UserSettings,
278 ) -> Self {
279 let env = TestEnvironment::init();
280
281 let repo_dir = env.root().join("repo");
282 fs::create_dir(&repo_dir).unwrap();
283
284 let repo = ReadonlyRepo::init(
285 settings,
286 &repo_dir,
287 &|settings, store_path| backend.init_backend(&env, settings, store_path),
288 Signer::from_settings(settings).unwrap(),
289 ReadonlyRepo::default_op_store_initializer(),
290 ReadonlyRepo::default_op_heads_store_initializer(),
291 ReadonlyRepo::default_index_store_initializer(),
292 ReadonlyRepo::default_submodule_store_initializer(),
293 )
294 .block_on()
295 .unwrap();
296
297 Self {
298 env,
299 repo,
300 repo_path: repo_dir,
301 }
302 }
303
304 pub fn repo_path(&self) -> &Path {
305 &self.repo_path
306 }
307 }
308
309 pub struct TestWorkspace {
310 pub env: TestEnvironment,
311 pub workspace: Workspace,
312 pub repo: Arc<ReadonlyRepo>,
313 }
314
315 impl TestWorkspace {
316 pub fn init() -> Self {
317 Self::init_with_backend(TestRepoBackend::Test)
318 }
319
320 pub fn init_with_backend(backend: TestRepoBackend) -> Self {
321 Self::init_with_backend_and_settings(backend, &user_settings())
322 }
323
324 pub fn init_with_settings(settings: &UserSettings) -> Self {
325 Self::init_with_backend_and_settings(TestRepoBackend::Test, settings)
326 }
327
328 pub fn init_with_backend_and_settings(
329 backend: TestRepoBackend,
330 settings: &UserSettings,
331 ) -> Self {
332 let signer = Signer::from_settings(settings).unwrap();
333 Self::init_with_backend_and_signer(backend, signer, settings)
334 }
335
336 pub fn init_with_backend_and_signer(
337 backend: TestRepoBackend,
338 signer: Signer,
339 settings: &UserSettings,
340 ) -> Self {
341 let env = TestEnvironment::init();
342
343 let workspace_root = env.root().join("repo");
344 fs::create_dir(&workspace_root).unwrap();
345
346 let (workspace, repo) = Workspace::init_with_backend(
347 settings,
348 &workspace_root,
349 &|settings, store_path| backend.init_backend(&env, settings, store_path),
350 signer,
351 )
352 .block_on()
353 .unwrap();
354
355 Self {
356 env,
357 workspace,
358 repo,
359 }
360 }
361
362 pub fn init_colocated_git() -> Self {
363 let env = TestEnvironment::init();
364 let workspace_root = env.root().join("repo");
365 fs::create_dir(&workspace_root).unwrap();
366 let (workspace, repo) = Workspace::init_colocated_git(
367 &user_settings(),
368 &workspace_root,
369 gix::hash::Kind::default(),
370 )
371 .block_on()
372 .unwrap();
373 Self {
374 env,
375 workspace,
376 repo,
377 }
378 }
379
380 pub fn root_dir(&self) -> PathBuf {
381 self.env.root().join("repo").join("..")
382 }
383
384 pub fn repo_path(&self) -> &Path {
385 self.workspace.repo_path()
386 }
387
388 /// Snapshots the working copy and returns the tree. Updates the working
389 /// copy state on disk, but does not update the working-copy commit (no
390 /// new operation).
391 pub fn snapshot_with_options(
392 &mut self,
393 options: &SnapshotOptions,
394 ) -> Result<(MergedTree, SnapshotStats), SnapshotError> {
395 let mut locked_ws = self
396 .workspace
397 .start_working_copy_mutation()
398 .block_on()
399 .unwrap();
400 let (tree, stats) = locked_ws.locked_wc().snapshot(options).block_on()?;
401 // arbitrary operation id
402 locked_ws
403 .finish(self.repo.op_id().clone())
404 .block_on()
405 .unwrap();
406 Ok((tree, stats))
407 }
408
409 /// Like `snapshot_with_option()` but with default options
410 pub fn snapshot(&mut self) -> Result<MergedTree, SnapshotError> {
411 let (tree, _stats) = self.snapshot_with_options(&empty_snapshot_options())?;
412 Ok(tree)
413 }
414 }
415
416 pub fn commit_transactions(txs: Vec<Transaction>) -> Arc<ReadonlyRepo> {
417 let repo_loader = txs[0].base_repo().loader().clone();
418 let mut op_ids = vec![];
419 for tx in txs {
420 op_ids.push(tx.commit("test").block_on().unwrap().op_id().clone());
421 std::thread::sleep(std::time::Duration::from_millis(1));
422 }
423 let repo = repo_loader.load_at_head().block_on().unwrap();
424 // Test the setup. The assumption here is that the parent order matches the
425 // order in which they were merged (which currently matches the transaction
426 // commit order), so we want to know make sure they appear in a certain
427 // order, so the caller can decide the order by passing them to this
428 // function in a certain order.
429 assert_eq!(*repo.operation().parent_ids(), op_ids);
430 repo
431 }
432
433 pub fn repo_path_component(value: &str) -> &RepoPathComponent {
434 RepoPathComponent::new(value).unwrap()
435 }
436
437 pub fn repo_path(value: &str) -> &RepoPath {
438 RepoPath::from_internal_string(value).unwrap()
439 }
440
441 pub fn repo_path_buf(value: impl Into<String>) -> RepoPathBuf {
442 RepoPathBuf::from_internal_string(value).unwrap()
443 }
444
445 pub fn read_file(store: &Store, path: &RepoPath, id: &FileId) -> Vec<u8> {
446 let mut reader = store.read_file(path, id).block_on().unwrap();
447 let mut content = vec![];
448 reader.read_to_end(&mut content).block_on().unwrap();
449 content
450 }
451
452 pub fn write_file(store: &Store, path: &RepoPath, contents: &str) -> FileId {
453 store
454 .write_file(path, &mut contents.as_bytes())
455 .block_on()
456 .unwrap()
457 }
458
459 pub struct TestTreeBuilder {
460 store: Arc<Store>,
461 tree_builder: TreeBuilder,
462 }
463
464 impl TestTreeBuilder {
465 pub fn new(store: Arc<Store>) -> Self {
466 let tree_builder = TreeBuilder::new(store.clone(), store.empty_tree_id().clone());
467 Self {
468 store,
469 tree_builder,
470 }
471 }
472
473 pub fn file(
474 &mut self,
475 path: &RepoPath,
476 contents: impl AsRef<[u8]>,
477 ) -> TestTreeFileEntryBuilder<'_> {
478 TestTreeFileEntryBuilder {
479 tree_builder: &mut self.tree_builder,
480 path: path.to_owned(),
481 contents: contents.as_ref().to_vec(),
482 executable: false,
483 copy_history: None,
484 copy_id: CopyId::placeholder(),
485 }
486 }
487
488 pub fn symlink(&mut self, path: &RepoPath, target: &str) {
489 let id = self.store.write_symlink(path, target).block_on().unwrap();
490 self.tree_builder
491 .set(path.to_owned(), TreeValue::Symlink(id));
492 }
493
494 pub fn submodule(&mut self, path: &RepoPath, commit: CommitId) {
495 self.tree_builder
496 .set(path.to_owned(), TreeValue::GitSubmodule(commit));
497 }
498
499 pub fn write_single_tree(self) -> Tree {
500 let id = self.tree_builder.write_tree().block_on().unwrap();
501 self.store
502 .get_tree(RepoPathBuf::root(), &id)
503 .block_on()
504 .unwrap()
505 }
506
507 pub fn write_merged_tree(self) -> MergedTree {
508 let id = self.tree_builder.write_tree().block_on().unwrap();
509 MergedTree::resolved(self.store, id)
510 }
511 }
512
513 pub struct TestTreeFileEntryBuilder<'a> {
514 tree_builder: &'a mut TreeBuilder,
515 path: RepoPathBuf,
516 contents: Vec<u8>,
517 executable: bool,
518 copy_history: Option<CopyHistory>,
519 copy_id: CopyId,
520 }
521
522 impl TestTreeFileEntryBuilder<'_> {
523 pub fn executable(mut self, executable: bool) -> Self {
524 self.executable = executable;
525 self
526 }
527
528 /// Setting an explicit `CopyHistory` overrides any previous `.copy_id()`
529 /// calls.
530 pub fn copy_history(mut self, copy_history: &CopyHistory) -> Self {
531 self.copy_history = Some(copy_history.clone());
532 self.copy_id = CopyId::placeholder();
533 self
534 }
535
536 /// Setting an explicit `CopyId` overrides any previous `.copy_history()`
537 /// calls.
538 pub fn copy_id(mut self, copy_id: CopyId) -> Self {
539 self.copy_id = copy_id;
540 self.copy_history = None;
541 self
542 }
543 }
544
545 impl Drop for TestTreeFileEntryBuilder<'_> {
546 fn drop(&mut self) {
547 let id = self
548 .tree_builder
549 .store()
550 .write_file(&self.path, &mut self.contents.as_slice())
551 .block_on()
552 .unwrap();
553 let path = std::mem::replace(&mut self.path, RepoPathBuf::root());
554 let copy_id = if let Some(copy_history) = self.copy_history.as_ref() {
555 self.tree_builder
556 .store()
557 .backend()
558 .write_copy(copy_history)
559 .block_on()
560 .unwrap()
561 } else {
562 self.copy_id.clone()
563 };
564 self.tree_builder.set(
565 path,
566 TreeValue::File {
567 id,
568 executable: self.executable,
569 copy_id,
570 },
571 );
572 }
573 }
574
575 pub struct TestThreeWayMergeTreeBuilder {
576 store: Arc<Store>,
577 base_builder: TestTreeBuilder,
578 parent1_builder: TestTreeBuilder,
579 parent2_builder: TestTreeBuilder,
580 }
581
582 impl TestThreeWayMergeTreeBuilder {
583 pub fn new(store: Arc<Store>) -> Self {
584 Self {
585 store: Arc::clone(&store),
586 base_builder: TestTreeBuilder::new(Arc::clone(&store)),
587 parent1_builder: TestTreeBuilder::new(Arc::clone(&store)),
588 parent2_builder: TestTreeBuilder::new(store),
589 }
590 }
591
592 pub fn base(&mut self) -> &mut TestTreeBuilder {
593 &mut self.base_builder
594 }
595
596 pub fn parent1(&mut self) -> &mut TestTreeBuilder {
597 &mut self.parent1_builder
598 }
599
600 pub fn parent2(&mut self) -> &mut TestTreeBuilder {
601 &mut self.parent2_builder
602 }
603
604 pub fn write_merged_tree(self) -> MergedTree {
605 let tree_ids = [
606 self.parent1_builder,
607 self.base_builder,
608 self.parent2_builder,
609 ]
610 .map(|builder| builder.write_single_tree().id().clone());
611 MergedTree::new(
612 self.store.clone(),
613 Merge::from_vec(tree_ids.to_vec()),
614 ConflictLabels::unlabeled(),
615 )
616 }
617 }
618
619 pub fn create_single_tree_with(
620 repo: &Arc<ReadonlyRepo>,
621 build: impl FnOnce(&mut TestTreeBuilder),
622 ) -> Tree {
623 let mut builder = TestTreeBuilder::new(repo.store().clone());
624 build(&mut builder);
625 builder.write_single_tree()
626 }
627
628 pub fn create_single_tree(repo: &Arc<ReadonlyRepo>, path_contents: &[(&RepoPath, &str)]) -> Tree {
629 create_single_tree_with(repo, |builder| {
630 for (path, contents) in path_contents {
631 builder.file(path, contents);
632 }
633 })
634 }
635
636 pub fn create_tree_with(
637 repo: &Arc<ReadonlyRepo>,
638 build: impl FnOnce(&mut TestTreeBuilder),
639 ) -> MergedTree {
640 let mut builder = TestTreeBuilder::new(repo.store().clone());
641 build(&mut builder);
642 builder.write_merged_tree()
643 }
644
645 pub fn create_tree(repo: &Arc<ReadonlyRepo>, path_contents: &[(&RepoPath, &str)]) -> MergedTree {
646 create_tree_with(repo, |builder| {
647 for (path, contents) in path_contents {
648 builder.file(path, contents);
649 }
650 })
651 }
652
653 pub fn create_tree_with_copy_history(
654 repo: &Arc<ReadonlyRepo>,
655 histories: &HashMap<RepoPathBuf, CopyHistory>,
656 path_contents: &[(&RepoPath, &str)],
657 ) -> MergedTree {
658 create_tree_with(repo, |builder| {
659 for (path, contents) in path_contents {
660 builder.file(path, contents).copy_history(&histories[*path]);
661 }
662 })
663 }
664
665 pub fn create_tree_with_copy_id(
666 repo: &Arc<ReadonlyRepo>,
667 path_contents_id: &[(&RepoPath, &str, &CopyId)],
668 ) -> MergedTree {
669 create_tree_with(repo, |builder| {
670 for (path, contents, id) in path_contents_id {
671 builder.file(path, contents).copy_id((*id).clone());
672 }
673 })
674 }
675
676 #[must_use]
677 pub fn create_random_tree(repo: &Arc<ReadonlyRepo>) -> MergedTree {
678 let number = rand::random::<u32>();
679 let path = repo_path_buf(format!("file{number}"));
680 create_tree_with(repo, |builder| {
681 builder.file(&path, "contents");
682 })
683 }
684
685 pub fn create_random_commit(mut_repo: &mut MutableRepo) -> CommitBuilder<'_> {
686 let tree = create_random_tree(mut_repo.base_repo());
687 let number = rand::random::<u32>();
688 mut_repo
689 .new_commit(vec![mut_repo.store().root_commit_id().clone()], tree)
690 .set_description(format!("random commit {number}"))
691 }
692
693 pub fn commit_with_tree(store: &Arc<Store>, tree: MergedTree) -> Commit {
694 let signature = Signature {
695 name: "Some One".to_string(),
696 email: "[email protected]".to_string(),
697 timestamp: Timestamp {
698 timestamp: MillisSinceEpoch(0),
699 tz_offset: 0,
700 },
701 };
702 let (root_tree, conflict_labels) = tree.into_tree_ids_and_labels();
703 let commit = backend::Commit {
704 parents: vec![store.root_commit_id().clone()],
705 predecessors: vec![],
706 root_tree,
707 conflict_labels: conflict_labels.into_merge(),
708 change_id: ChangeId::from_hex("abcd"),
709 description: "description".to_string(),
710 author: signature.clone(),
711 committer: signature,
712 secure_sig: None,
713 };
714 store.write_commit(commit, None).block_on().unwrap()
715 }
716
717 pub fn dump_tree(merged_tree: &MergedTree) -> String {
718 use std::fmt::Write as _;
719 let store = merged_tree.store();
720 let mut buf = String::new();
721 let trees = merged_tree.trees().block_on().unwrap();
722 writeln!(&mut buf, "merged tree (sides: {})", trees.num_sides()).unwrap();
723 for tree in &trees {
724 writeln!(&mut buf, " tree {}", tree.id()).unwrap();
725 for (path, entry) in tree.entries_matching(&EverythingMatcher) {
726 match entry {
727 TreeValue::File {
728 id,
729 executable: _,
730 copy_id: _,
731 } => {
732 let file_buf = read_file(store, &path, &id);
733 let file_contents = String::from_utf8_lossy(&file_buf);
734 writeln!(&mut buf, " file {path:?} ({id}): {file_contents:?}").unwrap();
735 }
736 TreeValue::Symlink(id) => {
737 writeln!(&mut buf, " symlink {path:?} ({id})").unwrap();
738 }
739 TreeValue::GitSubmodule(id) => {
740 writeln!(&mut buf, " submodule {path:?} ({id})").unwrap();
741 }
742 _ => {
743 writeln!(&mut buf, " entry {path:?}: {entry:?}").unwrap();
744 }
745 }
746 }
747 }
748 buf
749 }
750
751 #[macro_export]
752 macro_rules! assert_tree_eq {
753 ($left_tree:expr, $right_tree:expr $(,)?) => {
754 assert_tree_eq!($left_tree, $right_tree, "trees are different")
755 };
756 ($left_tree:expr, $right_tree:expr, $($args:tt)+) => {{
757 let left_tree: &::jj_lib::merged_tree::MergedTree = &$left_tree;
758 let right_tree: &::jj_lib::merged_tree::MergedTree = &$right_tree;
759 assert_eq!(
760 left_tree.tree_ids_and_labels(),
761 right_tree.tree_ids_and_labels(),
762 "{}:\n left: {}\nright: {}",
763 format_args!($($args)*),
764 $crate::dump_tree(left_tree),
765 $crate::dump_tree(right_tree),
766 )
767 }};
768 }
769
770 pub fn write_random_commit(mut_repo: &mut MutableRepo) -> Commit {
771 write_random_commit_with_parents(mut_repo, &[])
772 }
773
774 pub fn write_random_commit_with_parents(mut_repo: &mut MutableRepo, parents: &[&Commit]) -> Commit {
775 let parents = if parents.is_empty() {
776 &[&mut_repo.store().root_commit()]
777 } else {
778 parents
779 };
780 create_random_commit(mut_repo)
781 .set_parents(parents.iter().map(|commit| commit.id().clone()).collect())
782 .write_unwrap()
783 }
784
785 pub fn write_random_commit_with_parents_and_description(
786 mut_repo: &mut MutableRepo,
787 parents: &[&Commit],
788 description: &str,
789 ) -> Commit {
790 let parents = if parents.is_empty() {
791 &[&mut_repo.store().root_commit()]
792 } else {
793 parents
794 };
795 create_random_commit(mut_repo)
796 .set_description(description)
797 .set_parents(parents.iter().map(|commit| commit.id().clone()).collect())
798 .write_unwrap()
799 }
800
801 pub fn write_working_copy_file(workspace_root: &Path, path: &RepoPath, contents: impl AsRef<[u8]>) {
802 let path = path.to_fs_path(workspace_root).unwrap();
803 if let Some(parent) = path.parent() {
804 fs::create_dir_all(parent).unwrap();
805 }
806 let mut file = OpenOptions::new()
807 .write(true)
808 .create(true)
809 .truncate(true)
810 .open(path)
811 .unwrap();
812 file.write_all(contents.as_ref()).unwrap();
813 }
814
815 /// Rebase descendants of the rewritten commits. Returns map of original commit
816 /// ID to rebased (or abandoned parent) commit ID.
817 pub fn rebase_descendants_with_options_return_map(
818 repo: &mut MutableRepo,
819 options: &RebaseOptions,
820 ) -> HashMap<CommitId, CommitId> {
821 let immutable = RevsetExpression::none();
822 let mut rebased: HashMap<CommitId, CommitId> = HashMap::new();
823 repo.rebase_descendants_with_options(&immutable, options, |old_commit, rebased_commit| {
824 let old_commit_id = old_commit.id().clone();
825 let new_commit_id = match rebased_commit {
826 RebasedCommit::Rewritten(new_commit) => new_commit.id().clone(),
827 RebasedCommit::Abandoned { parent_id } => parent_id,
828 };
829 rebased.insert(old_commit_id, new_commit_id);
830 })
831 .block_on()
832 .unwrap();
833 rebased
834 }
835
836 fn assert_in_rebased_map(
837 repo: &impl Repo,
838 rebased: &HashMap<CommitId, CommitId>,
839 expected_old_commit: &Commit,
840 ) -> Commit {
841 let new_commit_id = rebased.get(expected_old_commit.id()).unwrap_or_else(|| {
842 panic!(
843 "Expected commit to have been rebased: {}",
844 expected_old_commit.id().hex()
845 )
846 });
847 repo.store().get_commit(new_commit_id).unwrap().clone()
848 }
849
850 pub fn assert_rebased_onto(
851 repo: &impl Repo,
852 rebased: &HashMap<CommitId, CommitId>,
853 expected_old_commit: &Commit,
854 expected_new_parent_ids: &[&CommitId],
855 ) -> Commit {
856 let new_commit = assert_in_rebased_map(repo, rebased, expected_old_commit);
857 assert_eq!(
858 new_commit.parent_ids().to_vec(),
859 expected_new_parent_ids
860 .iter()
861 .map(|x| (*x).clone())
862 .collect_vec()
863 );
864 assert_eq!(new_commit.change_id(), expected_old_commit.change_id());
865 new_commit
866 }
867
868 /// Maps children of an abandoned commit to a new rebase target.
869 ///
870 /// If `expected_old_commit` was abandoned, the `rebased` map indicates the
871 /// commit the children of `expected_old_commit` should be rebased to, which
872 /// would have a different change id. This happens when the EmptyBehavior in
873 /// RebaseOptions is not the default; because of the details of the
874 /// implementation this returned parent commit is always singular.
875 pub fn assert_abandoned_with_parent(
876 repo: &impl Repo,
877 rebased: &HashMap<CommitId, CommitId>,
878 expected_old_commit: &Commit,
879 expected_new_parent_id: &CommitId,
880 ) -> Commit {
881 let new_parent_commit = assert_in_rebased_map(repo, rebased, expected_old_commit);
882 assert_eq!(new_parent_commit.id(), expected_new_parent_id);
883 assert_ne!(
884 new_parent_commit.change_id(),
885 expected_old_commit.change_id()
886 );
887 new_parent_commit
888 }
889
890 pub fn assert_no_forgotten_test_files(test_dir: &Path) {
891 // Parse the integration tests' main modules from the Cargo manifest.
892 let manifest = {
893 let file_path = test_dir.parent().unwrap().join("Cargo.toml");
894 let text = fs::read_to_string(&file_path).unwrap();
895 toml_edit::Document::parse(text).unwrap()
896 };
897 let test_bin_mods = if let Some(item) = manifest.get("test") {
898 let tables = item.as_array_of_tables().unwrap();
899 tables
900 .iter()
901 .map(|test| test.get("name").unwrap().as_str().unwrap().to_owned())
902 .collect()
903 } else {
904 vec![]
905 };
906
907 // Add to that all submodules which are declared in the main test modules via
908 // `mod`.
909 let mut test_mods: HashSet<_> = test_bin_mods
910 .iter()
911 .flat_map(|test_mod| {
912 let test_mod_path = test_dir.join(test_mod).with_extension("rs");
913 let test_mod_contents = fs::read_to_string(&test_mod_path).unwrap();
914 test_mod_contents
915 .lines()
916 .map(|line| line.trim_start_matches("pub "))
917 .filter_map(|line| line.strip_prefix("mod"))
918 .filter_map(|line| line.strip_suffix(";"))
919 .map(|line| line.trim().to_string())
920 .collect_vec()
921 })
922 .collect();
923 test_mods.extend(test_bin_mods);
924
925 // Gather list of Rust source files in test directory for comparison.
926 let test_mod_files: HashSet<_> = fs::read_dir(test_dir)
927 .unwrap()
928 .map(|entry| entry.unwrap().path())
929 .filter(|path| path.extension().is_some_and(|ext| ext == "rs"))
930 .filter_map(|path| {
931 path.file_stem()
932 .and_then(|stem| stem.to_os_string().into_string().ok())
933 })
934 .collect();
935
936 assert!(
937 test_mod_files.is_subset(&test_mods),
938 "the following test source files are not declared as integration tests nor included as \
939 submodules of one: {}",
940 test_mod_files
941 .difference(&test_mods)
942 .map(|mod_stem| format!("{mod_stem}.rs"))
943 .join(", "),
944 );
945 }
946
947 pub trait CommitBuilderExt {
948 fn write_unwrap(self) -> Commit;
949 }
950
951 impl CommitBuilderExt for CommitBuilder<'_> {
952 fn write_unwrap(self) -> Commit {
953 self.write().block_on().unwrap()
954 }
955 }
956
957 // Creates a CopyHistory graph and writes it to the test repo, returning the
958 // resulting IDs and Histories. Items in `paths_and_parents` can refer to parent
959 // paths occurring earlier in the list
960 pub fn write_copy_histories(
961 repo: &Arc<ReadonlyRepo>,
962 paths_and_parents: &[(&RepoPath, Vec<&RepoPath>)],
963 ) -> HashMap<RepoPathBuf, CopyHistory> {
964 let mut ids = HashMap::<RepoPathBuf, CopyId>::new();
965 let mut histories = HashMap::<RepoPathBuf, CopyHistory>::new();
966
967 for (path, parents) in paths_and_parents {
968 let history = CopyHistory {
969 current_path: (*path).to_owned(),
970 parents: parents.iter().map(|parent| ids[*parent].clone()).collect(),
971 salt: vec![],
972 };
973 let id = repo
974 .store()
975 .backend()
976 .write_copy(&history)
977 .block_on()
978 .unwrap();
979 ids.insert((*path).to_owned(), id);
980 histories.insert((*path).to_owned(), history);
981 }
982
983 histories
984 }
985
986 /// Returns true if the directory appears to be on a filesystem with strict
987 /// UTF-8 validation, as on ZFS with the `utf8only=on` property set.
988 #[cfg(unix)]
989 pub fn check_strict_utf8_fs(dir: &Path) -> bool {
990 use std::os::unix::ffi::OsStrExt as _;
991
992 let test_file_normal = tempfile::Builder::new()
993 .prefix(OsStr::from_bytes(b"strict-utf8-normal-"))
994 .tempfile_in(dir);
995 assert!(test_file_normal.is_ok());
996
997 let test_file_invalid = tempfile::Builder::new()
998 .prefix(OsStr::from_bytes(b"strict-utf8-\xe0-"))
999 .tempfile_in(dir);
1000 test_file_invalid.is_err()
1001 }