Debian Codegraph @

lib/tests/test_git_backend.rs

raw
1 // Copyright 2024 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::collections::HashMap;
16 use std::collections::HashSet;
17 use std::path::Path;
18 use std::sync::Arc;
19 use std::time::Duration;
20 use std::time::SystemTime;
21
22 use futures::executor::block_on_stream;
23 use itertools::Itertools as _;
24 use jj_lib::backend::CommitId;
25 use jj_lib::backend::CopyRecord;
26 use jj_lib::commit::Commit;
27 use jj_lib::conflict_labels::ConflictLabels;
28 use jj_lib::git_backend::GitBackend;
29 use jj_lib::git_backend::JJ_TREES_COMMIT_HEADER;
30 use jj_lib::merge::Merge;
31 use jj_lib::merged_tree::MergedTree;
32 use jj_lib::object_id::ObjectId as _;
33 use jj_lib::repo::ReadonlyRepo;
34 use jj_lib::repo::Repo as _;
35 use jj_lib::repo_path::RepoPath;
36 use jj_lib::repo_path::RepoPathBuf;
37 use jj_lib::stacked_table::TableSegment as _;
38 use jj_lib::stacked_table::TableStore;
39 use jj_lib::store::Store;
40 use jj_lib::transaction::Transaction;
41 use maplit::hashmap;
42 use maplit::hashset;
43 use pollster::FutureExt as _;
44 use testutils::CommitBuilderExt as _;
45 use testutils::TestRepo;
46 use testutils::TestRepoBackend;
47 use testutils::TestResult;
48 use testutils::assert_tree_eq;
49 use testutils::commit_with_tree;
50 use testutils::create_random_commit;
51 use testutils::create_single_tree;
52 use testutils::create_tree;
53 use testutils::is_external_tool_installed;
54 use testutils::repo_path;
55 use testutils::repo_path_buf;
56 use testutils::write_random_commit;
57 use testutils::write_random_commit_with_parents;
58
59 fn get_git_backend(repo: &Arc<ReadonlyRepo>) -> &GitBackend {
60 repo.store().backend_impl().unwrap()
61 }
62
63 fn collect_no_gc_refs(git_repo_path: &Path) -> HashSet<CommitId> {
64 // Load fresh git repo to isolate from false caching issue. Here we want to
65 // ensure that the underlying data is correct. We could test the in-memory
66 // data as well, but we don't have any special handling in our code.
67 let git_repo = gix::open(git_repo_path).unwrap();
68 let git_refs = git_repo.references().unwrap();
69 let no_gc_refs_iter = git_refs.prefixed("refs/jj/keep/").unwrap();
70 no_gc_refs_iter
71 .map(|git_ref| CommitId::from_bytes(git_ref.unwrap().id().as_bytes()))
72 .collect()
73 }
74
75 fn get_copy_records(
76 store: &Store,
77 paths: Option<&[RepoPathBuf]>,
78 a: &Commit,
79 b: &Commit,
80 ) -> HashMap<String, String> {
81 let stream = store.get_copy_records(paths, a.id(), b.id()).unwrap();
82 let mut res: HashMap<String, String> = HashMap::new();
83 for CopyRecord { target, source, .. } in block_on_stream(stream).filter_map(|r| r.ok()) {
84 res.insert(
85 target.as_internal_file_string().into(),
86 source.as_internal_file_string().into(),
87 );
88 }
89 res
90 }
91
92 fn make_commit(
93 tx: &mut Transaction,
94 parents: Vec<CommitId>,
95 content: &[(&RepoPath, &str)],
96 ) -> Commit {
97 let tree = create_tree(tx.base_repo(), content);
98 tx.repo_mut().new_commit(parents, tree).write_unwrap()
99 }
100
101 fn list_dir(dir: &Path) -> Vec<String> {
102 std::fs::read_dir(dir)
103 .unwrap()
104 .map(|entry| entry.unwrap().file_name().to_str().unwrap().to_owned())
105 .sorted()
106 .collect()
107 }
108
109 #[test]
110 fn test_gc() -> TestResult {
111 // TODO: Better way to disable the test if git command couldn't be executed
112 if !is_external_tool_installed("git") {
113 eprintln!("Skipping because git command might fail to run");
114 return Ok(());
115 }
116
117 let test_repo = TestRepo::init_with_backend(TestRepoBackend::Git);
118 let repo = test_repo.repo;
119 let git_repo_path = get_git_backend(&repo).git_repo_path();
120 let base_index = repo.readonly_index();
121
122 // Set up commits:
123 //
124 // H (predecessor: D)
125 // G |
126 // |\|
127 // | F
128 // E |
129 // D | |
130 // C |/
131 // |/
132 // B
133 // A
134 let mut tx = repo.start_transaction();
135 let commit_a = write_random_commit(tx.repo_mut());
136 let commit_b = write_random_commit_with_parents(tx.repo_mut(), &[&commit_a]);
137 let commit_c = write_random_commit_with_parents(tx.repo_mut(), &[&commit_b]);
138 let commit_d = write_random_commit_with_parents(tx.repo_mut(), &[&commit_c]);
139 let commit_e = write_random_commit_with_parents(tx.repo_mut(), &[&commit_b]);
140 let commit_f = write_random_commit_with_parents(tx.repo_mut(), &[&commit_b]);
141 let commit_g = write_random_commit_with_parents(tx.repo_mut(), &[&commit_e, &commit_f]);
142 let commit_h = create_random_commit(tx.repo_mut())
143 .set_parents(vec![commit_f.id().clone()])
144 .set_predecessors(vec![commit_d.id().clone()])
145 .write_unwrap();
146 let repo = tx.commit("test").block_on()?;
147 assert_eq!(
148 *repo.view().heads(),
149 hashset! {
150 commit_d.id().clone(),
151 commit_g.id().clone(),
152 commit_h.id().clone(),
153 },
154 );
155
156 // At first, all commits have no-gc refs
157 assert_eq!(
158 collect_no_gc_refs(git_repo_path),
159 hashset! {
160 commit_a.id().clone(),
161 commit_b.id().clone(),
162 commit_c.id().clone(),
163 commit_d.id().clone(),
164 commit_e.id().clone(),
165 commit_f.id().clone(),
166 commit_g.id().clone(),
167 commit_h.id().clone(),
168 },
169 );
170
171 // Empty index, but all kept by file modification time
172 // (Beware that this invokes "git gc" and refs will be packed.)
173 repo.store()
174 .gc(base_index.as_index(), SystemTime::UNIX_EPOCH)?;
175 assert_eq!(
176 collect_no_gc_refs(git_repo_path),
177 hashset! {
178 commit_a.id().clone(),
179 commit_b.id().clone(),
180 commit_c.id().clone(),
181 commit_d.id().clone(),
182 commit_e.id().clone(),
183 commit_f.id().clone(),
184 commit_g.id().clone(),
185 commit_h.id().clone(),
186 },
187 );
188
189 // Don't rely on the exact system time because file modification time might
190 // have lower precision for example.
191 let now = || SystemTime::now() + Duration::from_secs(1);
192
193 // All reachable: redundant no-gc refs will be removed
194 repo.store().gc(repo.index(), now())?;
195 assert_eq!(
196 collect_no_gc_refs(git_repo_path),
197 hashset! {
198 commit_d.id().clone(),
199 commit_g.id().clone(),
200 commit_h.id().clone(),
201 },
202 );
203
204 // G is no longer reachable
205 let mut mut_index = base_index.start_modification();
206 mut_index.add_commit(&commit_a).block_on()?;
207 mut_index.add_commit(&commit_b).block_on()?;
208 mut_index.add_commit(&commit_c).block_on()?;
209 mut_index.add_commit(&commit_d).block_on()?;
210 mut_index.add_commit(&commit_e).block_on()?;
211 mut_index.add_commit(&commit_f).block_on()?;
212 mut_index.add_commit(&commit_h).block_on()?;
213 repo.store().gc(mut_index.as_index(), now())?;
214 assert_eq!(
215 collect_no_gc_refs(git_repo_path),
216 hashset! {
217 commit_d.id().clone(),
218 commit_e.id().clone(),
219 commit_h.id().clone(),
220 },
221 );
222
223 // D|E|H are no longer reachable
224 let mut mut_index = base_index.start_modification();
225 mut_index.add_commit(&commit_a).block_on()?;
226 mut_index.add_commit(&commit_b).block_on()?;
227 mut_index.add_commit(&commit_c).block_on()?;
228 mut_index.add_commit(&commit_f).block_on()?;
229 repo.store().gc(mut_index.as_index(), now())?;
230 assert_eq!(
231 collect_no_gc_refs(git_repo_path),
232 hashset! {
233 commit_c.id().clone(),
234 commit_f.id().clone(),
235 },
236 );
237
238 // B|C|F are no longer reachable
239 let mut mut_index = base_index.start_modification();
240 mut_index.add_commit(&commit_a).block_on()?;
241 repo.store().gc(mut_index.as_index(), now())?;
242 assert_eq!(
243 collect_no_gc_refs(git_repo_path),
244 hashset! {
245 commit_a.id().clone(),
246 },
247 );
248
249 // All unreachable
250 repo.store().gc(base_index.as_index(), now())?;
251 assert_eq!(collect_no_gc_refs(git_repo_path), hashset! {});
252 Ok(())
253 }
254
255 #[test]
256 fn test_gc_extra_table() -> TestResult {
257 if !is_external_tool_installed("git") {
258 eprintln!("Skipping because git command might fail to run");
259 return Ok(());
260 }
261
262 let test_repo = TestRepo::init_with_backend(TestRepoBackend::Git);
263 let extra_path = test_repo.repo_path().join("store").join("extra");
264 let extra_key_size = test_repo.repo.store().root_commit_id().as_bytes().len();
265 let load_repo = || {
266 test_repo
267 .env
268 .load_repo_at_head(test_repo.repo.settings(), test_repo.repo_path())
269 };
270 let load_extra_table = || {
271 TableStore::load(extra_path.clone(), extra_key_size)
272 .get_head()
273 .unwrap()
274 };
275 let collect_extra_segment_num_entries = || {
276 let mut num_entries = load_extra_table()
277 .ancestor_segments()
278 .map(|table| table.segment_num_entries())
279 .collect_vec();
280 num_entries.reverse();
281 num_entries
282 };
283
284 // Sanity check for the initial state
285 assert_eq!(collect_extra_segment_num_entries(), [0]);
286 assert_eq!(list_dir(&extra_path).len(), 1 + 1); // empty segment + "heads"
287
288 // Write 4 commits
289 let mut tx = test_repo.repo.start_transaction();
290 for _ in 0..4 {
291 write_random_commit(tx.repo_mut());
292 }
293 tx.commit("test").block_on()?;
294 // The first 3 will be squashed into one table segment
295 assert_eq!(collect_extra_segment_num_entries(), [3, 1]);
296 assert_eq!(list_dir(&extra_path).len(), 5 + 1);
297
298 // Reload repo to invalidate cache in TableStore
299 let repo = load_repo();
300 let index = repo.readonly_index().as_index();
301
302 // All segments should be kept by modification time
303 repo.store().gc(index, SystemTime::UNIX_EPOCH)?;
304 assert_eq!(collect_extra_segment_num_entries(), [3, 1]);
305 assert_eq!(list_dir(&extra_path).len(), 5 + 1);
306
307 // All unreachable segments should be removed
308 let now = SystemTime::now() + Duration::from_secs(1);
309 repo.store().gc(index, now)?;
310 assert_eq!(collect_extra_segment_num_entries(), [3, 1]);
311 assert_eq!(list_dir(&extra_path).len(), 2 + 1);
312
313 // Ensure that repo is still loadable
314 load_repo();
315 Ok(())
316 }
317
318 #[test]
319 fn test_copy_detection() -> TestResult {
320 let test_repo = TestRepo::init_with_backend(TestRepoBackend::Git);
321 let repo = &test_repo.repo;
322
323 let paths = &[
324 repo_path_buf("file0"),
325 repo_path_buf("file1"),
326 repo_path_buf("file2"),
327 ];
328
329 let mut tx = repo.start_transaction();
330 let commit_a = make_commit(
331 &mut tx,
332 vec![repo.store().root_commit_id().clone()],
333 &[(&paths[0], "content")],
334 );
335 let commit_b = make_commit(
336 &mut tx,
337 vec![commit_a.id().clone()],
338 &[(&paths[1], "content")],
339 );
340 let commit_c = make_commit(
341 &mut tx,
342 vec![commit_b.id().clone()],
343 &[(&paths[2], "content")],
344 );
345
346 let store = repo.store();
347 assert_eq!(
348 get_copy_records(store, Some(paths), &commit_a, &commit_b),
349 HashMap::from([("file1".to_string(), "file0".to_string())])
350 );
351 assert_eq!(
352 get_copy_records(store, Some(paths), &commit_b, &commit_c),
353 HashMap::from([("file2".to_string(), "file1".to_string())])
354 );
355 assert_eq!(
356 get_copy_records(store, Some(paths), &commit_a, &commit_c),
357 HashMap::from([("file2".to_string(), "file0".to_string())])
358 );
359 assert_eq!(
360 get_copy_records(store, None, &commit_a, &commit_c),
361 HashMap::from([("file2".to_string(), "file0".to_string())])
362 );
363 assert_eq!(
364 get_copy_records(store, Some(&[paths[1].clone()]), &commit_a, &commit_c),
365 HashMap::default(),
366 );
367 assert_eq!(
368 get_copy_records(store, Some(paths), &commit_c, &commit_c),
369 HashMap::default(),
370 );
371 Ok(())
372 }
373
374 #[test]
375 fn test_copy_detection_file_and_dir() -> TestResult {
376 let test_repo = TestRepo::init_with_backend(TestRepoBackend::Git);
377 let repo = &test_repo.repo;
378
379 // a -> b (file)
380 // b -> a (dir)
381 // c -> c/file (file)
382 let mut tx = repo.start_transaction();
383 let commit_a = make_commit(
384 &mut tx,
385 vec![repo.store().root_commit_id().clone()],
386 &[
387 (repo_path("a"), "content1"),
388 (repo_path("b/file"), "content2"),
389 (repo_path("c"), "content3"),
390 ],
391 );
392 let commit_b = make_commit(
393 &mut tx,
394 vec![commit_a.id().clone()],
395 &[
396 (repo_path("a/file"), "content2"),
397 (repo_path("b"), "content1"),
398 (repo_path("c/file"), "content3"),
399 ],
400 );
401
402 assert_eq!(
403 get_copy_records(repo.store(), None, &commit_a, &commit_b),
404 hashmap! {
405 "b".to_owned() => "a".to_owned(),
406 "a/file".to_owned() => "b/file".to_owned(),
407 "c/file".to_owned() => "c".to_owned(),
408 }
409 );
410 Ok(())
411 }
412
413 #[test]
414 fn test_jj_trees_header_with_one_tree() -> TestResult {
415 let test_repo = TestRepo::init_with_backend(TestRepoBackend::Git);
416 let repo = test_repo.repo;
417 let git_backend = get_git_backend(&repo);
418 let git_repo = git_backend.git_repo();
419
420 let tree_1 = create_single_tree(&repo, &[(repo_path("file"), "aaa")]);
421 let tree_2 = create_single_tree(&repo, &[(repo_path("file"), "bbb")]);
422
423 // Create a normal commit with tree 1
424 let commit = commit_with_tree(
425 repo.store(),
426 MergedTree::resolved(repo.store().clone(), tree_1.id().clone()),
427 );
428 let git_commit_id = gix::ObjectId::from_bytes_or_panic(commit.id().as_bytes());
429 let git_commit = git_repo.find_commit(git_commit_id)?;
430
431 // Add `jj:trees` with a single tree which is different from the Git commit tree
432 let mut new_commit: gix::objs::Commit = git_commit.decode()?.try_into()?;
433 new_commit.extra_headers = vec![(
434 JJ_TREES_COMMIT_HEADER.into(),
435 tree_2.id().to_string().into(),
436 )];
437 let new_commit_id = git_repo.write_object(&new_commit)?;
438 let new_commit_id = CommitId::from_bytes(new_commit_id.as_bytes());
439
440 // Import new commit into `jj` repo. This should fail, because allowing a
441 // non-conflicted commit to have a different tree in `jj` than in Git could be
442 // used to hide malicious code.
443 insta::assert_debug_snapshot!(git_backend.import_head_commits(std::slice::from_ref(&new_commit_id)), @r#"
444 Err(
445 ReadObject {
446 object_type: "commit",
447 hash: "87df728a30166ce1de0bf883948dd66b74cf25a0",
448 source: "Invalid jj:trees header",
449 },
450 )
451 "#);
452 Ok(())
453 }
454
455 #[test]
456 fn test_conflict_headers_roundtrip() -> TestResult {
457 let test_repo = TestRepo::init_with_backend(TestRepoBackend::Git);
458 let repo = test_repo.repo;
459
460 let tree_1 = create_single_tree(&repo, &[(repo_path("file"), "aaa")]);
461 let tree_2 = create_single_tree(&repo, &[(repo_path("file"), "bbb")]);
462 let tree_3 = create_single_tree(&repo, &[(repo_path("file"), "ccc")]);
463 let tree_4 = create_single_tree(&repo, &[(repo_path("file"), "ddd")]);
464 let tree_5 = create_single_tree(&repo, &[(repo_path("file"), "eee")]);
465 let tree_6 = create_single_tree(&repo, &[(repo_path("file"), "fff")]);
466 let tree_7 = create_single_tree(&repo, &[(repo_path("file"), "ggg")]);
467
468 // This creates a Git commit header with leading and trailing newlines to ensure
469 // that it can still be parsed correctly. The resulting `jj:conflict-labels`
470 // header value will look like `\nbase 1\nside 2\n\nside 3\n\n\n`.
471 let merged_tree = MergedTree::new(
472 repo.store().clone(),
473 Merge::from_vec(vec![
474 tree_1.id().clone(),
475 tree_2.id().clone(),
476 tree_3.id().clone(),
477 tree_4.id().clone(),
478 tree_5.id().clone(),
479 tree_6.id().clone(),
480 tree_7.id().clone(),
481 ]),
482 ConflictLabels::from_vec(vec![
483 "".into(),
484 // Test that various UTF-8 characters can be encoded and decoded. Git doesn't allow
485 // storing arbitrary binary data in headers, but it does allow storing UTF-8 encoded
486 // strings as long as they don't contain U+0000 codepoints.
487 "base 1 \"utf8 \u{67d4}\u{8853} \u{ba4}\u{bc1}\u{bb0}\u{bc1} \u{2699}\u{fe0f}\"".into(),
488 "side 2".into(),
489 "".into(),
490 "side 3".into(),
491 "".into(),
492 "".into(),
493 ]),
494 );
495
496 // Create a commit with the conflicted tree.
497 let commit = commit_with_tree(repo.store(), merged_tree.clone());
498 // Clear cached commit to ensure it is re-read.
499 repo.store().clear_caches();
500 // Conflict trees and labels should be preserved on read.
501 assert_tree_eq!(repo.store().get_commit(commit.id())?.tree(), merged_tree);
502 Ok(())
503 }