Debian Codegraph @

lib/tests/test_local_working_copy.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::convert::Infallible;
16 use std::fs::File;
17 use std::io;
18 #[cfg(unix)]
19 use std::os::unix::fs::PermissionsExt as _;
20 use std::path::Component;
21 use std::path::Path;
22 use std::path::PathBuf;
23 use std::sync::Arc;
24 use std::time::Duration;
25 use std::time::SystemTime;
26
27 use assert_matches::assert_matches;
28 use bstr::BString;
29 use futures::AsyncReadExt as _;
30 use gix::odb::pack::FindExt as _;
31 use indoc::indoc;
32 use itertools::Itertools as _;
33 use jj_lib::backend::CopyId;
34 use jj_lib::backend::TreeId;
35 use jj_lib::backend::TreeValue;
36 use jj_lib::conflict_labels::ConflictLabels;
37 use jj_lib::conflicts::ConflictMaterializeOptions;
38 use jj_lib::default_backend_factories::default_working_copy_factories;
39 use jj_lib::file_util;
40 use jj_lib::file_util::check_symlink_support;
41 use jj_lib::file_util::symlink_dir;
42 use jj_lib::file_util::symlink_file;
43 use jj_lib::files::FileMergeHunkLevel;
44 use jj_lib::fsmonitor::FsmonitorSettings;
45 use jj_lib::git::get_git_backend;
46 use jj_lib::gitignore::GitIgnoreFile;
47 use jj_lib::local_working_copy::LocalWorkingCopy;
48 use jj_lib::local_working_copy::TreeState;
49 use jj_lib::local_working_copy::TreeStateSettings;
50 use jj_lib::matchers::FilesMatcher;
51 use jj_lib::merge::Merge;
52 use jj_lib::merge::SameChange;
53 use jj_lib::merged_tree::MergedTree;
54 use jj_lib::merged_tree_builder::MergedTreeBuilder;
55 use jj_lib::op_store::OperationId;
56 use jj_lib::ref_name::WorkspaceName;
57 use jj_lib::repo::ReadonlyRepo;
58 use jj_lib::repo::Repo as _;
59 use jj_lib::repo_path::RepoPath;
60 use jj_lib::repo_path::RepoPathBuf;
61 use jj_lib::rewrite::merge_commit_trees;
62 use jj_lib::secret_backend::SecretBackend;
63 use jj_lib::tree_builder::TreeBuilder;
64 use jj_lib::tree_merge::MergeOptions;
65 use jj_lib::working_copy::CheckoutError;
66 use jj_lib::working_copy::CheckoutStats;
67 use jj_lib::working_copy::SnapshotOptions;
68 use jj_lib::working_copy::UntrackedReason;
69 use jj_lib::working_copy::WorkingCopy as _;
70 use jj_lib::workspace::Workspace;
71 use pollster::FutureExt as _;
72 use test_case::test_case;
73 use testutils::CommitBuilderExt as _;
74 use testutils::TestRepo;
75 use testutils::TestRepoBackend;
76 use testutils::TestResult;
77 use testutils::TestWorkspace;
78 use testutils::assert_tree_eq;
79 use testutils::commit_with_tree;
80 use testutils::create_tree;
81 use testutils::create_tree_with;
82 use testutils::empty_snapshot_options;
83 use testutils::repo_path;
84 use testutils::repo_path_buf;
85 use testutils::repo_path_component;
86 use testutils::write_random_commit;
87
88 fn check_icase_fs(dir: &Path) -> bool {
89 let test_file = tempfile::Builder::new()
90 .prefix("icase-")
91 .tempfile_in(dir)
92 .unwrap();
93 let orig_name = test_file.path().file_name().unwrap().to_str().unwrap();
94 let upper_name = orig_name.to_ascii_uppercase();
95 assert_ne!(orig_name, upper_name);
96 dir.join(upper_name).try_exists().unwrap()
97 }
98
99 /// Returns true if the directory appears to ignore some unicode zero-width
100 /// characters, as in HFS+.
101 fn check_hfs_plus(dir: &Path) -> bool {
102 let test_file = tempfile::Builder::new()
103 .prefix("hfs-plus-\u{200c}-")
104 .tempfile_in(dir)
105 .unwrap();
106 let orig_name = test_file.path().file_name().unwrap().to_str().unwrap();
107 let stripped_name = orig_name.replace('\u{200c}', "");
108 assert_ne!(orig_name, stripped_name);
109 dir.join(stripped_name).try_exists().unwrap()
110 }
111
112 /// Returns true if the directory appears to support Windows short file names.
113 fn check_vfat(dir: &Path) -> bool {
114 let _test_file = tempfile::Builder::new()
115 .prefix("vfattest-")
116 .tempfile_in(dir)
117 .unwrap();
118 let short_name = "VFATTE~1";
119 dir.join(short_name).try_exists().unwrap()
120 }
121
122 fn to_owned_path_vec(paths: &[&RepoPath]) -> Vec<RepoPathBuf> {
123 paths.iter().map(|&path| path.to_owned()).collect()
124 }
125
126 #[test]
127 fn test_root() -> TestResult {
128 // Test that the working copy is clean and empty after init.
129 let mut test_workspace = TestWorkspace::init();
130
131 let wc = test_workspace.workspace.working_copy();
132 assert_eq!(wc.sparse_patterns()?, vec![RepoPathBuf::root()]);
133 let new_tree = test_workspace.snapshot()?;
134 let repo = &test_workspace.repo;
135 let wc_commit_id = repo
136 .view()
137 .get_wc_commit_id(WorkspaceName::DEFAULT)
138 .unwrap();
139 let wc_commit = repo.store().get_commit(wc_commit_id)?;
140 assert_tree_eq!(new_tree, wc_commit.tree());
141 assert_tree_eq!(new_tree, repo.store().empty_merged_tree());
142 Ok(())
143 }
144
145 #[test_case(TestRepoBackend::Simple ; "simple backend")]
146 #[test_case(TestRepoBackend::Git ; "git backend")]
147 fn test_checkout_file_transitions(backend: TestRepoBackend) -> TestResult {
148 // Tests switching between commits where a certain path is of one type in one
149 // commit and another type in the other. Includes a "missing" type, so we cover
150 // additions and removals as well.
151
152 let mut test_workspace = TestWorkspace::init_with_backend(backend);
153 let repo = &test_workspace.repo;
154 let store = repo.store().clone();
155 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
156
157 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
158 enum Kind {
159 Missing,
160 Normal,
161 Executable,
162 // Executable, but same content as Normal, to test transition where only the bit changed
163 ExecutableNormalContent,
164 Conflict,
165 // Same content as Executable, to test that transition preserves the executable bit
166 ConflictedExecutableContent,
167 Symlink,
168 Tree,
169 GitSubmodule,
170 }
171
172 fn write_path(
173 repo: &Arc<ReadonlyRepo>,
174 tree_builder: &mut MergedTreeBuilder,
175 kind: Kind,
176 path: &RepoPath,
177 ) {
178 let store = repo.store();
179 let copy_id = CopyId::placeholder();
180 let value = match kind {
181 Kind::Missing => Merge::absent(),
182 Kind::Normal => {
183 let id = testutils::write_file(store, path, "normal file contents");
184 Merge::normal(TreeValue::File {
185 id,
186 executable: false,
187 copy_id,
188 })
189 }
190 Kind::Executable => {
191 let id: jj_lib::backend::FileId =
192 testutils::write_file(store, path, "executable file contents");
193 Merge::normal(TreeValue::File {
194 id,
195 executable: true,
196 copy_id,
197 })
198 }
199 Kind::ExecutableNormalContent => {
200 let id = testutils::write_file(store, path, "normal file contents");
201 Merge::normal(TreeValue::File {
202 id,
203 executable: true,
204 copy_id,
205 })
206 }
207 Kind::Conflict => {
208 let base_file_id = testutils::write_file(store, path, "base file contents");
209 let left_file_id = testutils::write_file(store, path, "left file contents");
210 let right_file_id = testutils::write_file(store, path, "right file contents");
211 Merge::from_removes_adds(
212 vec![Some(TreeValue::File {
213 id: base_file_id,
214 executable: false,
215 copy_id: copy_id.clone(),
216 })],
217 vec![
218 Some(TreeValue::File {
219 id: left_file_id,
220 executable: false,
221 copy_id: copy_id.clone(),
222 }),
223 Some(TreeValue::File {
224 id: right_file_id,
225 executable: false,
226 copy_id: copy_id.clone(),
227 }),
228 ],
229 )
230 }
231 Kind::ConflictedExecutableContent => {
232 let base_file_id = testutils::write_file(store, path, "executable file contents");
233 let left_file_id =
234 testutils::write_file(store, path, "left executable file contents");
235 let right_file_id =
236 testutils::write_file(store, path, "right executable file contents");
237 Merge::from_removes_adds(
238 vec![Some(TreeValue::File {
239 id: base_file_id,
240 executable: true,
241 copy_id: copy_id.clone(),
242 })],
243 vec![
244 Some(TreeValue::File {
245 id: left_file_id,
246 executable: true,
247 copy_id: copy_id.clone(),
248 }),
249 Some(TreeValue::File {
250 id: right_file_id,
251 executable: true,
252 copy_id: copy_id.clone(),
253 }),
254 ],
255 )
256 }
257 Kind::Symlink => {
258 let id = store.write_symlink(path, "target").block_on().unwrap();
259 Merge::normal(TreeValue::Symlink(id))
260 }
261 Kind::Tree => {
262 let file_path = path.join(repo_path_component("file"));
263 let id = testutils::write_file(store, &file_path, "normal file contents");
264 let value = TreeValue::File {
265 id,
266 executable: false,
267 copy_id: copy_id.clone(),
268 };
269 tree_builder.set_or_remove(file_path, Merge::normal(value));
270 return;
271 }
272 Kind::GitSubmodule => {
273 let mut tx = repo.start_transaction();
274 let id = write_random_commit(tx.repo_mut()).id().clone();
275 tx.commit("test").block_on().unwrap();
276 Merge::normal(TreeValue::GitSubmodule(id))
277 }
278 };
279 tree_builder.set_or_remove(path.to_owned(), value);
280 }
281
282 let mut kinds = vec![
283 Kind::Missing,
284 Kind::Normal,
285 Kind::Executable,
286 Kind::ExecutableNormalContent,
287 Kind::Conflict,
288 Kind::ConflictedExecutableContent,
289 Kind::Tree,
290 ];
291 kinds.push(Kind::Symlink);
292 if backend == TestRepoBackend::Git {
293 kinds.push(Kind::GitSubmodule);
294 }
295 let mut left_tree_builder = MergedTreeBuilder::new(store.empty_merged_tree());
296 let mut right_tree_builder = MergedTreeBuilder::new(store.empty_merged_tree());
297 let mut files = vec![];
298 for left_kind in &kinds {
299 for right_kind in &kinds {
300 let path = repo_path_buf(format!("{left_kind:?}_{right_kind:?}"));
301 write_path(repo, &mut left_tree_builder, *left_kind, &path);
302 write_path(repo, &mut right_tree_builder, *right_kind, &path);
303 files.push((*left_kind, *right_kind, path.clone()));
304 }
305 }
306 let left_tree = left_tree_builder.write_tree().block_on()?;
307 let right_tree = right_tree_builder.write_tree().block_on()?;
308 let left_commit = commit_with_tree(&store, left_tree);
309 let right_commit = commit_with_tree(&store, right_tree.clone());
310
311 let ws = &mut test_workspace.workspace;
312 ws.check_out(repo.op_id().clone(), None, &left_commit)
313 .block_on()?;
314 ws.check_out(repo.op_id().clone(), None, &right_commit)
315 .block_on()?;
316
317 // Check that the working copy is clean.
318 let new_tree = test_workspace.snapshot()?;
319 assert_tree_eq!(new_tree, right_tree);
320
321 for (_left_kind, right_kind, path) in &files {
322 let wc_path = workspace_root.join(path.as_internal_file_string());
323 let maybe_metadata = wc_path.symlink_metadata();
324 match right_kind {
325 Kind::Missing => {
326 assert!(maybe_metadata.is_err(), "{path:?} should not exist");
327 }
328 Kind::Normal => {
329 assert!(maybe_metadata.is_ok(), "{path:?} should exist");
330 let metadata = maybe_metadata?;
331 assert!(metadata.is_file(), "{path:?} should be a file");
332 #[cfg(unix)]
333 assert_eq!(
334 metadata.permissions().mode() & 0o111,
335 0,
336 "{path:?} should not be executable"
337 );
338 }
339 Kind::Executable | Kind::ExecutableNormalContent => {
340 assert!(maybe_metadata.is_ok(), "{path:?} should exist");
341 let metadata = maybe_metadata?;
342 assert!(metadata.is_file(), "{path:?} should be a file");
343 #[cfg(unix)]
344 assert_ne!(
345 metadata.permissions().mode() & 0o111,
346 0,
347 "{path:?} should be executable"
348 );
349 }
350 Kind::Conflict => {
351 assert!(maybe_metadata.is_ok(), "{path:?} should exist");
352 let metadata = maybe_metadata?;
353 assert!(metadata.is_file(), "{path:?} should be a file");
354 #[cfg(unix)]
355 assert_eq!(
356 metadata.permissions().mode() & 0o111,
357 0,
358 "{path:?} should not be executable"
359 );
360 }
361 Kind::ConflictedExecutableContent => {
362 assert!(maybe_metadata.is_ok(), "{path:?} should exist");
363 let metadata = maybe_metadata?;
364 assert!(metadata.is_file(), "{path:?} should be a file");
365 #[cfg(unix)]
366 assert_ne!(
367 metadata.permissions().mode() & 0o111,
368 0,
369 "{path:?} should be executable"
370 );
371 }
372 Kind::Symlink => {
373 assert!(maybe_metadata.is_ok(), "{path:?} should exist");
374 let metadata = maybe_metadata?;
375 if check_symlink_support().unwrap_or(false) {
376 assert!(
377 metadata.file_type().is_symlink(),
378 "{path:?} should be a symlink"
379 );
380 }
381 }
382 Kind::Tree => {
383 assert!(maybe_metadata.is_ok(), "{path:?} should exist");
384 let metadata = maybe_metadata?;
385 assert!(metadata.is_dir(), "{path:?} should be a directory");
386 }
387 Kind::GitSubmodule => {
388 assert!(maybe_metadata.is_ok(), "{path:?} should exist");
389 let metadata = maybe_metadata?;
390 assert!(metadata.is_dir(), "{path:?} should be a directory");
391 }
392 }
393 }
394 Ok(())
395 }
396
397 #[test]
398 fn test_checkout_no_op() -> TestResult {
399 // Check out another commit with the same tree that's already checked out. The
400 // recorded operation should be updated even though the tree is unchanged.
401 let mut test_workspace = TestWorkspace::init();
402 let repo = test_workspace.repo.clone();
403
404 let file_path = repo_path("file");
405
406 let tree = create_tree(&repo, &[(file_path, "contents")]);
407 let commit1 = commit_with_tree(repo.store(), tree.clone());
408 let commit2 = commit_with_tree(repo.store(), tree);
409
410 let ws = &mut test_workspace.workspace;
411 ws.check_out(repo.op_id().clone(), None, &commit1)
412 .block_on()?;
413
414 // Test the setup: the file should exist on in the tree state.
415 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
416 assert!(wc.file_states()?.contains_path(file_path));
417
418 // Update to commit2 (same tree as commit1)
419 let new_op_id = OperationId::from_bytes(b"whatever");
420 let stats = ws.check_out(new_op_id.clone(), None, &commit2).block_on()?;
421 assert_eq!(stats, CheckoutStats::default());
422
423 // The tree state is unchanged but the recorded operation id is updated.
424 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
425 assert!(wc.file_states()?.contains_path(file_path));
426 assert_eq!(*wc.operation_id(), new_op_id);
427 Ok(())
428 }
429
430 // Test case for issue #2165
431 #[test]
432 fn test_conflict_subdirectory() -> TestResult {
433 let mut test_workspace = TestWorkspace::init();
434 let repo = &test_workspace.repo;
435
436 let path = repo_path("sub/file");
437 let empty_tree = create_tree(repo, &[]);
438 let tree1 = create_tree(repo, &[(path, "0")]);
439 let commit1 = commit_with_tree(repo.store(), tree1.clone());
440 let tree2 = create_tree(repo, &[(path, "1")]);
441 let merged_tree = MergedTree::merge(Merge::from_vec(vec![
442 (tree1, "tree 1".into()),
443 (empty_tree, "empty".into()),
444 (tree2, "tree 2".into()),
445 ]))
446 .block_on()?;
447 let merged_commit = commit_with_tree(repo.store(), merged_tree);
448 let repo = &test_workspace.repo;
449 let ws = &mut test_workspace.workspace;
450 ws.check_out(repo.op_id().clone(), None, &commit1)
451 .block_on()?;
452 ws.check_out(repo.op_id().clone(), None, &merged_commit)
453 .block_on()?;
454 Ok(())
455 }
456
457 #[test]
458 fn test_acl() -> TestResult {
459 let settings = testutils::user_settings();
460 let test_workspace =
461 TestWorkspace::init_with_backend_and_settings(TestRepoBackend::Git, &settings);
462 let repo = &test_workspace.repo;
463 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
464
465 let secret_modified_path = repo_path("secret/modified");
466 let secret_added_path = repo_path("secret/added");
467 let secret_deleted_path = repo_path("secret/deleted");
468 let became_secret_path = repo_path("file1");
469 let became_public_path = repo_path("file2");
470 let tree1 = create_tree(
471 repo,
472 &[
473 (secret_modified_path, "0"),
474 (secret_deleted_path, "0"),
475 (became_secret_path, "public"),
476 (became_public_path, "secret"),
477 ],
478 );
479 let tree2 = create_tree(
480 repo,
481 &[
482 (secret_modified_path, "1"),
483 (secret_added_path, "1"),
484 (became_secret_path, "secret"),
485 (became_public_path, "public"),
486 ],
487 );
488 let commit1 = commit_with_tree(repo.store(), tree1);
489 let commit2 = commit_with_tree(repo.store(), tree2);
490 SecretBackend::adopt_git_repo(&workspace_root);
491
492 let mut ws = Workspace::load(
493 &settings,
494 &workspace_root,
495 &test_workspace.env.default_backend_factories(),
496 &default_working_copy_factories(),
497 )?;
498 // Reload commits from the store associated with the workspace
499 let repo = ws.repo_loader().load_at(repo.operation()).block_on()?;
500 let commit1 = repo.store().get_commit(commit1.id())?;
501 let commit2 = repo.store().get_commit(commit2.id())?;
502
503 ws.check_out(repo.op_id().clone(), None, &commit1)
504 .block_on()?;
505 assert!(
506 !secret_modified_path
507 .to_fs_path_unchecked(&workspace_root)
508 .is_file()
509 );
510 assert!(
511 !secret_added_path
512 .to_fs_path_unchecked(&workspace_root)
513 .is_file()
514 );
515 assert!(
516 !secret_deleted_path
517 .to_fs_path_unchecked(&workspace_root)
518 .is_file()
519 );
520 assert!(
521 became_secret_path
522 .to_fs_path_unchecked(&workspace_root)
523 .is_file()
524 );
525 assert!(
526 !became_public_path
527 .to_fs_path_unchecked(&workspace_root)
528 .is_file()
529 );
530 ws.check_out(repo.op_id().clone(), None, &commit2)
531 .block_on()?;
532 assert!(
533 !secret_modified_path
534 .to_fs_path_unchecked(&workspace_root)
535 .is_file()
536 );
537 assert!(
538 !secret_added_path
539 .to_fs_path_unchecked(&workspace_root)
540 .is_file()
541 );
542 assert!(
543 !secret_deleted_path
544 .to_fs_path_unchecked(&workspace_root)
545 .is_file()
546 );
547 assert!(
548 !became_secret_path
549 .to_fs_path_unchecked(&workspace_root)
550 .is_file()
551 );
552 assert!(
553 became_public_path
554 .to_fs_path_unchecked(&workspace_root)
555 .is_file()
556 );
557 Ok(())
558 }
559
560 #[test]
561 fn test_tree_builder_file_directory_transition() -> TestResult {
562 let test_workspace = TestWorkspace::init();
563 let repo = &test_workspace.repo;
564 let store = repo.store();
565 let mut ws = test_workspace.workspace;
566 let workspace_root = ws.workspace_root().to_owned();
567 let mut check_out_tree = |tree_id: &TreeId| {
568 let tree = repo
569 .store()
570 .get_tree(RepoPathBuf::root(), tree_id)
571 .block_on()
572 .unwrap();
573 let commit = commit_with_tree(
574 repo.store(),
575 MergedTree::resolved(repo.store().clone(), tree.id().clone()),
576 );
577 ws.check_out(repo.op_id().clone(), None, &commit)
578 .block_on()
579 .unwrap();
580 };
581
582 let parent_path = repo_path("foo/bar");
583 let child_path = repo_path("foo/bar/baz");
584
585 // Add file at parent_path
586 let mut tree_builder = TreeBuilder::new(store.clone(), store.empty_tree_id().clone());
587 tree_builder.set(
588 parent_path.to_owned(),
589 TreeValue::File {
590 id: testutils::write_file(store, parent_path, ""),
591 executable: false,
592 copy_id: CopyId::placeholder(),
593 },
594 );
595 let tree_id = tree_builder.write_tree().block_on()?;
596 check_out_tree(&tree_id);
597 assert!(parent_path.to_fs_path_unchecked(&workspace_root).is_file());
598 assert!(!child_path.to_fs_path_unchecked(&workspace_root).exists());
599
600 // Turn parent_path into directory, add file at child_path
601 let mut tree_builder = TreeBuilder::new(store.clone(), tree_id);
602 tree_builder.remove(parent_path.to_owned());
603 tree_builder.set(
604 child_path.to_owned(),
605 TreeValue::File {
606 id: testutils::write_file(store, child_path, ""),
607 executable: false,
608 copy_id: CopyId::placeholder(),
609 },
610 );
611 let tree_id = tree_builder.write_tree().block_on()?;
612 check_out_tree(&tree_id);
613 assert!(parent_path.to_fs_path_unchecked(&workspace_root).is_dir());
614 assert!(child_path.to_fs_path_unchecked(&workspace_root).is_file());
615
616 // Turn parent_path back to file
617 let mut tree_builder = TreeBuilder::new(store.clone(), tree_id);
618 tree_builder.remove(child_path.to_owned());
619 tree_builder.set(
620 parent_path.to_owned(),
621 TreeValue::File {
622 id: testutils::write_file(store, parent_path, ""),
623 executable: false,
624 copy_id: CopyId::placeholder(),
625 },
626 );
627 let tree_id = tree_builder.write_tree().block_on()?;
628 check_out_tree(&tree_id);
629 assert!(parent_path.to_fs_path_unchecked(&workspace_root).is_file());
630 assert!(!child_path.to_fs_path_unchecked(&workspace_root).exists());
631 Ok(())
632 }
633
634 #[test]
635 fn test_conflicting_changes_on_disk() -> TestResult {
636 let test_workspace = TestWorkspace::init();
637 let repo = &test_workspace.repo;
638 let mut ws = test_workspace.workspace;
639 let workspace_root = ws.workspace_root().to_owned();
640
641 // file on disk conflicts with file in target commit
642 let file_file_path = repo_path("file-file");
643 // file on disk conflicts with directory in target commit
644 let file_dir_path = repo_path("file-dir");
645 // directory on disk conflicts with file in target commit
646 let dir_file_path = repo_path("dir-file");
647 let tree = create_tree(
648 repo,
649 &[
650 (file_file_path, "committed contents"),
651 (
652 &file_dir_path.join(repo_path_component("file")),
653 "committed contents",
654 ),
655 (dir_file_path, "committed contents"),
656 ],
657 );
658 let commit = commit_with_tree(repo.store(), tree);
659
660 std::fs::write(
661 file_file_path.to_fs_path_unchecked(&workspace_root),
662 "contents on disk",
663 )?;
664 std::fs::write(
665 file_dir_path.to_fs_path_unchecked(&workspace_root),
666 "contents on disk",
667 )?;
668 std::fs::create_dir(dir_file_path.to_fs_path_unchecked(&workspace_root))?;
669 std::fs::write(
670 dir_file_path
671 .to_fs_path_unchecked(&workspace_root)
672 .join("file"),
673 "contents on disk",
674 )?;
675
676 let stats = ws
677 .check_out(repo.op_id().clone(), None, &commit)
678 .block_on()?;
679 assert_eq!(
680 stats,
681 CheckoutStats {
682 updated_files: 0,
683 added_files: 3,
684 removed_files: 0,
685 skipped_files: 3
686 }
687 );
688
689 assert_eq!(
690 std::fs::read_to_string(file_file_path.to_fs_path_unchecked(&workspace_root)).ok(),
691 Some("contents on disk".to_string())
692 );
693 assert_eq!(
694 std::fs::read_to_string(file_dir_path.to_fs_path_unchecked(&workspace_root)).ok(),
695 Some("contents on disk".to_string())
696 );
697 assert_eq!(
698 std::fs::read_to_string(
699 dir_file_path
700 .to_fs_path_unchecked(&workspace_root)
701 .join("file")
702 )
703 .ok(),
704 Some("contents on disk".to_string())
705 );
706 Ok(())
707 }
708
709 #[test]
710 fn test_reset() -> TestResult {
711 let mut test_workspace = TestWorkspace::init();
712 let repo = &test_workspace.repo;
713 let op_id = repo.op_id().clone();
714 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
715
716 let ignored_path = repo_path("ignored");
717 let gitignore_path = repo_path(".gitignore");
718
719 let tree_without_file = create_tree(repo, &[(gitignore_path, "ignored\n")]);
720 let commit_without_file = commit_with_tree(repo.store(), tree_without_file.clone());
721 let tree_with_file = create_tree(
722 repo,
723 &[(gitignore_path, "ignored\n"), (ignored_path, "code")],
724 );
725 let commit_with_file = commit_with_tree(repo.store(), tree_with_file.clone());
726
727 let ws = &mut test_workspace.workspace;
728 let commit = commit_with_tree(repo.store(), tree_with_file.clone());
729 ws.check_out(repo.op_id().clone(), None, &commit)
730 .block_on()?;
731
732 // Test the setup: the file should exist on disk and in the tree state.
733 assert!(ignored_path.to_fs_path_unchecked(&workspace_root).is_file());
734 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
735 assert!(wc.file_states()?.contains_path(ignored_path));
736
737 // After we reset to the commit without the file, it should still exist on disk,
738 // but it should not be in the tree state, and it should not get added when we
739 // commit the working copy (because it's ignored).
740 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
741 locked_ws
742 .locked_wc()
743 .reset(&commit_without_file)
744 .block_on()?;
745 locked_ws.finish(op_id.clone()).block_on()?;
746 assert!(ignored_path.to_fs_path_unchecked(&workspace_root).is_file());
747 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
748 assert!(!wc.file_states()?.contains_path(ignored_path));
749 let new_tree = test_workspace.snapshot()?;
750 assert_tree_eq!(new_tree, tree_without_file);
751
752 // Now test the opposite direction: resetting to a commit where the file is
753 // tracked. The file should become tracked (even though it's ignored).
754 let ws = &mut test_workspace.workspace;
755 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
756 locked_ws.locked_wc().reset(&commit_with_file).block_on()?;
757 locked_ws.finish(op_id.clone()).block_on()?;
758 assert!(ignored_path.to_fs_path_unchecked(&workspace_root).is_file());
759 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
760 assert!(wc.file_states()?.contains_path(ignored_path));
761 let new_tree = test_workspace.snapshot()?;
762 assert_tree_eq!(new_tree, tree_with_file);
763 Ok(())
764 }
765
766 #[test]
767 fn test_checkout_discard() -> TestResult {
768 // Start a mutation, do a checkout, and then discard the mutation. The working
769 // copy files should remain changed, but the state files should not be
770 // written.
771 let mut test_workspace = TestWorkspace::init();
772 let repo = test_workspace.repo.clone();
773 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
774
775 let file1_path = repo_path("file1");
776 let file2_path = repo_path("file2");
777
778 let store = repo.store();
779 let tree1 = create_tree(&repo, &[(file1_path, "contents")]);
780 let tree2 = create_tree(&repo, &[(file2_path, "contents")]);
781 let commit1 = commit_with_tree(repo.store(), tree1);
782 let commit2 = commit_with_tree(repo.store(), tree2);
783
784 let ws = &mut test_workspace.workspace;
785 ws.check_out(repo.op_id().clone(), None, &commit1)
786 .block_on()?;
787 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
788 let state_path = wc.state_path().to_path_buf();
789
790 // Test the setup: the file should exist on disk and in the tree state.
791 assert!(file1_path.to_fs_path_unchecked(&workspace_root).is_file());
792 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
793 assert!(wc.file_states()?.contains_path(file1_path));
794
795 // Start a checkout
796 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
797 locked_ws.locked_wc().check_out(&commit2).block_on()?;
798 // The change should be reflected in the working copy but not saved
799 assert!(!file1_path.to_fs_path_unchecked(&workspace_root).is_file());
800 assert!(file2_path.to_fs_path_unchecked(&workspace_root).is_file());
801 let reloaded_wc = LocalWorkingCopy::load(
802 store.clone(),
803 workspace_root.clone(),
804 state_path.clone(),
805 repo.settings(),
806 )?;
807 assert!(reloaded_wc.file_states()?.contains_path(file1_path));
808 assert!(!reloaded_wc.file_states()?.contains_path(file2_path));
809 drop(locked_ws);
810
811 // The change should remain in the working copy, but not in memory and not saved
812 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
813 assert!(wc.file_states()?.contains_path(file1_path));
814 assert!(!wc.file_states()?.contains_path(file2_path));
815 assert!(!file1_path.to_fs_path_unchecked(&workspace_root).is_file());
816 assert!(file2_path.to_fs_path_unchecked(&workspace_root).is_file());
817 let reloaded_wc =
818 LocalWorkingCopy::load(store.clone(), workspace_root, state_path, repo.settings())?;
819 assert!(reloaded_wc.file_states()?.contains_path(file1_path));
820 assert!(!reloaded_wc.file_states()?.contains_path(file2_path));
821 Ok(())
822 }
823
824 #[test]
825 fn test_snapshot_file_directory_transition() -> TestResult {
826 let mut test_workspace = TestWorkspace::init();
827 let repo = test_workspace.repo.clone();
828 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
829 let to_ws_path = |path: &RepoPath| path.to_fs_path(&workspace_root).unwrap();
830
831 // file <-> directory transition at root and sub directories
832 let file1_path = repo_path("foo/bar");
833 let file2_path = repo_path("sub/bar/baz");
834 let file1p_path = file1_path.parent().unwrap();
835 let file2p_path = file2_path.parent().unwrap();
836
837 let tree1 = create_tree(&repo, &[(file1p_path, "1p"), (file2p_path, "2p")]);
838 let tree2 = create_tree(&repo, &[(file1_path, "1"), (file2_path, "2")]);
839 let commit1 = commit_with_tree(repo.store(), tree1.clone());
840 let commit2 = commit_with_tree(repo.store(), tree2.clone());
841
842 let ws = &mut test_workspace.workspace;
843 ws.check_out(repo.op_id().clone(), None, &commit1)
844 .block_on()?;
845
846 // file -> directory
847 std::fs::remove_file(to_ws_path(file1p_path))?;
848 std::fs::remove_file(to_ws_path(file2p_path))?;
849 std::fs::create_dir(to_ws_path(file1p_path))?;
850 std::fs::create_dir(to_ws_path(file2p_path))?;
851 std::fs::write(to_ws_path(file1_path), "1")?;
852 std::fs::write(to_ws_path(file2_path), "2")?;
853 let new_tree = test_workspace.snapshot()?;
854 assert_tree_eq!(new_tree, tree2);
855
856 let ws = &mut test_workspace.workspace;
857 ws.check_out(repo.op_id().clone(), None, &commit2)
858 .block_on()?;
859
860 // directory -> file
861 std::fs::remove_file(to_ws_path(file1_path))?;
862 std::fs::remove_file(to_ws_path(file2_path))?;
863 std::fs::remove_dir(to_ws_path(file1p_path))?;
864 std::fs::remove_dir(to_ws_path(file2p_path))?;
865 std::fs::write(to_ws_path(file1p_path), "1p")?;
866 std::fs::write(to_ws_path(file2p_path), "2p")?;
867 let new_tree = test_workspace.snapshot()?;
868 assert_tree_eq!(new_tree, tree1);
869 Ok(())
870 }
871
872 #[test]
873 fn test_materialize_snapshot_conflicted_files() -> TestResult {
874 let mut test_workspace = TestWorkspace::init();
875 let repo = &test_workspace.repo.clone();
876 let ws = &mut test_workspace.workspace;
877 let workspace_root = ws.workspace_root().to_owned();
878
879 // Create tree with 3-sided conflict, with file1 and file2 having different
880 // conflicts:
881 // file1: A - A + A - B + C
882 // file2: A - B + C - D + D
883 let file1_path = repo_path("file1");
884 let file2_path = repo_path("file2");
885 let side1_tree = create_tree(repo, &[(file1_path, "a\n"), (file2_path, "1\n")]);
886 let base1_tree = create_tree(repo, &[(file1_path, "a\n"), (file2_path, "2\n")]);
887 let side2_tree = create_tree(repo, &[(file1_path, "a\n"), (file2_path, "4\n")]);
888 let base2_tree = create_tree(repo, &[(file1_path, "b\n"), (file2_path, "3\n")]);
889 let side3_tree = create_tree(repo, &[(file1_path, "c\n"), (file2_path, "3\n")]);
890 let merged_tree = MergedTree::merge(Merge::from_vec(vec![
891 (side1_tree, "side 1".into()),
892 (base1_tree, "base 1".into()),
893 (side2_tree, "side 2".into()),
894 (base2_tree, "base 2".into()),
895 (side3_tree, "side 3".into()),
896 ]))
897 .block_on()?;
898 let commit = commit_with_tree(repo.store(), merged_tree.clone());
899
900 let stats = ws
901 .check_out(repo.op_id().clone(), None, &commit)
902 .block_on()?;
903 assert_eq!(
904 stats,
905 CheckoutStats {
906 updated_files: 0,
907 added_files: 2,
908 removed_files: 0,
909 skipped_files: 0
910 }
911 );
912
913 // Even though the tree-level conflict is a 3-sided conflict, each file is
914 // materialized as a 2-sided conflict.
915 let file1_value = merged_tree.path_value(file1_path).block_on()?;
916 let file2_value = merged_tree.path_value(file2_path).block_on()?;
917 assert_eq!(file1_value.num_sides(), 3);
918 assert_eq!(file2_value.num_sides(), 3);
919 insta::assert_snapshot!(
920 std::fs::read_to_string(file1_path.to_fs_path_unchecked(&workspace_root)).ok().unwrap(),
921 @r"
922 <<<<<<< conflict 1 of 1
923 %%%%%%% diff from: base 2
924 \\\\\\\ to: side 2
925 -b
926 +a
927 +++++++ side 3
928 c
929 >>>>>>> conflict 1 of 1 ends
930 ");
931 insta::assert_snapshot!(
932 std::fs::read_to_string(file2_path.to_fs_path_unchecked(&workspace_root)).ok().unwrap(),
933 @r"
934 <<<<<<< conflict 1 of 1
935 %%%%%%% diff from: base 1
936 \\\\\\\ to: side 1
937 -2
938 +1
939 +++++++ side 2
940 4
941 >>>>>>> conflict 1 of 1 ends
942 ");
943
944 // Editing a conflicted file should correctly propagate updates to each of
945 // the conflicting trees.
946 testutils::write_working_copy_file(
947 &workspace_root,
948 file1_path,
949 indoc! {"
950 <<<<<<< conflict 1 of 1
951 %%%%%%% diff from base to side #1
952 -b_edited
953 +a_edited
954 +++++++ side #2
955 c_edited
956 >>>>>>> conflict 1 of 1 ends
957 "},
958 );
959
960 let edited_tree = test_workspace.snapshot()?;
961 let edited_file_value = edited_tree.path_value(file1_path).block_on()?;
962 let edited_file_values = edited_file_value.iter().flatten().collect_vec();
963 assert_eq!(edited_file_values.len(), 5);
964
965 let get_file_id = |value: &TreeValue| match value {
966 TreeValue::File { id, .. } => id.clone(),
967 _ => panic!("unexpected value: {value:#?}"),
968 };
969 // The file IDs with indices 0 and 1 are the original unedited file values
970 // which were simplified.
971 let edited_file_file_id_0 = get_file_id(edited_file_values[0]);
972 assert_eq!(
973 testutils::read_file(repo.store(), file1_path, &edited_file_file_id_0),
974 b"a\n"
975 );
976 assert_eq!(edited_file_values[0], edited_file_values[1]);
977 let edited_file_file_id_2 = get_file_id(edited_file_values[2]);
978 assert_eq!(
979 testutils::read_file(repo.store(), file1_path, &edited_file_file_id_2),
980 b"a_edited\n"
981 );
982 let edited_file_file_id_3 = get_file_id(edited_file_values[3]);
983 assert_eq!(
984 testutils::read_file(repo.store(), file1_path, &edited_file_file_id_3),
985 b"b_edited\n"
986 );
987 let edited_file_file_id_4 = get_file_id(edited_file_values[4]);
988 assert_eq!(
989 testutils::read_file(repo.store(), file1_path, &edited_file_file_id_4),
990 b"c_edited\n"
991 );
992 Ok(())
993 }
994
995 #[test]
996 fn test_materialize_snapshot_unchanged_conflicts() -> TestResult {
997 let mut test_workspace = TestWorkspace::init();
998 let repo = &test_workspace.repo;
999 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1000
1001 // Both sides change "line 3" differently, right side deletes "line 5".
1002 let base_content = indoc! {"
1003 line 1
1004 line 2
1005 line 3
1006 line 4
1007 line 5
1008 "};
1009 let left_content = indoc! {"
1010 line 1
1011 line 2
1012 left 3.1
1013 left 3.2
1014 left 3.3
1015 line 4
1016 line 5
1017 "};
1018 let right_content = indoc! {"
1019 line 1
1020 line 2
1021 right 3.1
1022 line 4
1023 "};
1024 let file_path = repo_path("file");
1025 let base_tree = create_tree(repo, &[(file_path, base_content)]);
1026 let left_tree = create_tree(repo, &[(file_path, left_content)]);
1027 let right_tree = create_tree(repo, &[(file_path, right_content)]);
1028 let merged_tree = MergedTree::merge(Merge::from_vec(vec![
1029 (left_tree, "left".into()),
1030 (base_tree, "base".into()),
1031 (right_tree, "right".into()),
1032 ]))
1033 .block_on()?;
1034 let commit = commit_with_tree(repo.store(), merged_tree.clone());
1035
1036 test_workspace
1037 .workspace
1038 .check_out(repo.op_id().clone(), None, &commit)
1039 .block_on()?;
1040
1041 // "line 5" should be deleted from the checked-out content.
1042 let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
1043 let materialized_content = std::fs::read_to_string(&disk_path)?;
1044 insta::assert_snapshot!(materialized_content, @r"
1045 line 1
1046 line 2
1047 <<<<<<< conflict 1 of 1
1048 +++++++ left
1049 left 3.1
1050 left 3.2
1051 left 3.3
1052 %%%%%%% diff from: base
1053 \\\\\\\ to: right
1054 -line 3
1055 +right 3.1
1056 >>>>>>> conflict 1 of 1 ends
1057 line 4
1058 ");
1059
1060 let merged_tree_with_labels = MergedTree::new(
1061 merged_tree.store().clone(),
1062 merged_tree.tree_ids().clone(),
1063 ConflictLabels::from_vec(vec![
1064 "left label".into(),
1065 "base label".into(),
1066 "right label".into(),
1067 ]),
1068 );
1069 let commit_with_labels = commit_with_tree(repo.store(), merged_tree_with_labels.clone());
1070
1071 // When checking out a commit with the same conflicts but different labels, the
1072 // file should still be updated.
1073 let stats = test_workspace
1074 .workspace
1075 .check_out(repo.op_id().clone(), None, &commit_with_labels)
1076 .block_on()?;
1077 assert_eq!(
1078 stats,
1079 CheckoutStats {
1080 updated_files: 1,
1081 ..CheckoutStats::default()
1082 }
1083 );
1084 let materialized_content = std::fs::read_to_string(&disk_path)?;
1085 insta::assert_snapshot!(materialized_content, @r"
1086 line 1
1087 line 2
1088 <<<<<<< conflict 1 of 1
1089 +++++++ left label
1090 left 3.1
1091 left 3.2
1092 left 3.3
1093 %%%%%%% diff from: base label
1094 \\\\\\\ to: right label
1095 -line 3
1096 +right 3.1
1097 >>>>>>> conflict 1 of 1 ends
1098 line 4
1099 ");
1100
1101 // Update mtime to bypass file state comparison.
1102 let file = File::options().write(true).open(&disk_path)?;
1103 file.set_modified(SystemTime::now() + Duration::from_secs(1))?;
1104 drop(file);
1105
1106 // Unchanged snapshot should be identical to the original even if "line 5"
1107 // could be deleted from all sides.
1108 let snapshotted_tree = test_workspace.snapshot()?;
1109 assert_tree_eq!(snapshotted_tree, merged_tree_with_labels);
1110 Ok(())
1111 }
1112
1113 struct SnapshotModifiedMaterializedConflictTestConfig {
1114 base_contents: Option<&'static str>,
1115 parent1_contents: Option<&'static str>,
1116 parent2_contents: Option<&'static str>,
1117 // Edit the conflict contents of the conflict file. The input is the parsed hunks of the
1118 // conflict file. The contents of the conflict file will be replaced by the hunks returned.
1119 get_new_merge_hunks: fn(Vec<Merge<BString>>) -> Vec<Merge<BString>>,
1120
1121 expected_file_contents: Merge<Option<&'static str>>,
1122 }
1123
1124 #[test_case(SnapshotModifiedMaterializedConflictTestConfig {
1125 base_contents: None,
1126 parent1_contents: Some("parent1\n"),
1127 parent2_contents: Some("parent2\n"),
1128 get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
1129 for (i, side) in hunks[0].iter_mut().enumerate() {
1130 if i == 0 {
1131 side.extend(b"appended\n");
1132 }
1133 }
1134 hunks
1135 },
1136 expected_file_contents: Merge::from_vec(vec![
1137 Some("parent1\nappended\n"),
1138 None,
1139 Some("parent2\n"),
1140 ]),
1141 }; "no base contents parent 1 appended")]
1142 #[test_case(SnapshotModifiedMaterializedConflictTestConfig {
1143 base_contents: None,
1144 parent1_contents: Some("parent1\n"),
1145 parent2_contents: Some("parent2\n"),
1146 get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
1147 for (i, side) in hunks[0].iter_mut().enumerate() {
1148 if i == 2 {
1149 side.extend(b"appended\n");
1150 }
1151 }
1152 hunks
1153 },
1154 expected_file_contents: Merge::from_vec(vec![
1155 Some("parent1\n"),
1156 None,
1157 Some("parent2\nappended\n"),
1158 ]),
1159 }; "no base contents parent 2 appended")]
1160 #[test_case(SnapshotModifiedMaterializedConflictTestConfig {
1161 base_contents: None,
1162 parent1_contents: Some("parent1\n"),
1163 parent2_contents: Some("parent2\n"),
1164 get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
1165 for (i, side) in hunks[0].iter_mut().enumerate() {
1166 if i == 0 || i == 2 {
1167 side.extend(b"appended\n");
1168 }
1169 }
1170 hunks
1171 },
1172 expected_file_contents: Merge::from_vec(vec![
1173 Some("parent1\nappended\n"),
1174 None,
1175 Some("parent2\nappended\n"),
1176 ]),
1177 }; "no base contents both parents appended")]
1178 #[test_case(SnapshotModifiedMaterializedConflictTestConfig {
1179 base_contents: None,
1180 parent1_contents: Some("parent1\n"),
1181 parent2_contents: Some("parent2\n"),
1182 get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
1183 hunks.push(Merge::resolved(BString::from("appended\n")));
1184 hunks
1185 },
1186 expected_file_contents: Merge::from_vec(vec![
1187 Some("parent1\nappended\n"),
1188 // The file in the base change is also modified to preserve the materialized conflict.
1189 Some("appended\n"),
1190 Some("parent2\nappended\n"),
1191 ]),
1192 }; "no base contents a new resolved hunk appended")]
1193 #[test_case(SnapshotModifiedMaterializedConflictTestConfig {
1194 base_contents: None,
1195 parent1_contents: Some("parent1\n"),
1196 parent2_contents: Some("parent2\n"),
1197 get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
1198 for side in &mut hunks[0] {
1199 side.extend(b"appended\n");
1200 }
1201 hunks
1202 },
1203 expected_file_contents: Merge::from_vec(vec![
1204 Some("parent1\nappended\n"),
1205 // The file in the base change is also modified to preserve the materialized conflict.
1206 Some("appended\n"),
1207 Some("parent2\nappended\n"),
1208 ]),
1209 }; "no base contents all sides of the existing hunk appended")]
1210 #[test_case(SnapshotModifiedMaterializedConflictTestConfig {
1211 base_contents: None,
1212 parent1_contents: Some("parent1\n"),
1213 parent2_contents: Some("parent2\n"),
1214 get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
1215 hunks[0].iter_mut().nth(1).unwrap().extend(b"new base\n");
1216 hunks
1217 },
1218 // If the user adds contents to the absent side of a conflict hunk, we consider the conflict resolved.
1219 expected_file_contents: Merge::from_vec(vec![
1220 Some("parent1\n"),
1221 // The file in the base change is modified to preserve the materialized conflict.
1222 Some("new base\n"),
1223 Some("parent2\n"),
1224 ]),
1225 }; "no base contents base side appended only")]
1226 #[test_case(SnapshotModifiedMaterializedConflictTestConfig {
1227 base_contents: None,
1228 parent1_contents: Some("parent1\n"),
1229 parent2_contents: Some("parent2\n"),
1230 get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
1231 hunks.insert(0, Merge::resolved(BString::from("prepended\n")));
1232 hunks
1233 },
1234 expected_file_contents: Merge::from_vec(vec![
1235 Some("prepended\nparent1\n"),
1236 // The file in the base change is also modified to preserve the materialized conflict.
1237 Some("prepended\n"),
1238 Some("prepended\nparent2\n"),
1239 ]),
1240 }; "no base contents a new resolved hunk prepended")]
1241 #[test_case(SnapshotModifiedMaterializedConflictTestConfig {
1242 base_contents: Some("base\n"),
1243 parent1_contents: None,
1244 parent2_contents: Some("parent2\n"),
1245 get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
1246 hunks.push(Merge::resolved(BString::from("appended\n")));
1247 hunks
1248 },
1249 expected_file_contents: Merge::from_vec(vec![
1250 // The file in the parent1 change is also modified to preserve the materialized conflict.
1251 Some("appended\n"),
1252 Some("base\nappended\n"),
1253 Some("parent2\nappended\n"),
1254 ]),
1255 }; "file removed in parent1 a resolved hunk appended in merge")]
1256 #[test_case(SnapshotModifiedMaterializedConflictTestConfig {
1257 base_contents: Some("base\n"),
1258 parent1_contents: Some("parent1\n"),
1259 parent2_contents: None,
1260 get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
1261 hunks.push(Merge::resolved(BString::from("appended\n")));
1262 hunks
1263 },
1264 expected_file_contents: Merge::from_vec(vec![
1265 Some("parent1\nappended\n"),
1266 Some("base\nappended\n"),
1267 // The file in the parent2 change is also modified to preserve the materialized conflict.
1268 Some("appended\n"),
1269 ]),
1270 }; "file removed in parent2 a resolved hunk appended in merge")]
1271 fn test_snapshot_modified_materialized_conflict(
1272 SnapshotModifiedMaterializedConflictTestConfig {
1273 base_contents,
1274 parent1_contents,
1275 parent2_contents,
1276 get_new_merge_hunks,
1277 expected_file_contents,
1278 }: SnapshotModifiedMaterializedConflictTestConfig,
1279 ) -> TestResult {
1280 // In this test, we create the following commits, checkout the merge commit,
1281 // modify the merge contents, snapshot, and verify if the new merged tree is
1282 // correct.
1283
1284 // D
1285 // |\
1286 // B C
1287 // |/
1288 // A
1289
1290 // We can't use the tokio runtime here because the test backend will create
1291 // the tokio runtime in TestWorkspace::init, and tokio will panic if the
1292 // tokio runtime is dropped in an async context. See
1293 // https://docs.rs/tokio/1.47.1/tokio/runtime/struct.Handle.html#panics-2
1294 // for details.
1295 let mut test_workspace = TestWorkspace::init();
1296 let file_repo_path = repo_path("test-file");
1297 let file_disk_path = file_repo_path.to_fs_path(test_workspace.workspace.workspace_root())?;
1298
1299 // Create the commits with given contents.
1300 let mut tx = test_workspace.repo.start_transaction();
1301 let tree = create_tree(
1302 &test_workspace.repo,
1303 base_contents
1304 .map(|contents| (file_repo_path, contents))
1305 .as_slice(),
1306 );
1307 let base_commit = tx
1308 .repo_mut()
1309 .new_commit(
1310 vec![test_workspace.repo.store().root_commit_id().clone()],
1311 tree,
1312 )
1313 .write_unwrap();
1314 let tree = create_tree(
1315 &test_workspace.repo,
1316 &parent1_contents
1317 .map(|contents| (file_repo_path, contents))
1318 .into_iter()
1319 .collect::<Vec<_>>(),
1320 );
1321 let parent1_commit = tx
1322 .repo_mut()
1323 .new_commit(vec![base_commit.id().clone()], tree)
1324 .write_unwrap();
1325 let tree = create_tree(
1326 &test_workspace.repo,
1327 &parent2_contents
1328 .map(|contents| (file_repo_path, contents))
1329 .into_iter()
1330 .collect::<Vec<_>>(),
1331 );
1332 let parent2_commit = tx
1333 .repo_mut()
1334 .new_commit(vec![base_commit.id().clone()], tree)
1335 .write_unwrap();
1336 // Update the repo to pick up the new commits.
1337 test_workspace.repo = tx.commit("create parent commits").block_on()?;
1338
1339 // Create the merge commit.
1340 let tree =
1341 merge_commit_trees(&*test_workspace.repo, &[parent1_commit, parent2_commit]).block_on()?;
1342 let merge_commit = commit_with_tree(test_workspace.repo.store(), tree);
1343
1344 // Checkout the merge commit.
1345 test_workspace
1346 .workspace
1347 .check_out(test_workspace.repo.op_id().clone(), None, &merge_commit)
1348 .block_on()?;
1349 let contents = std::fs::read(&file_disk_path)?;
1350 let hunks =
1351 jj_lib::conflicts::parse_conflict(&contents, 2, jj_lib::conflicts::MIN_CONFLICT_MARKER_LEN)
1352 .unwrap();
1353 let hunks = get_new_merge_hunks(hunks);
1354 let mut new_contents = vec![];
1355 for hunk in hunks {
1356 jj_lib::conflicts::materialize_merge_result(
1357 &hunk,
1358 &ConflictLabels::unlabeled(),
1359 &mut new_contents,
1360 &ConflictMaterializeOptions {
1361 marker_style: jj_lib::conflicts::ConflictMarkerStyle::Diff,
1362 marker_len: None,
1363 merge: MergeOptions {
1364 hunk_level: FileMergeHunkLevel::Line,
1365 same_change: SameChange::Accept,
1366 },
1367 },
1368 )?;
1369 }
1370 std::fs::write(&file_disk_path, new_contents)?;
1371
1372 // Snapshot.
1373 let tree = test_workspace.snapshot()?;
1374 let actual_file_contents = tree
1375 .path_value(file_repo_path)
1376 .block_on()?
1377 .try_map_async(async |tree_value| {
1378 let Some(tree_value) = tree_value else {
1379 return Ok::<_, Infallible>(None);
1380 };
1381 let TreeValue::File { id, .. } = tree_value else {
1382 panic!("All sides of the conflict should be either a file or absent.");
1383 };
1384 let mut contents = vec![];
1385 test_workspace
1386 .repo
1387 .store()
1388 .read_file(file_repo_path, id)
1389 .await
1390 .unwrap()
1391 .read_to_end(&mut contents)
1392 .await
1393 .unwrap();
1394 Ok::<_, Infallible>(Some(String::from_utf8(contents).unwrap()))
1395 })
1396 .block_on()?;
1397 let expected_file_contents =
1398 expected_file_contents.map(|contents| contents.as_deref().map(str::to_string));
1399 assert_eq!(actual_file_contents, expected_file_contents);
1400 Ok(())
1401 }
1402
1403 #[test]
1404 fn test_snapshot_racy_timestamps() -> TestResult {
1405 // Tests that file modifications are detected even if they happen the same
1406 // millisecond as the updated working copy state.
1407 let mut test_workspace = TestWorkspace::init();
1408 let repo = &test_workspace.repo;
1409 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1410
1411 let file_path = workspace_root.join("file");
1412 let mut previous_tree = repo.store().empty_merged_tree();
1413 for i in 0..100 {
1414 std::fs::write(&file_path, format!("contents {i}").as_bytes())?;
1415 let mut locked_ws = test_workspace
1416 .workspace
1417 .start_working_copy_mutation()
1418 .block_on()?;
1419 let (new_tree, _stats) = locked_ws
1420 .locked_wc()
1421 .snapshot(&empty_snapshot_options())
1422 .block_on()?;
1423 assert_ne!(new_tree.tree_ids(), previous_tree.tree_ids());
1424 previous_tree = new_tree;
1425 }
1426 Ok(())
1427 }
1428
1429 #[cfg(unix)]
1430 #[test]
1431 fn test_snapshot_special_file() -> TestResult {
1432 // Tests that we ignore when special files (such as sockets and pipes) exist on
1433 // disk.
1434 let mut test_workspace = TestWorkspace::init();
1435 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1436 let ws = &mut test_workspace.workspace;
1437
1438 let file1_path = repo_path("file1");
1439 let file1_disk_path = file1_path.to_fs_path_unchecked(&workspace_root);
1440 std::fs::write(&file1_disk_path, "contents".as_bytes())?;
1441 let file2_path = repo_path("file2");
1442 let file2_disk_path = file2_path.to_fs_path_unchecked(&workspace_root);
1443 std::fs::write(file2_disk_path, "contents".as_bytes())?;
1444
1445 let fifo_disk_path = workspace_root.join("fifo");
1446 nix::unistd::mkfifo(&fifo_disk_path, nix::sys::stat::Mode::S_IRWXU)?;
1447 assert!(fifo_disk_path.exists());
1448 assert!(!fifo_disk_path.is_file());
1449
1450 // Snapshot the working copy with the socket file
1451 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
1452 let (tree, _stats) = locked_ws
1453 .locked_wc()
1454 .snapshot(&empty_snapshot_options())
1455 .block_on()?;
1456 locked_ws
1457 .finish(OperationId::from_hex("abc123"))
1458 .block_on()?;
1459 // Only the regular files should be in the tree
1460 assert_eq!(
1461 tree.entries().map(|(path, _value)| path).collect_vec(),
1462 to_owned_path_vec(&[file1_path, file2_path])
1463 );
1464 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
1465 assert_eq!(
1466 wc.file_states()?.paths().collect_vec(),
1467 vec![file1_path, file2_path]
1468 );
1469
1470 // Replace a regular file by a socket and snapshot the working copy again
1471 std::fs::remove_file(&file1_disk_path)?;
1472 nix::unistd::mkfifo(&file1_disk_path, nix::sys::stat::Mode::S_IRWXU)?;
1473 let tree = test_workspace.snapshot()?;
1474 // Only the regular file should be in the tree
1475 assert_eq!(
1476 tree.entries().map(|(path, _value)| path).collect_vec(),
1477 to_owned_path_vec(&[file2_path])
1478 );
1479 let ws = &mut test_workspace.workspace;
1480 let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
1481 assert_eq!(wc.file_states()?.paths().collect_vec(), vec![file2_path]);
1482 Ok(())
1483 }
1484
1485 #[cfg(unix)]
1486 #[test]
1487 fn test_snapshot_non_utf8_path() -> TestResult {
1488 // Tests that paths that can't be represented as RepoPaths are skipped
1489 // instead of failing the whole snapshot. #9774
1490 use std::ffi::OsStr;
1491 use std::os::unix::ffi::OsStrExt as _;
1492
1493 let mut test_workspace = TestWorkspace::init();
1494 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1495
1496 if testutils::check_strict_utf8_fs(&workspace_root) {
1497 eprintln!(
1498 "Skipping test \"test_snapshot_non_utf8_path\" due to strict UTF-8 filesystem for \
1499 path {workspace_root:?}"
1500 );
1501 return Ok(());
1502 }
1503
1504 let file_path = repo_path("file");
1505 std::fs::write(file_path.to_fs_path_unchecked(&workspace_root), "contents")?;
1506 let bad_file_name = OsStr::from_bytes(b"file\xe0");
1507 std::fs::write(workspace_root.join(bad_file_name), "contents")?;
1508 let bad_dir_name = OsStr::from_bytes(b"dir\xe0");
1509 let bad_dir_disk_path = workspace_root.join(bad_dir_name);
1510 std::fs::create_dir(&bad_dir_disk_path)?;
1511 std::fs::write(bad_dir_disk_path.join("file"), "contents")?;
1512
1513 let ws = &mut test_workspace.workspace;
1514 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
1515 let (tree, stats) = locked_ws
1516 .locked_wc()
1517 .snapshot(&empty_snapshot_options())
1518 .block_on()?;
1519 locked_ws
1520 .finish(OperationId::from_hex("abc123"))
1521 .block_on()?;
1522
1523 // Only the path with a valid UTF-8 name should be in the tree. The
1524 // directory isn't descended into, so it's reported as a single path.
1525 assert_eq!(
1526 tree.entries().map(|(path, _value)| path).collect_vec(),
1527 to_owned_path_vec(&[file_path])
1528 );
1529 assert_eq!(
1530 stats.invalid_utf8_paths,
1531 [
1532 (RepoPathBuf::root(), bad_dir_name.to_owned()),
1533 (RepoPathBuf::root(), bad_file_name.to_owned()),
1534 ]
1535 .into()
1536 );
1537 assert!(stats.untracked_paths.is_empty());
1538 Ok(())
1539 }
1540
1541 #[test]
1542 fn test_gitignores() -> TestResult {
1543 // Tests that .gitignore files are respected.
1544
1545 let mut test_workspace = TestWorkspace::init();
1546 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1547
1548 let gitignore_path = repo_path(".gitignore");
1549 let added_path = repo_path("added");
1550 let modified_path = repo_path("modified");
1551 let removed_path = repo_path("removed");
1552 let ignored_path = repo_path("ignored");
1553 let subdir_modified_path = repo_path("dir/modified");
1554 let subdir_ignored_path = repo_path("dir/ignored");
1555
1556 testutils::write_working_copy_file(&workspace_root, gitignore_path, "ignored\n");
1557 testutils::write_working_copy_file(&workspace_root, modified_path, "1");
1558 testutils::write_working_copy_file(&workspace_root, removed_path, "1");
1559 std::fs::create_dir(workspace_root.join("dir"))?;
1560 testutils::write_working_copy_file(&workspace_root, subdir_modified_path, "1");
1561
1562 let tree1 = test_workspace.snapshot()?;
1563 let files1 = tree1.entries().map(|(name, _value)| name).collect_vec();
1564 assert_eq!(
1565 files1,
1566 to_owned_path_vec(&[
1567 gitignore_path,
1568 subdir_modified_path,
1569 modified_path,
1570 removed_path,
1571 ])
1572 );
1573
1574 testutils::write_working_copy_file(
1575 &workspace_root,
1576 gitignore_path,
1577 "ignored\nmodified\nremoved\n",
1578 );
1579 testutils::write_working_copy_file(&workspace_root, added_path, "2");
1580 testutils::write_working_copy_file(&workspace_root, modified_path, "2");
1581 std::fs::remove_file(removed_path.to_fs_path_unchecked(&workspace_root))?;
1582 testutils::write_working_copy_file(&workspace_root, ignored_path, "2");
1583 testutils::write_working_copy_file(&workspace_root, subdir_modified_path, "2");
1584 testutils::write_working_copy_file(&workspace_root, subdir_ignored_path, "2");
1585
1586 let tree2 = test_workspace.snapshot()?;
1587 let files2 = tree2.entries().map(|(name, _value)| name).collect_vec();
1588 assert_eq!(
1589 files2,
1590 to_owned_path_vec(&[
1591 gitignore_path,
1592 added_path,
1593 subdir_modified_path,
1594 modified_path,
1595 ])
1596 );
1597 Ok(())
1598 }
1599
1600 #[test]
1601 fn test_gitignores_walk() -> TestResult {
1602 // Tests that .gitignore files are respected.
1603
1604 let mut test_workspace = TestWorkspace::init();
1605 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1606
1607 let gitignore_path = repo_path(".gitignore");
1608 let ignored_path = repo_path("ignore_dir/file");
1609 let subdir_not_ignored_path = repo_path("subdir/ignore_dir/file");
1610
1611 let nested_gitignore_path = repo_path("nested/dir/.gitignore");
1612 let nested_ignored_path = repo_path("nested/dir/ignored");
1613 let also_ignored_path = repo_path("nested/dir/also_ignored");
1614 let nested_path = repo_path("nested/dir/ignore_dir");
1615
1616 testutils::write_working_copy_file(
1617 &workspace_root,
1618 gitignore_path,
1619 "/ignore_dir\n/**/also_ignored",
1620 );
1621 testutils::write_working_copy_file(&workspace_root, ignored_path, "1");
1622 testutils::write_working_copy_file(&workspace_root, subdir_not_ignored_path, "1");
1623
1624 testutils::write_working_copy_file(&workspace_root, nested_gitignore_path, "/ignored\n");
1625 testutils::write_working_copy_file(&workspace_root, nested_ignored_path, "2");
1626 testutils::write_working_copy_file(&workspace_root, also_ignored_path, "2");
1627 testutils::write_working_copy_file(&workspace_root, nested_path, "2");
1628
1629 let tree1 = test_workspace.snapshot()?;
1630 let files1 = tree1.entries().map(|(name, _value)| name).collect_vec();
1631 assert_eq!(
1632 files1,
1633 to_owned_path_vec(&[
1634 gitignore_path,
1635 nested_gitignore_path,
1636 nested_path,
1637 subdir_not_ignored_path,
1638 ])
1639 );
1640 Ok(())
1641 }
1642
1643 #[test]
1644 fn test_gitignores_in_ignored_dir() -> TestResult {
1645 // Tests that .gitignore files in an ignored directory are ignored, i.e. that
1646 // they cannot override the ignores from the parent
1647
1648 let mut test_workspace = TestWorkspace::init();
1649 let op_id = test_workspace.repo.op_id().clone();
1650 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1651
1652 let gitignore_path = repo_path(".gitignore");
1653 let nested_gitignore_path = repo_path("ignored/.gitignore");
1654 let ignored_path = repo_path("ignored/file");
1655
1656 let tree1 = create_tree(&test_workspace.repo, &[(gitignore_path, "ignored\n")]);
1657 let commit1 = commit_with_tree(test_workspace.repo.store(), tree1.clone());
1658 let ws = &mut test_workspace.workspace;
1659 ws.check_out(op_id.clone(), None, &commit1).block_on()?;
1660
1661 testutils::write_working_copy_file(&workspace_root, nested_gitignore_path, "!file\n");
1662 testutils::write_working_copy_file(&workspace_root, ignored_path, "contents");
1663
1664 let new_tree = test_workspace.snapshot()?;
1665 assert_tree_eq!(new_tree, tree1);
1666
1667 // The nested .gitignore is ignored even if it's tracked
1668 let tree2 = create_tree(
1669 &test_workspace.repo,
1670 &[
1671 (gitignore_path, "ignored\n"),
1672 (nested_gitignore_path, "!file\n"),
1673 ],
1674 );
1675 let commit2 = commit_with_tree(test_workspace.repo.store(), tree2.clone());
1676 let mut locked_ws = test_workspace
1677 .workspace
1678 .start_working_copy_mutation()
1679 .block_on()?;
1680 locked_ws.locked_wc().reset(&commit2).block_on()?;
1681 locked_ws
1682 .finish(OperationId::from_hex("abc123"))
1683 .block_on()?;
1684
1685 let new_tree = test_workspace.snapshot()?;
1686 assert_tree_eq!(new_tree, tree2);
1687 Ok(())
1688 }
1689
1690 #[test]
1691 fn test_gitignores_checkout_never_overwrites_ignored() -> TestResult {
1692 // Tests that a .gitignore'd file doesn't get overwritten if check out a commit
1693 // where the file is tracked.
1694
1695 let mut test_workspace = TestWorkspace::init();
1696 let repo = &test_workspace.repo;
1697 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1698
1699 // Write an ignored file called "modified" to disk
1700 let gitignore_path = repo_path(".gitignore");
1701 testutils::write_working_copy_file(&workspace_root, gitignore_path, "modified\n");
1702 let modified_path = repo_path("modified");
1703 testutils::write_working_copy_file(&workspace_root, modified_path, "garbage");
1704
1705 // Create a tree that adds the same file but with different contents
1706 let tree = create_tree(repo, &[(modified_path, "contents")]);
1707 let commit = commit_with_tree(repo.store(), tree);
1708
1709 // Now check out the tree that adds the file "modified" with contents
1710 // "contents". The exiting contents ("garbage") shouldn't be replaced in the
1711 // working copy.
1712 let ws = &mut test_workspace.workspace;
1713 assert!(
1714 ws.check_out(repo.op_id().clone(), None, &commit)
1715 .block_on()
1716 .is_ok()
1717 );
1718
1719 // Check that the old contents are in the working copy
1720 let path = workspace_root.join("modified");
1721 assert!(path.is_file());
1722 assert_eq!(std::fs::read(&path)?, b"garbage");
1723 Ok(())
1724 }
1725
1726 #[test]
1727 fn test_gitignores_ignored_directory_already_tracked() -> TestResult {
1728 // Tests that a .gitignore'd directory that already has a tracked file in it
1729 // does not get removed when snapshotting the working directory.
1730
1731 let mut test_workspace = TestWorkspace::init();
1732 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1733 let repo = test_workspace.repo.clone();
1734
1735 let gitignore_path = repo_path(".gitignore");
1736 let unchanged_normal_path = repo_path("ignored/unchanged_normal");
1737 let modified_normal_path = repo_path("ignored/modified_normal");
1738 let deleted_normal_path = repo_path("ignored/deleted_normal");
1739 let unchanged_executable_path = repo_path("ignored/unchanged_executable");
1740 let modified_executable_path = repo_path("ignored/modified_executable");
1741 let deleted_executable_path = repo_path("ignored/deleted_executable");
1742 let unchanged_symlink_path = repo_path("ignored/unchanged_symlink");
1743 let modified_symlink_path = repo_path("ignored/modified_symlink");
1744 let deleted_symlink_path = repo_path("ignored/deleted_symlink");
1745 let tree = create_tree_with(&repo, |builder| {
1746 builder.file(gitignore_path, "/ignored/\n");
1747 builder.file(unchanged_normal_path, "contents");
1748 builder.file(modified_normal_path, "contents");
1749 builder.file(deleted_normal_path, "contents");
1750 builder
1751 .file(unchanged_executable_path, "contents")
1752 .executable(true);
1753 builder
1754 .file(modified_executable_path, "contents")
1755 .executable(true);
1756 builder
1757 .file(deleted_executable_path, "contents")
1758 .executable(true);
1759 builder.symlink(unchanged_symlink_path, "contents");
1760 builder.symlink(modified_symlink_path, "contents");
1761 builder.symlink(deleted_symlink_path, "contents");
1762 });
1763 let commit = commit_with_tree(repo.store(), tree);
1764
1765 // Check out the tree with the files in `ignored/`
1766 let ws = &mut test_workspace.workspace;
1767 ws.check_out(repo.op_id().clone(), None, &commit)
1768 .block_on()?;
1769
1770 // Make some changes inside the ignored directory and check that they are
1771 // detected when we snapshot. The files that are still there should not be
1772 // deleted from the resulting tree.
1773 std::fs::write(
1774 modified_normal_path.to_fs_path_unchecked(&workspace_root),
1775 "modified",
1776 )?;
1777 std::fs::remove_file(deleted_normal_path.to_fs_path_unchecked(&workspace_root))?;
1778 std::fs::write(
1779 modified_executable_path.to_fs_path_unchecked(&workspace_root),
1780 "modified",
1781 )?;
1782 std::fs::remove_file(deleted_executable_path.to_fs_path_unchecked(&workspace_root))?;
1783 let fs_path = modified_symlink_path.to_fs_path_unchecked(&workspace_root);
1784 std::fs::remove_file(&fs_path)?;
1785 if check_symlink_support().unwrap_or(false) {
1786 symlink_file("modified", &fs_path)?;
1787 } else {
1788 std::fs::write(fs_path, "modified")?;
1789 }
1790 std::fs::remove_file(deleted_symlink_path.to_fs_path_unchecked(&workspace_root))?;
1791 let new_tree = test_workspace.snapshot()?;
1792 let expected_tree = create_tree_with(&repo, |builder| {
1793 builder.file(gitignore_path, "/ignored/\n");
1794 builder.file(unchanged_normal_path, "contents");
1795 builder.file(modified_normal_path, "modified");
1796 builder
1797 .file(unchanged_executable_path, "contents")
1798 .executable(true);
1799 builder
1800 .file(modified_executable_path, "modified")
1801 .executable(true);
1802 builder.symlink(unchanged_symlink_path, "contents");
1803 builder.symlink(modified_symlink_path, "modified");
1804 });
1805 assert_tree_eq!(new_tree, expected_tree);
1806 Ok(())
1807 }
1808
1809 #[test]
1810 fn test_dotgit_ignored() -> TestResult {
1811 // Tests that .git directories and files are always ignored (we could accept
1812 // them if the backend is not git).
1813
1814 let mut test_workspace = TestWorkspace::init();
1815 let store = test_workspace.repo.store().clone();
1816 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1817
1818 // Test with a .git/ directory (with a file in, since we don't write empty
1819 // trees)
1820 let dotgit_path = workspace_root.join(".git");
1821 std::fs::create_dir(&dotgit_path)?;
1822 testutils::write_working_copy_file(&workspace_root, repo_path(".git/file"), "contents");
1823 let new_tree = test_workspace.snapshot()?;
1824 let empty_tree = store.empty_merged_tree();
1825 assert_tree_eq!(new_tree, empty_tree);
1826 std::fs::remove_dir_all(&dotgit_path)?;
1827
1828 // Test with a .git file
1829 testutils::write_working_copy_file(&workspace_root, repo_path(".git"), "contents");
1830 let new_tree = test_workspace.snapshot()?;
1831 assert_tree_eq!(new_tree, empty_tree);
1832 std::fs::remove_file(workspace_root.join(".git"))?;
1833
1834 // Test a nested repository foo/ containing .git and f.
1835 let foo_path = workspace_root.join("foo");
1836 std::fs::create_dir(&foo_path)?;
1837 testutils::write_working_copy_file(&workspace_root, repo_path("foo/.git"), "");
1838 testutils::write_working_copy_file(&workspace_root, repo_path("foo/f"), "contents");
1839 let new_tree = test_workspace.snapshot()?;
1840 assert_tree_eq!(new_tree, empty_tree);
1841 std::fs::remove_dir_all(&foo_path)?;
1842 Ok(())
1843 }
1844
1845 #[test_case(""; "ignore nothing")]
1846 #[test_case("/*\n"; "ignore all")]
1847 fn test_git_submodule(gitignore_content: &str) -> TestResult {
1848 // Tests that git submodules are ignored.
1849
1850 let mut test_workspace = TestWorkspace::init_with_backend(TestRepoBackend::Git);
1851 let repo = test_workspace.repo.clone();
1852 let store = repo.store().clone();
1853 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
1854 let base_ignores = GitIgnoreFile::empty().chain(
1855 RepoPath::root(),
1856 Path::new(""),
1857 gitignore_content.as_bytes(),
1858 )?;
1859 let snapshot_options = SnapshotOptions {
1860 base_ignores,
1861 ..empty_snapshot_options()
1862 };
1863 let mut tx = repo.start_transaction();
1864
1865 // Add files in sub directory. Sub directories are traversed differently
1866 // depending on .gitignore. #5246
1867 let added_path = repo_path("sub/added");
1868 let submodule_path = repo_path("sub/module");
1869 let added_submodule_path = repo_path("sub/module/added");
1870
1871 let mut tree_builder = MergedTreeBuilder::new(store.empty_merged_tree());
1872
1873 tree_builder.set_or_remove(
1874 added_path.to_owned(),
1875 Merge::normal(TreeValue::File {
1876 id: testutils::write_file(repo.store(), added_path, "added\n"),
1877 executable: false,
1878 copy_id: CopyId::new(vec![]),
1879 }),
1880 );
1881
1882 let submodule_id1 = write_random_commit(tx.repo_mut()).id().clone();
1883
1884 tree_builder.set_or_remove(
1885 submodule_path.to_owned(),
1886 Merge::normal(TreeValue::GitSubmodule(submodule_id1)),
1887 );
1888
1889 let tree_id1 = tree_builder.write_tree().block_on()?;
1890 let commit1 = commit_with_tree(repo.store(), tree_id1.clone());
1891
1892 let mut tree_builder = MergedTreeBuilder::new(tree_id1.clone());
1893 let submodule_id2 = write_random_commit(tx.repo_mut()).id().clone();
1894 tree_builder.set_or_remove(
1895 submodule_path.to_owned(),
1896 Merge::normal(TreeValue::GitSubmodule(submodule_id2)),
1897 );
1898 let tree_id2 = tree_builder.write_tree().block_on()?;
1899 let commit2 = commit_with_tree(repo.store(), tree_id2.clone());
1900
1901 // A commit with a file instead of the submodule at the same path
1902 let mut tree_builder = MergedTreeBuilder::new(store.empty_merged_tree());
1903 tree_builder.set_or_remove(
1904 submodule_path.to_owned(),
1905 Merge::normal(TreeValue::File {
1906 id: testutils::write_file(
1907 repo.store(),
1908 submodule_path,
1909 "file with same path as submodule\n",
1910 ),
1911 executable: false,
1912 copy_id: CopyId::new(vec![]),
1913 }),
1914 );
1915 let tree_id3 = tree_builder.write_tree().block_on()?;
1916 let commit3_file_clash = commit_with_tree(repo.store(), tree_id3.clone());
1917
1918 let ws = &mut test_workspace.workspace;
1919 ws.check_out(repo.op_id().clone(), None, &commit1)
1920 .block_on()?;
1921
1922 testutils::write_working_copy_file(
1923 &workspace_root,
1924 added_submodule_path,
1925 "i am a file in a submodule\n",
1926 );
1927
1928 // Check that the files present in the submodule are not tracked
1929 // when we snapshot
1930 let (new_tree, _stats) = test_workspace.snapshot_with_options(&snapshot_options)?;
1931 assert_tree_eq!(new_tree, tree_id1);
1932
1933 // Check that the files in the submodule are not deleted
1934 let file_in_submodule_path = added_submodule_path.to_fs_path_unchecked(&workspace_root);
1935 assert!(
1936 file_in_submodule_path.metadata().is_ok(),
1937 "{file_in_submodule_path:?} should exist"
1938 );
1939
1940 // Check out new commit updating the submodule, which shouldn't fail because
1941 // of existing submodule files
1942 let ws = &mut test_workspace.workspace;
1943 ws.check_out(repo.op_id().clone(), None, &commit2)
1944 .block_on()?;
1945
1946 // Check that the files in the submodule are not deleted
1947 let file_in_submodule_path = added_submodule_path.to_fs_path_unchecked(&workspace_root);
1948 assert!(
1949 file_in_submodule_path.metadata().is_ok(),
1950 "{file_in_submodule_path:?} should exist"
1951 );
1952
1953 // Check that the files present in the submodule are not tracked
1954 // when we snapshot
1955 let (new_tree, _stats) = test_workspace.snapshot_with_options(&snapshot_options)?;
1956 assert_tree_eq!(new_tree, tree_id2);
1957
1958 // Check out the empty tree, which shouldn't fail
1959 let ws = &mut test_workspace.workspace;
1960 let stats = ws
1961 .check_out(repo.op_id().clone(), None, &store.root_commit())
1962 .block_on()?;
1963 assert_eq!(stats.skipped_files, 0, "Empty tree should checkout cleanly");
1964
1965 // Start with an empty submodule directory and check out a commit without
1966 // the submodule
1967 let ws = &mut test_workspace.workspace;
1968 ws.check_out(repo.op_id().clone(), None, &commit1)
1969 .block_on()?;
1970 std::fs::remove_file(added_submodule_path.to_fs_path_unchecked(&workspace_root))?;
1971 let ws = &mut test_workspace.workspace;
1972 ws.check_out(repo.op_id().clone(), None, &store.root_commit())
1973 .block_on()?;
1974
1975 // Check that the empty submodule directory was removed
1976 let submodule_dir = submodule_path.to_fs_path_unchecked(&workspace_root);
1977 assert!(
1978 submodule_dir.metadata().is_err(),
1979 "{submodule_dir:?} should not exist"
1980 );
1981
1982 // Go back to a commit with the submodule
1983 let ws = &mut test_workspace.workspace;
1984 ws.check_out(repo.op_id().clone(), None, &commit2)
1985 .block_on()?;
1986
1987 // Check that the empty submodule directory was created
1988 let submodule_dir = submodule_path.to_fs_path_unchecked(&workspace_root);
1989 assert!(
1990 submodule_dir.metadata().is_ok(),
1991 "{submodule_dir:?} should exist"
1992 );
1993 assert_eq!(stats.skipped_files, 0);
1994
1995 // Restore submodule contents (pretend that the user did `git submodule update`)
1996 testutils::write_working_copy_file(
1997 &workspace_root,
1998 added_submodule_path,
1999 "i am a file in a submodule\n",
2000 );
2001
2002 // Check that the files in the submodule are not deleted after checking out
2003 // a commit without the submodule
2004 let ws = &mut test_workspace.workspace;
2005 let stats = ws
2006 .check_out(repo.op_id().clone(), None, &store.root_commit())
2007 .block_on()?;
2008 let file_in_submodule_path = added_submodule_path.to_fs_path_unchecked(&workspace_root);
2009 assert!(
2010 file_in_submodule_path.metadata().is_ok(),
2011 "{file_in_submodule_path:?} should exist"
2012 );
2013
2014 // Check that checking out a submodule over an existing directory with the
2015 // same path does not result in a conflict and that the submodule is still
2016 // recorded as a submodule in the commit
2017 let ws = &mut test_workspace.workspace;
2018 ws.check_out(repo.op_id().clone(), None, &commit2)
2019 .block_on()?;
2020 assert_eq!(stats.skipped_files, 0);
2021 let (new_tree, _stats) = test_workspace.snapshot_with_options(&snapshot_options)?;
2022 assert_tree_eq!(new_tree, tree_id2);
2023
2024 // Restore submodule contents (pretend that the user did `git submodule update`)
2025 testutils::write_working_copy_file(
2026 &workspace_root,
2027 added_submodule_path,
2028 "i am a file in a submodule\n",
2029 );
2030
2031 // Check out a commit which tries to place a file at the same path
2032 let ws = &mut test_workspace.workspace;
2033 ws.check_out(repo.op_id().clone(), None, &commit3_file_clash)
2034 .block_on()?;
2035
2036 // Check that the submodule is not replaced by the file, preserving the
2037 // user's existing submodule files
2038 let file_in_submodule_path = added_submodule_path.to_fs_path_unchecked(&workspace_root);
2039 assert!(
2040 file_in_submodule_path.metadata().is_ok(),
2041 "{file_in_submodule_path:?} should exist"
2042 );
2043 Ok(())
2044 }
2045
2046 #[test]
2047 fn test_check_out_existing_file_cannot_be_removed() -> TestResult {
2048 let mut test_workspace = TestWorkspace::init();
2049 let repo = &test_workspace.repo;
2050 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2051
2052 let file_path = repo_path("file");
2053 let tree1 = create_tree(repo, &[(file_path, "0")]);
2054 let tree2 = create_tree(repo, &[(file_path, "1")]);
2055 let commit1 = commit_with_tree(repo.store(), tree1);
2056 let commit2 = commit_with_tree(repo.store(), tree2);
2057
2058 let ws = &mut test_workspace.workspace;
2059 ws.check_out(repo.op_id().clone(), None, &commit1)
2060 .block_on()?;
2061
2062 // Make the parent directory readonly.
2063 let writable_dir_perm = workspace_root.symlink_metadata()?.permissions();
2064 let mut readonly_dir_perm = writable_dir_perm.clone();
2065 readonly_dir_perm.set_readonly(true);
2066
2067 std::fs::set_permissions(&workspace_root, readonly_dir_perm)?;
2068 let result = ws
2069 .check_out(repo.op_id().clone(), None, &commit2)
2070 .block_on();
2071 std::fs::set_permissions(&workspace_root, writable_dir_perm)?;
2072
2073 // TODO: find a way to trigger the error on Windows
2074 if !cfg!(windows) {
2075 assert_matches!(
2076 result,
2077 Err(CheckoutError::Other { message, .. }) if message.contains("Failed to remove")
2078 );
2079 }
2080 Ok(())
2081 }
2082
2083 #[test]
2084 fn test_check_out_existing_file_replaced_with_directory() -> TestResult {
2085 let mut test_workspace = TestWorkspace::init();
2086 let repo = &test_workspace.repo;
2087 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2088
2089 let file_path = repo_path("file");
2090 let tree1 = create_tree(repo, &[(file_path, "0")]);
2091 let tree2 = create_tree(repo, &[(file_path, "1")]);
2092 let commit1 = commit_with_tree(repo.store(), tree1);
2093 let commit2 = commit_with_tree(repo.store(), tree2);
2094
2095 let ws = &mut test_workspace.workspace;
2096 ws.check_out(repo.op_id().clone(), None, &commit1)
2097 .block_on()?;
2098
2099 std::fs::remove_file(file_path.to_fs_path_unchecked(&workspace_root))?;
2100 std::fs::create_dir(file_path.to_fs_path_unchecked(&workspace_root))?;
2101
2102 // Checkout doesn't fail, but the file should be skipped.
2103 let stats = ws
2104 .check_out(repo.op_id().clone(), None, &commit2)
2105 .block_on()?;
2106 assert_eq!(stats.skipped_files, 1);
2107 assert!(file_path.to_fs_path_unchecked(&workspace_root).is_dir());
2108 Ok(())
2109 }
2110
2111 #[test]
2112 fn test_check_out_existing_directory_symlink() -> TestResult {
2113 if !check_symlink_support()? {
2114 eprintln!("Skipping test because symlink isn't supported");
2115 return Ok(());
2116 }
2117
2118 let mut test_workspace = TestWorkspace::init();
2119 let repo = &test_workspace.repo;
2120 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2121
2122 // Creates a symlink in working directory, and a tree that will add a file
2123 // under the symlinked directory.
2124 symlink_dir("..", workspace_root.join("parent"))?;
2125
2126 // Test two file paths writing to the same directory to ensure that
2127 // any directory creation optimizations which depend on how
2128 // `parent/escaped1` behaved don't allow `parent/escaped2` to be
2129 // created
2130 let file_path1 = repo_path("parent/escaped1");
2131 let file_path2 = repo_path("parent/escaped2");
2132 let tree = create_tree(repo, &[(file_path1, "contents"), (file_path2, "contents")]);
2133 let commit = commit_with_tree(repo.store(), tree);
2134
2135 // Checkout doesn't fail, but the file should be skipped.
2136 let ws = &mut test_workspace.workspace;
2137 let stats = ws
2138 .check_out(repo.op_id().clone(), None, &commit)
2139 .block_on()?;
2140 assert_eq!(stats.skipped_files, 2);
2141
2142 // Therefore, "../escaped*" paths shouldn't be created.
2143 assert!(!workspace_root.parent().unwrap().join("escaped1").exists());
2144 assert!(!workspace_root.parent().unwrap().join("escaped2").exists());
2145 Ok(())
2146 }
2147
2148 #[test]
2149 fn test_check_out_existing_directory_symlink_icase_fs() -> TestResult {
2150 if !check_symlink_support()? {
2151 eprintln!("Skipping test because symlink isn't supported");
2152 return Ok(());
2153 }
2154
2155 let mut test_workspace = TestWorkspace::init();
2156 let repo = &test_workspace.repo;
2157 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2158 let is_icase_fs = check_icase_fs(&workspace_root);
2159
2160 // Creates a symlink in working directory, and a tree that will add a file
2161 // under the symlinked directory.
2162 symlink_dir("..", workspace_root.join("parent"))?;
2163
2164 let file_path1 = repo_path("PARENT/escaped1");
2165 let file_path2 = repo_path("PARENT/escaped2");
2166 let tree = create_tree(repo, &[(file_path1, "contents"), (file_path2, "contents")]);
2167 let commit = commit_with_tree(repo.store(), tree);
2168
2169 // Checkout doesn't fail, but the file should be skipped on icase fs.
2170 let ws = &mut test_workspace.workspace;
2171 let stats = ws
2172 .check_out(repo.op_id().clone(), None, &commit)
2173 .block_on()?;
2174 if is_icase_fs {
2175 assert_eq!(stats.skipped_files, 2);
2176 } else {
2177 assert_eq!(stats.skipped_files, 0);
2178 }
2179
2180 // Therefore, "../escaped*" paths shouldn't be created.
2181 assert!(!workspace_root.parent().unwrap().join("escaped1").exists());
2182 assert!(!workspace_root.parent().unwrap().join("escaped2").exists());
2183 Ok(())
2184 }
2185
2186 #[test_case(false; "symlink target does not exist")]
2187 #[test_case(true; "symlink target exists")]
2188 fn test_check_out_existing_file_symlink_icase_fs(victim_exists: bool) -> TestResult {
2189 if !check_symlink_support()? {
2190 eprintln!("Skipping test because symlink isn't supported");
2191 return Ok(());
2192 }
2193
2194 let mut test_workspace = TestWorkspace::init();
2195 let repo = &test_workspace.repo;
2196 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2197 let is_icase_fs = check_icase_fs(&workspace_root);
2198
2199 // Creates a symlink in working directory, and a tree that will overwrite
2200 // the symlink content.
2201 symlink_file(
2202 PathBuf::from_iter(["..", "pwned"]),
2203 workspace_root.join("parent"),
2204 )?;
2205 let victim_file_path = workspace_root.parent().unwrap().join("pwned");
2206 if victim_exists {
2207 std::fs::write(&victim_file_path, "old")?;
2208 }
2209 assert_eq!(workspace_root.join("parent").exists(), victim_exists);
2210
2211 let file_path = repo_path("PARENT");
2212 let tree = create_tree(repo, &[(file_path, "bad")]);
2213 let commit = commit_with_tree(repo.store(), tree);
2214
2215 // Checkout doesn't fail, but the file should be skipped on icase fs.
2216 let ws = &mut test_workspace.workspace;
2217 let stats = ws
2218 .check_out(repo.op_id().clone(), None, &commit)
2219 .block_on()?;
2220 if is_icase_fs {
2221 assert_eq!(stats.skipped_files, 1);
2222 } else {
2223 assert_eq!(stats.skipped_files, 0);
2224 }
2225
2226 // Therefore, "../pwned" shouldn't be updated.
2227 if victim_exists {
2228 assert_eq!(std::fs::read(&victim_file_path)?, b"old");
2229 } else {
2230 assert!(!victim_file_path.exists());
2231 }
2232 Ok(())
2233 }
2234
2235 #[test]
2236 fn test_check_out_file_removal_over_existing_directory_symlink() -> TestResult {
2237 if !check_symlink_support()? {
2238 eprintln!("Skipping test because symlink isn't supported");
2239 return Ok(());
2240 }
2241
2242 let mut test_workspace = TestWorkspace::init();
2243 let repo = &test_workspace.repo;
2244 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2245
2246 let file_path = repo_path("parent/escaped");
2247 let tree1 = create_tree(repo, &[(file_path, "contents")]);
2248 let tree2 = create_tree(repo, &[]);
2249 let commit1 = commit_with_tree(repo.store(), tree1);
2250 let commit2 = commit_with_tree(repo.store(), tree2);
2251
2252 // Check out "parent/escaped".
2253 let ws = &mut test_workspace.workspace;
2254 ws.check_out(repo.op_id().clone(), None, &commit1)
2255 .block_on()?;
2256
2257 // Pretend that "parent" was a symlink, which might be created by
2258 // e.g. checking out "PARENT" on case-insensitive fs. The file
2259 // "parent/escaped" would be skipped in that case.
2260 std::fs::remove_file(file_path.to_fs_path_unchecked(&workspace_root))?;
2261 std::fs::remove_dir(workspace_root.join("parent"))?;
2262 symlink_dir("..", workspace_root.join("parent"))?;
2263 let victim_file_path = workspace_root.parent().unwrap().join("escaped");
2264 std::fs::write(&victim_file_path, "")?;
2265 assert!(file_path.to_fs_path_unchecked(&workspace_root).exists());
2266
2267 // Check out empty tree, which tries to remove "parent/escaped".
2268 let stats = ws
2269 .check_out(repo.op_id().clone(), None, &commit2)
2270 .block_on()?;
2271 assert_eq!(stats.skipped_files, 1);
2272
2273 // "../escaped" shouldn't be removed.
2274 assert!(victim_file_path.exists());
2275 Ok(())
2276 }
2277
2278 #[test_case(".git"; "reserved .git dir")]
2279 #[test_case(".jj"; "reserved .jj dir")]
2280 #[test_case("symlink"; "looped")]
2281 #[test_case("unknown"; "dead")]
2282 #[cfg_attr(windows, ignore = "Windows impl follows symlink")] // FIXME
2283 fn test_check_out_symlink_unusual_target(link_target: &str) -> TestResult {
2284 if !check_symlink_support()? {
2285 eprintln!("Skipping test because symlink isn't supported");
2286 return Ok(());
2287 }
2288
2289 let mut test_workspace = TestWorkspace::init();
2290 let repo = &test_workspace.repo;
2291 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2292 std::fs::create_dir(workspace_root.join(".git"))?;
2293
2294 let symlink_path = repo_path("symlink");
2295 let symlink_disk_path = symlink_path.to_fs_path_unchecked(&workspace_root);
2296 let tree1 = create_tree_with(repo, |builder| {
2297 builder.symlink(symlink_path, link_target);
2298 });
2299 let tree2 = create_tree(repo, &[]);
2300 let commit1 = commit_with_tree(repo.store(), tree1);
2301 let commit2 = commit_with_tree(repo.store(), tree2);
2302
2303 // Check out tree containing symlink
2304 let ws = &mut test_workspace.workspace;
2305 let stats = ws
2306 .check_out(repo.op_id().clone(), None, &commit1)
2307 .block_on()?;
2308 assert_eq!(stats.added_files, 1);
2309
2310 // Symlink should be created
2311 assert_eq!(symlink_disk_path.read_link()?.as_os_str(), link_target);
2312
2313 // Check out empty tree
2314 let stats = ws
2315 .check_out(repo.op_id().clone(), None, &commit2)
2316 .block_on()?;
2317 assert_eq!(stats.removed_files, 1);
2318
2319 // Symlink should be deleted
2320 assert_matches!(
2321 symlink_disk_path.symlink_metadata().map_err(|e| e.kind()),
2322 Err(io::ErrorKind::NotFound)
2323 );
2324 Ok(())
2325 }
2326
2327 #[test_case("../pwned"; "escape from root")]
2328 #[test_case("sub/../../pwned"; "escape from sub dir")]
2329 fn test_check_out_malformed_file_path(file_path_str: &str) {
2330 let mut test_workspace = TestWorkspace::init();
2331 let repo = &test_workspace.repo;
2332 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2333
2334 let file_path = repo_path(file_path_str);
2335 let tree = create_tree(repo, &[(file_path, "contents")]);
2336 let commit = commit_with_tree(repo.store(), tree);
2337
2338 // Checkout should fail
2339 let ws = &mut test_workspace.workspace;
2340 let result = ws.check_out(repo.op_id().clone(), None, &commit).block_on();
2341 assert_matches!(result, Err(CheckoutError::InvalidRepoPath(_)));
2342
2343 // Therefore, "pwned" file shouldn't be created.
2344 assert!(!workspace_root.join(file_path_str).exists());
2345 assert!(!workspace_root.parent().unwrap().join("pwned").exists());
2346 }
2347
2348 #[test_case(r"sub\..\../pwned"; "path separator")]
2349 #[test_case("d:/pwned"; "drive letter")]
2350 fn test_check_out_malformed_file_path_windows(file_path_str: &str) {
2351 let mut test_workspace = TestWorkspace::init();
2352 let repo = &test_workspace.repo;
2353 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2354
2355 let file_path = repo_path(file_path_str);
2356 let tree = create_tree(repo, &[(file_path, "contents")]);
2357 let commit = commit_with_tree(repo.store(), tree);
2358
2359 // Checkout should fail on Windows
2360 let ws = &mut test_workspace.workspace;
2361 let result = ws.check_out(repo.op_id().clone(), None, &commit).block_on();
2362 if cfg!(windows) {
2363 assert_matches!(result, Err(CheckoutError::InvalidRepoPath(_)));
2364 } else {
2365 assert_matches!(result, Ok(_));
2366 }
2367
2368 // Therefore, "pwned" file shouldn't be created.
2369 if cfg!(windows) {
2370 assert!(!workspace_root.join(file_path_str).exists());
2371 }
2372 assert!(!workspace_root.parent().unwrap().join("pwned").exists());
2373 }
2374
2375 #[test_case(".git"; "root .git file")]
2376 #[test_case(".jj"; "root .jj file")]
2377 #[test_case(".git/pwned"; "root .git dir")]
2378 #[test_case(".jj/pwned"; "root .jj dir")]
2379 #[test_case("sub/.git"; "sub .git file")]
2380 #[test_case("sub/.jj"; "sub .jj file")]
2381 #[test_case("sub/.git/pwned"; "sub .git dir")]
2382 #[test_case("sub/.jj/pwned"; "sub .jj dir")]
2383 fn test_check_out_reserved_file_path(file_path_str: &str) -> TestResult {
2384 let mut test_workspace = TestWorkspace::init();
2385 let repo = &test_workspace.repo;
2386 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2387 std::fs::create_dir(workspace_root.join(".git"))?;
2388
2389 let file_path = repo_path(file_path_str);
2390 let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
2391 let tree1 = create_tree(repo, &[(file_path, "contents")]);
2392 let tree2 = create_tree(repo, &[]);
2393 let commit1 = commit_with_tree(repo.store(), tree1);
2394 let commit2 = commit_with_tree(repo.store(), tree2);
2395
2396 // Checkout should fail.
2397 let ws = &mut test_workspace.workspace;
2398 let result = ws
2399 .check_out(repo.op_id().clone(), None, &commit1)
2400 .block_on();
2401 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2402
2403 // Therefore, "pwned" file shouldn't be created.
2404 if ![".git", ".jj"].contains(&file_path_str) {
2405 assert!(!disk_path.exists());
2406 }
2407 assert!(!workspace_root.join(".git").join("pwned").exists());
2408 assert!(!workspace_root.join(".jj").join("pwned").exists());
2409 assert!(!workspace_root.join("sub").join(".git").exists());
2410 assert!(!workspace_root.join("sub").join(".jj").exists());
2411
2412 // Pretend that the checkout somehow succeeded.
2413 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
2414 locked_ws.locked_wc().reset(&commit1).block_on()?;
2415 locked_ws.finish(repo.op_id().clone()).block_on()?;
2416 if ![".git", ".jj"].contains(&file_path_str) {
2417 std::fs::create_dir_all(disk_path.parent().unwrap())?;
2418 std::fs::write(&disk_path, "")?;
2419 }
2420
2421 // Check out empty tree, which tries to remove the file.
2422 let result = ws
2423 .check_out(repo.op_id().clone(), None, &commit2)
2424 .block_on();
2425 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2426
2427 // The existing file shouldn't be removed.
2428 assert!(disk_path.exists());
2429 Ok(())
2430 }
2431
2432 #[test_case(".Git/pwned"; "root .git dir")]
2433 #[test_case(".jJ/pwned"; "root .jj dir")]
2434 #[test_case("sub/.GIt"; "sub .git file")]
2435 #[test_case("sub/.JJ"; "sub .jj file")]
2436 #[test_case("sub/.gIT/pwned"; "sub .git dir")]
2437 #[test_case("sub/.Jj/pwned"; "sub .jj dir")]
2438 fn test_check_out_reserved_file_path_icase_fs(file_path_str: &str) -> TestResult {
2439 let mut test_workspace = TestWorkspace::init();
2440 let repo = &test_workspace.repo;
2441 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2442 std::fs::create_dir(workspace_root.join(".git"))?;
2443 let is_icase_fs = check_icase_fs(&workspace_root);
2444
2445 let file_path = repo_path(file_path_str);
2446 let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
2447 let tree1 = create_tree(repo, &[(file_path, "contents")]);
2448 let tree2 = create_tree(repo, &[]);
2449 let commit1 = commit_with_tree(repo.store(), tree1);
2450 let commit2 = commit_with_tree(repo.store(), tree2);
2451
2452 // Checkout should fail on icase fs.
2453 let ws = &mut test_workspace.workspace;
2454 let result = ws
2455 .check_out(repo.op_id().clone(), None, &commit1)
2456 .block_on();
2457 if is_icase_fs {
2458 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2459 } else {
2460 assert_matches!(result, Ok(_));
2461 }
2462
2463 // Therefore, "pwned" file shouldn't be created.
2464 if is_icase_fs {
2465 assert!(!disk_path.exists());
2466 }
2467 assert!(!workspace_root.join(".git").join("pwned").exists());
2468 assert!(!workspace_root.join(".jj").join("pwned").exists());
2469 assert!(!workspace_root.join("sub").join(".git").exists());
2470 assert!(!workspace_root.join("sub").join(".jj").exists());
2471
2472 // Pretend that the checkout somehow succeeded.
2473 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
2474 locked_ws.locked_wc().reset(&commit1).block_on()?;
2475 locked_ws.finish(repo.op_id().clone()).block_on()?;
2476 std::fs::create_dir_all(disk_path.parent().unwrap())?;
2477 std::fs::write(&disk_path, "")?;
2478
2479 // Check out empty tree, which tries to remove the file.
2480 let result = ws
2481 .check_out(repo.op_id().clone(), None, &commit2)
2482 .block_on();
2483 if is_icase_fs {
2484 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2485 } else {
2486 assert_matches!(result, Ok(_));
2487 }
2488
2489 // The existing file shouldn't be removed on icase fs.
2490 if is_icase_fs {
2491 assert!(disk_path.exists());
2492 }
2493 Ok(())
2494 }
2495
2496 // Here we don't test ignored characters exhaustively because our implementation
2497 // isn't using deny list.
2498 #[test_case("\u{200c}.git/pwned"; "root .git dir")]
2499 #[test_case(".\u{200d}jj/pwned"; "root .jj dir")]
2500 #[test_case("sub/.g\u{200c}it"; "sub .git file")]
2501 #[test_case("sub/.jj\u{200d}"; "sub .jj file")]
2502 #[test_case("sub/.gi\u{200e}t/pwned"; "sub .git dir")]
2503 #[test_case("sub/.jj\u{200f}/pwned"; "sub .jj dir")]
2504 fn test_check_out_reserved_file_path_hfs_plus(file_path_str: &str) -> TestResult {
2505 let mut test_workspace = TestWorkspace::init();
2506 let repo = &test_workspace.repo;
2507 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2508 std::fs::create_dir(workspace_root.join(".git"))?;
2509 let is_hfs_plus = check_hfs_plus(&workspace_root);
2510
2511 let file_path = repo_path(file_path_str);
2512 let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
2513 let tree1 = create_tree(repo, &[(file_path, "contents")]);
2514 let tree2 = create_tree(repo, &[]);
2515 let commit1 = commit_with_tree(repo.store(), tree1);
2516 let commit2 = commit_with_tree(repo.store(), tree2);
2517
2518 // Checkout should fail on HFS+-like fs.
2519 let ws = &mut test_workspace.workspace;
2520 let result = ws
2521 .check_out(repo.op_id().clone(), None, &commit1)
2522 .block_on();
2523 if is_hfs_plus {
2524 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2525 } else {
2526 assert_matches!(result, Ok(_));
2527 }
2528
2529 // Therefore, "pwned" file shouldn't be created.
2530 if is_hfs_plus {
2531 assert!(!disk_path.exists());
2532 }
2533 assert!(!workspace_root.join(".git").join("pwned").exists());
2534 assert!(!workspace_root.join(".jj").join("pwned").exists());
2535 assert!(!workspace_root.join("sub").join(".git").exists());
2536 assert!(!workspace_root.join("sub").join(".jj").exists());
2537
2538 // Pretend that the checkout somehow succeeded.
2539 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
2540 locked_ws.locked_wc().reset(&commit1).block_on()?;
2541 locked_ws.finish(repo.op_id().clone()).block_on()?;
2542 std::fs::create_dir_all(disk_path.parent().unwrap())?;
2543 std::fs::write(&disk_path, "")?;
2544
2545 // Check out empty tree, which tries to remove the file.
2546 let result = ws
2547 .check_out(repo.op_id().clone(), None, &commit2)
2548 .block_on();
2549 if is_hfs_plus {
2550 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2551 } else {
2552 assert_matches!(result, Ok(_));
2553 }
2554
2555 // The existing file shouldn't be removed on HFS+-like fs.
2556 if is_hfs_plus {
2557 assert!(disk_path.exists());
2558 }
2559 Ok(())
2560 }
2561
2562 #[test_case(".git/pwned", &["GIT~1/pwned", "GI2837~1/pwned"]; "root .git dir short name")]
2563 #[test_case(".jj/pwned", &["JJ~1/pwned", "JJ2E09~1/pwned"]; "root .jj dir short name")]
2564 #[test_case(".git/pwned", &[".GIT./pwned"]; "root .git dir trailing dots")]
2565 #[test_case(".jj/pwned", &[".JJ../pwned"]; "root .jj dir trailing dots")]
2566 #[test_case("sub/.git", &["sub/.GIT.."]; "sub .git file trailing dots")]
2567 #[test_case("sub/.jj", &["sub/.JJ."]; "sub .jj file trailing dots")]
2568 // TODO: Add more weird patterns?
2569 // - https://en.wikipedia.org/wiki/8.3_filename
2570 // - See is_ntfs_dotgit() of Git and pathauditor of Mercurial
2571 fn test_check_out_reserved_file_path_vfat(
2572 vfat_path_str: &str,
2573 file_path_strs: &[&str],
2574 ) -> TestResult {
2575 let mut test_workspace = TestWorkspace::init();
2576 let repo = &test_workspace.repo;
2577 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2578 std::fs::create_dir(workspace_root.join(".git"))?;
2579 let is_vfat = check_vfat(&workspace_root);
2580
2581 let vfat_disk_path = workspace_root.join(vfat_path_str);
2582 let file_paths = file_path_strs.iter().map(|&s| repo_path(s)).collect_vec();
2583 let tree1 = create_tree_with(repo, |builder| {
2584 for path in file_paths {
2585 builder.file(path, "contents");
2586 }
2587 });
2588 let tree2 = create_tree(repo, &[]);
2589 let commit1 = commit_with_tree(repo.store(), tree1);
2590 let commit2 = commit_with_tree(repo.store(), tree2);
2591
2592 // Checkout should fail on VFAT-like fs.
2593 let ws = &mut test_workspace.workspace;
2594 let result = ws
2595 .check_out(repo.op_id().clone(), None, &commit1)
2596 .block_on();
2597 if is_vfat {
2598 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2599 } else {
2600 assert_matches!(result, Ok(_));
2601 }
2602
2603 // Therefore, "pwned" file shouldn't be created.
2604 if is_vfat {
2605 assert!(!vfat_disk_path.exists());
2606 }
2607 assert!(!workspace_root.join(".git").join("pwned").exists());
2608 assert!(!workspace_root.join(".jj").join("pwned").exists());
2609 assert!(!workspace_root.join("sub").join(".git").exists());
2610 assert!(!workspace_root.join("sub").join(".jj").exists());
2611
2612 // Pretend that the checkout somehow succeeded.
2613 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
2614 locked_ws.locked_wc().reset(&commit1).block_on()?;
2615 locked_ws.finish(repo.op_id().clone()).block_on()?;
2616 if is_vfat {
2617 std::fs::create_dir_all(vfat_disk_path.parent().unwrap())?;
2618 std::fs::write(&vfat_disk_path, "")?;
2619 }
2620
2621 // Check out empty tree, which tries to remove the file.
2622 let result = ws
2623 .check_out(repo.op_id().clone(), None, &commit2)
2624 .block_on();
2625 if is_vfat {
2626 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2627 } else {
2628 assert_matches!(result, Ok(_));
2629 }
2630
2631 // The existing file shouldn't be removed on VFAT-like fs.
2632 if is_vfat {
2633 assert!(vfat_disk_path.exists());
2634 }
2635 Ok(())
2636 }
2637
2638 #[test_case(".git"; "root .git file")]
2639 #[test_case(".git/pwned"; "root .git dir")]
2640 fn test_check_out_reserved_file_path_dot_git_symlink(file_path_str: &str) -> TestResult {
2641 if !check_symlink_support()? {
2642 eprintln!("Skipping test because symlink isn't supported");
2643 return Ok(());
2644 }
2645
2646 let mut test_workspace = TestWorkspace::init();
2647 let repo = &test_workspace.repo;
2648 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2649
2650 // Create symlink .git -> ../git-repo
2651 let git_repo_dir = test_workspace.env.root().join("git-repo");
2652 let dot_git_path = workspace_root.join(".git");
2653 std::fs::create_dir(&git_repo_dir)?;
2654 symlink_dir(&git_repo_dir, &dot_git_path)?;
2655 assert!(dot_git_path.exists());
2656
2657 let file_path = repo_path(file_path_str);
2658 let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
2659 let tree1 = create_tree(repo, &[(file_path, "contents")]);
2660 let tree2 = create_tree(repo, &[]);
2661 let commit1 = commit_with_tree(repo.store(), tree1);
2662 let commit2 = commit_with_tree(repo.store(), tree2);
2663
2664 // Checkout should fail.
2665 let ws = &mut test_workspace.workspace;
2666 let result = ws
2667 .check_out(repo.op_id().clone(), None, &commit1)
2668 .block_on();
2669 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2670
2671 // Therefore, "pwned" file shouldn't be created.
2672 assert!(!git_repo_dir.join("pwned").exists());
2673 assert!(!dot_git_path.join("pwned").exists());
2674
2675 // Pretend that the checkout somehow succeeded.
2676 let mut locked_ws = ws.start_working_copy_mutation().block_on()?;
2677 locked_ws.locked_wc().reset(&commit1).block_on()?;
2678 locked_ws.finish(repo.op_id().clone()).block_on()?;
2679 if file_path_str != ".git" {
2680 std::fs::write(&disk_path, "")?;
2681 }
2682
2683 // Check out empty tree, which tries to remove the file.
2684 let result = ws
2685 .check_out(repo.op_id().clone(), None, &commit2)
2686 .block_on();
2687 assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
2688
2689 // The existing file shouldn't be removed.
2690 assert!(disk_path.exists());
2691 Ok(())
2692 }
2693
2694 #[test]
2695 fn test_fsmonitor() -> TestResult {
2696 let test_repo = TestRepo::init();
2697 let repo = &test_repo.repo;
2698 let workspace_root = test_repo.env.root().join("workspace");
2699 let state_path = test_repo.env.root().join("state");
2700 std::fs::create_dir(&workspace_root)?;
2701 std::fs::create_dir(&state_path)?;
2702 let tree_state_settings = TreeStateSettings::try_from_user_settings(repo.settings())?;
2703 TreeState::init(
2704 repo.store().clone(),
2705 workspace_root.clone(),
2706 state_path.clone(),
2707 &tree_state_settings,
2708 )?;
2709
2710 let foo_path = repo_path("foo");
2711 let bar_path = repo_path("bar");
2712 let nested_path = repo_path("path/to/nested");
2713 testutils::write_working_copy_file(&workspace_root, foo_path, "foo\n");
2714 testutils::write_working_copy_file(&workspace_root, bar_path, "bar\n");
2715 testutils::write_working_copy_file(&workspace_root, nested_path, "nested\n");
2716
2717 let ignored_path = repo_path("path/to/ignored");
2718 let gitignore_path = repo_path("path/.gitignore");
2719 testutils::write_working_copy_file(&workspace_root, ignored_path, "ignored\n");
2720 testutils::write_working_copy_file(&workspace_root, gitignore_path, "to/ignored\n");
2721
2722 let snapshot = |paths: &[&RepoPath]| {
2723 let changed_files = paths
2724 .iter()
2725 .map(|p| p.to_fs_path_unchecked(Path::new("")))
2726 .collect();
2727 let settings = TreeStateSettings {
2728 fsmonitor_settings: FsmonitorSettings::Test { changed_files },
2729 ..tree_state_settings.clone()
2730 };
2731 let mut tree_state = TreeState::load(
2732 repo.store().clone(),
2733 workspace_root.clone(),
2734 state_path.clone(),
2735 &settings,
2736 )
2737 .unwrap();
2738 tree_state
2739 .snapshot(&empty_snapshot_options())
2740 .block_on()
2741 .unwrap();
2742 tree_state
2743 };
2744
2745 let tree_state = snapshot(&[]);
2746 assert_tree_eq!(*tree_state.current_tree(), repo.store().empty_merged_tree());
2747
2748 let tree_state = snapshot(&[foo_path]);
2749 insta::assert_snapshot!(testutils::dump_tree(tree_state.current_tree()), @r#"
2750 merged tree (sides: 1)
2751 tree 2a5341b103917cfdb48a
2752 file "foo" (e99c2057c15160add351): "foo\n"
2753 "#);
2754
2755 let mut tree_state = snapshot(&[foo_path, bar_path, nested_path, ignored_path]);
2756 insta::assert_snapshot!(testutils::dump_tree(tree_state.current_tree()), @r#"
2757 merged tree (sides: 1)
2758 tree 1c5c336421714b1df7bb
2759 file "bar" (94cc973e7e1aefb7eff6): "bar\n"
2760 file "foo" (e99c2057c15160add351): "foo\n"
2761 file "path/to/nested" (6209060941cd770c8d46): "nested\n"
2762 "#);
2763 tree_state.save()?;
2764
2765 testutils::write_working_copy_file(&workspace_root, foo_path, "updated foo\n");
2766 testutils::write_working_copy_file(&workspace_root, bar_path, "updated bar\n");
2767 let tree_state = snapshot(&[foo_path]);
2768 insta::assert_snapshot!(testutils::dump_tree(tree_state.current_tree()), @r#"
2769 merged tree (sides: 1)
2770 tree f653dfa18d0b025bdb9e
2771 file "bar" (94cc973e7e1aefb7eff6): "bar\n"
2772 file "foo" (e0fbd106147cc04ccd05): "updated foo\n"
2773 file "path/to/nested" (6209060941cd770c8d46): "nested\n"
2774 "#);
2775
2776 std::fs::remove_file(foo_path.to_fs_path_unchecked(&workspace_root))?;
2777 let mut tree_state = snapshot(&[foo_path]);
2778 insta::assert_snapshot!(testutils::dump_tree(tree_state.current_tree()), @r#"
2779 merged tree (sides: 1)
2780 tree b7416fc248a038b920c3
2781 file "bar" (94cc973e7e1aefb7eff6): "bar\n"
2782 file "path/to/nested" (6209060941cd770c8d46): "nested\n"
2783 "#);
2784 tree_state.save()?;
2785 Ok(())
2786 }
2787
2788 #[test]
2789 fn track_ignored_with_flag_and_fsmonitor() -> TestResult {
2790 let test_repo = TestRepo::init();
2791 let repo = &test_repo.repo;
2792 let workspace_root = test_repo.env.root().join("workspace");
2793 let state_path = test_repo.env.root().join("state");
2794 std::fs::create_dir(&workspace_root)?;
2795 std::fs::create_dir(&state_path)?;
2796 let tree_state_settings = TreeStateSettings::try_from_user_settings(repo.settings())?;
2797 TreeState::init(
2798 repo.store().clone(),
2799 workspace_root.clone(),
2800 state_path.clone(),
2801 &tree_state_settings,
2802 )?;
2803
2804 let ignored_path = repo_path("file.ignored");
2805 let gitignore_path = repo_path(".gitignore");
2806 testutils::write_working_copy_file(&workspace_root, ignored_path, "contents\n");
2807 testutils::write_working_copy_file(&workspace_root, gitignore_path, "*.ignored\n");
2808
2809 let snapshot = |paths: &[&RepoPath], matcher: Option<&FilesMatcher>| {
2810 let changed_files = paths
2811 .iter()
2812 .map(|p| p.to_fs_path_unchecked(Path::new("")))
2813 .collect();
2814 let settings = TreeStateSettings {
2815 fsmonitor_settings: FsmonitorSettings::Test { changed_files },
2816 ..tree_state_settings.clone()
2817 };
2818 let mut tree_state = TreeState::load(
2819 repo.store().clone(),
2820 workspace_root.clone(),
2821 state_path.clone(),
2822 &settings,
2823 )
2824 .unwrap();
2825 let mut options = empty_snapshot_options();
2826 if let Some(matcher) = matcher {
2827 options.force_tracking_matcher = matcher;
2828 }
2829 tree_state.snapshot(&options).block_on().unwrap();
2830 tree_state.save().unwrap();
2831 tree_state
2832 };
2833
2834 let tree_state = snapshot(&[], None);
2835 assert_tree_eq!(*tree_state.current_tree(), repo.store().empty_merged_tree());
2836
2837 let tree_state = snapshot(&[ignored_path], None);
2838 assert_tree_eq!(*tree_state.current_tree(), repo.store().empty_merged_tree());
2839
2840 // Simulate `jj file track --include-ignored`.
2841 let force_tracking_matcher = FilesMatcher::new([ignored_path]);
2842 let tree_state = snapshot(&[], Some(&force_tracking_matcher));
2843
2844 let expected_tree = create_tree(repo, &[(ignored_path, "contents\n")]);
2845 assert_tree_eq!(*tree_state.current_tree(), expected_tree);
2846 Ok(())
2847 }
2848
2849 #[test]
2850 fn fsmonitor_gitignore_rescan_subtree() -> TestResult {
2851 let test_repo = TestRepo::init();
2852 let repo = &test_repo.repo;
2853 let workspace_root = test_repo.env.root().join("workspace");
2854 let state_path = test_repo.env.root().join("state");
2855 std::fs::create_dir(&workspace_root)?;
2856 std::fs::create_dir(&state_path)?;
2857 let tree_state_settings = TreeStateSettings::try_from_user_settings(repo.settings())?;
2858 TreeState::init(
2859 repo.store().clone(),
2860 workspace_root.clone(),
2861 state_path.clone(),
2862 &tree_state_settings,
2863 )?;
2864
2865 let ignored_path = repo_path("file.ignored");
2866 let gitignore_path = repo_path(".gitignore");
2867 testutils::write_working_copy_file(&workspace_root, ignored_path, "contents\n");
2868 testutils::write_working_copy_file(&workspace_root, gitignore_path, "*.ignored\n");
2869
2870 let snapshot = |paths: &[&RepoPath]| {
2871 let changed_files = paths
2872 .iter()
2873 .map(|p| p.to_fs_path_unchecked(Path::new("")))
2874 .collect();
2875 let settings = TreeStateSettings {
2876 fsmonitor_settings: FsmonitorSettings::Test { changed_files },
2877 ..tree_state_settings.clone()
2878 };
2879 let mut tree_state = TreeState::load(
2880 repo.store().clone(),
2881 workspace_root.clone(),
2882 state_path.clone(),
2883 &settings,
2884 )
2885 .unwrap();
2886 tree_state
2887 .snapshot(&empty_snapshot_options())
2888 .block_on()
2889 .unwrap();
2890 tree_state.save().unwrap();
2891 tree_state
2892 };
2893
2894 let tree_state = snapshot(&[gitignore_path, ignored_path]);
2895 let expected_tree = create_tree(repo, &[(gitignore_path, "*.ignored\n")]);
2896 assert_tree_eq!(*tree_state.current_tree(), expected_tree);
2897
2898 testutils::write_working_copy_file(&workspace_root, gitignore_path, "");
2899 let tree_state = snapshot(&[gitignore_path]);
2900 let expected_tree = create_tree(repo, &[(gitignore_path, ""), (ignored_path, "contents\n")]);
2901 assert_tree_eq!(*tree_state.current_tree(), expected_tree);
2902 Ok(())
2903 }
2904
2905 #[test]
2906 fn test_snapshot_max_new_file_size() -> TestResult {
2907 let mut test_workspace = TestWorkspace::init();
2908 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2909 let small_path = repo_path("small");
2910 let large_path = repo_path("large");
2911 let limit: usize = 1024;
2912 std::fs::write(
2913 small_path.to_fs_path_unchecked(&workspace_root),
2914 vec![0; limit],
2915 )?;
2916 let options = SnapshotOptions {
2917 max_new_file_size: limit as u64,
2918 ..empty_snapshot_options()
2919 };
2920 test_workspace
2921 .snapshot_with_options(&options)
2922 .expect("files exactly matching the size limit should succeed");
2923 std::fs::write(
2924 small_path.to_fs_path_unchecked(&workspace_root),
2925 vec![0; limit + 1],
2926 )?;
2927 let (old_tree, _stats) = test_workspace
2928 .snapshot_with_options(&options)
2929 .expect("existing files may grow beyond the size limit");
2930
2931 // A new file of 1KiB + 1 bytes should be left untracked
2932 std::fs::write(
2933 large_path.to_fs_path_unchecked(&workspace_root),
2934 vec![0; limit + 1],
2935 )?;
2936 let (new_tree, stats) = test_workspace
2937 .snapshot_with_options(&options)
2938 .expect("snapshot should not fail because of new files beyond the size limit");
2939 assert_tree_eq!(new_tree, old_tree);
2940 assert_eq!(
2941 stats
2942 .untracked_paths
2943 .keys()
2944 .map(AsRef::as_ref)
2945 .collect_vec(),
2946 [large_path]
2947 );
2948 assert_matches!(
2949 stats.untracked_paths.values().next().unwrap(),
2950 UntrackedReason::FileTooLarge { size, .. } if *size == (limit as u64) + 1
2951 );
2952
2953 // A file in sub directory should also be caught
2954 let sub_large_path = repo_path("sub/large");
2955 std::fs::create_dir(
2956 sub_large_path
2957 .parent()
2958 .unwrap()
2959 .to_fs_path_unchecked(&workspace_root),
2960 )?;
2961 std::fs::rename(
2962 large_path.to_fs_path_unchecked(&workspace_root),
2963 sub_large_path.to_fs_path_unchecked(&workspace_root),
2964 )?;
2965 let (new_tree, stats) = test_workspace
2966 .snapshot_with_options(&options)
2967 .expect("snapshot should not fail because of new files beyond the size limit");
2968 assert_tree_eq!(new_tree, old_tree);
2969 assert_eq!(
2970 stats
2971 .untracked_paths
2972 .keys()
2973 .map(AsRef::as_ref)
2974 .collect_vec(),
2975 [sub_large_path]
2976 );
2977 assert_matches!(
2978 stats.untracked_paths.values().next().unwrap(),
2979 UntrackedReason::FileTooLarge { .. }
2980 );
2981 Ok(())
2982 }
2983
2984 #[test]
2985 fn test_snapshot_symlink_use_forward_slash() -> TestResult {
2986 if !file_util::check_symlink_support()? {
2987 eprintln!("Symlink not supported. Skip the test.");
2988 }
2989 let mut test_workspace = TestWorkspace::init();
2990 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
2991 let target = repo_path("target/link/target.txt");
2992 let target_path = target.to_fs_path(&workspace_root)?;
2993 std::fs::create_dir_all(target_path.parent().unwrap())?;
2994 std::fs::write(&target_path, "a\n")?;
2995 let link = repo_path("link/link.txt");
2996 let link_path = link.to_fs_path(&workspace_root)?;
2997 let link_contents = "../target/link/target.txt";
2998 std::fs::create_dir_all(link_path.parent().unwrap())?;
2999 symlink_file(link_contents, link_path)?;
3000
3001 let tree = test_workspace
3002 .snapshot()
3003 .expect("Snapshot with symlink should succeed.");
3004 let tree_value = tree
3005 .path_value(link)
3006 .block_on()
3007 .expect("Failed to retrieve the MergedTreeValue from the path.")
3008 .into_resolved()
3009 .expect("Shouldn't have conflicts.")
3010 .expect("The link path should exist.");
3011 let TreeValue::Symlink(symlink_id) = tree_value.clone() else {
3012 panic!(
3013 "Expect {} to be a symlink, but got {:?}",
3014 link.as_internal_file_string(),
3015 tree_value
3016 );
3017 };
3018 let actual_link_contents = test_workspace
3019 .repo
3020 .store()
3021 .read_symlink(link, &symlink_id)
3022 .block_on()?;
3023
3024 assert!(
3025 !actual_link_contents.contains('\\'),
3026 r#"Expect the symlink in the Store to use "/" as the separator, but got {actual_link_contents}."#
3027 );
3028 Ok(())
3029 }
3030
3031 fn is_verbatim_path(path: &Path) -> bool {
3032 let Some(Component::Prefix(prefix)) = path.components().next() else {
3033 return false;
3034 };
3035 prefix.kind().is_verbatim()
3036 }
3037
3038 #[cfg(windows)]
3039 fn absolute_path_to_verbatim_path(input: &Path) -> PathBuf {
3040 use std::ffi::OsString;
3041 use std::path::Prefix;
3042
3043 use bstr::ByteSlice as _;
3044
3045 assert!(input.is_absolute());
3046 let input = input.canonicalize().unwrap();
3047
3048 let mut components = input.components();
3049 let Component::Prefix(prefix_component) = components.next().unwrap() else {
3050 panic!("target should be an absolute path after being canonicalized");
3051 };
3052 let mut verbatim_path = match prefix_component.kind() {
3053 // C: -> \\?\Global\C:
3054 // \\?\C: -> \\?\Global\C:
3055 //
3056 // Prefix the path with `Global`, so that when we read back the symlink, it's still a
3057 // verbatim path. The symlink to a `\\?\C:` prefixed path (e.g. `\\?\C:\file.txt`)
3058 // will be converted to a non-verbatim path (e.g. `C:\file.txt`) when calling
3059 // `read_link()`.
3060 Prefix::Disk(disk) | Prefix::VerbatimDisk(disk) => {
3061 let mut verbatim_prefix = OsString::from(r"\\?\Global\");
3062 verbatim_prefix.push([disk].to_os_str().unwrap());
3063 verbatim_prefix.push(":");
3064 verbatim_prefix
3065 }
3066 _ => panic!("Unsupported path: {}", input.display()),
3067 };
3068 verbatim_path.push(components.as_path().as_os_str());
3069 let verbatim_path = PathBuf::from(verbatim_path);
3070 assert!(is_verbatim_path(&verbatim_path));
3071 verbatim_path
3072 }
3073
3074 #[test_case(|link, target| file_util::relative_path(link.parent().unwrap(), target); "relative")]
3075 #[test_case(|_, target| {
3076 assert!(target.is_absolute());
3077 target.to_owned()
3078 }; "absolute")]
3079 #[cfg_attr(
3080 windows,
3081 test_case(|_, target: &Path| absolute_path_to_verbatim_path(target); "verbatim absolute")
3082 )]
3083 fn test_snapshot_and_update_valid_symlink(
3084 get_link_target: impl FnOnce(&Path, &Path) -> PathBuf,
3085 ) -> TestResult {
3086 if !file_util::check_symlink_support()? {
3087 eprintln!("Symlink not supported. Skip the test.");
3088 }
3089 let mut test_workspace = TestWorkspace::init();
3090 let workspace_root = test_workspace.workspace.workspace_root().to_owned();
3091 let target = repo_path("target/link/target.txt");
3092 let target_path = target.to_fs_path(&workspace_root)?;
3093 std::fs::create_dir_all(target_path.parent().unwrap())?;
3094 // Unique contents that it's unlikely that we match accidentally.
3095 let file_contents = b"18bHZD165T@C\n";
3096 std::fs::write(&target_path, file_contents)?;
3097 let link = repo_path("link/link.txt");
3098 let link_path = link.to_fs_path(&workspace_root)?;
3099 let link_contents = get_link_target(&link_path, &target_path);
3100 std::fs::create_dir_all(link_path.parent().unwrap())?;
3101 symlink_file(&link_contents, &link_path)?;
3102 std::fs::read_link(&link_path).expect("The symlink itself should exist.");
3103 assert_eq!(std::fs::read(&link_path)?, file_contents);
3104 assert_eq!(
3105 is_verbatim_path(&std::fs::read_link(&link_path)?),
3106 is_verbatim_path(&link_contents),
3107 "Make sure that when we test with a verbatim path, it's still a verbatim path in the \
3108 Store when snapshotting."
3109 );
3110
3111 let tree = test_workspace
3112 .snapshot()
3113 .expect("Snapshot with symlink should succeed.");
3114 let commit = commit_with_tree(test_workspace.repo.store(), tree);
3115
3116 // Checkout the root commit to clear the workspace.
3117 let mut locked_ws = test_workspace
3118 .workspace
3119 .start_working_copy_mutation()
3120 .block_on()?;
3121 let root_commit = test_workspace.repo.store().root_commit();
3122 locked_ws.locked_wc().check_out(&root_commit).block_on()?;
3123 locked_ws
3124 .finish(test_workspace.repo.op_id().clone())
3125 .block_on()?;
3126
3127 assert!(!std::fs::exists(&link_path)?);
3128 assert!(std::fs::read_link(&link_path).is_err());
3129
3130 // Checkout the original commit back.
3131 let mut locked_ws = test_workspace
3132 .workspace
3133 .start_working_copy_mutation()
3134 .block_on()?;
3135 locked_ws.locked_wc().check_out(&commit).block_on()?;
3136 locked_ws
3137 .finish(test_workspace.repo.op_id().clone())
3138 .block_on()?;
3139
3140 let actual_target = std::fs::read_link(&link_path).expect("The symlink itself should exist.");
3141 let actual_contents = std::fs::read(&link_path).unwrap_or_else(|e| {
3142 panic!(
3143 "Failed to read from the symlink at {}, which points to {}: {e:?}",
3144 link_path.display(),
3145 actual_target.display()
3146 )
3147 });
3148 assert_eq!(actual_contents, file_contents);
3149 assert_eq!(
3150 is_verbatim_path(&std::fs::read_link(&link_path)?),
3151 is_verbatim_path(&link_contents),
3152 "When we checkout a symlink to a verbatim path, it should still point to a verbatim path."
3153 );
3154 Ok(())
3155 }
3156
3157 #[test]
3158 fn test_always_store_empty_tree() -> TestResult {
3159 let mut test_workspace = TestWorkspace::init_with_backend(TestRepoBackend::Git);
3160 let git_backend = get_git_backend(test_workspace.repo.store())?;
3161 let git_repo = git_backend.git_repo();
3162 let empty_tree_id = gix::ObjectId::empty_tree(gix::hash::Kind::Sha1);
3163
3164 test_workspace.snapshot()?;
3165
3166 let mut buf = Vec::new();
3167 // Use objects.find as it doesn't short-circuit when asked for the empty tree
3168 let (empty_tree, _) = git_repo
3169 .objects
3170 .find(&empty_tree_id, &mut buf)
3171 .expect("empty tree should be stored in the git repo");
3172 assert_eq!(empty_tree.kind, gix::objs::Kind::Tree);
3173 assert!(empty_tree.data.is_empty());
3174 Ok(())
3175 }