Debian Codegraph @

lib/src/git_backend.rs

raw ◀ ▶
1 Debian patch touch this file
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 #![expect(missing_docs)]
16
17 use std::collections::HashSet;
18 use std::ffi::OsStr;
19 use std::fmt::Debug;
20 use std::fmt::Error;
21 use std::fmt::Formatter;
22 use std::fs;
23 use std::io;
24 use std::path::Path;
25 use std::path::PathBuf;
26 use std::pin::Pin;
27 use std::process::Command;
28 use std::process::ExitStatus;
29 use std::str::Utf8Error;
30 use std::sync::Arc;
31 use std::sync::Mutex;
32 use std::sync::MutexGuard;
33 use std::time::SystemTime;
34
35 use async_trait::async_trait;
36 use futures::AsyncRead;
37 use futures::AsyncReadExt as _;
38 use futures::StreamExt as _;
39 use futures::io::Cursor;
40 use futures::stream::BoxStream;
41 use gix::bstr::BString;
42 use gix::objs::CommitRefIter;
43 use gix::objs::Exists as _;
44 use gix::objs::Write as _;
45 use gix::objs::WriteTo as _;
46 use itertools::Itertools as _;
47 use once_cell::sync::OnceCell as OnceLock;
48 use pollster::FutureExt as _;
49 use prost::Message as _;
50 use smallvec::SmallVec;
51 use thiserror::Error;
52
53 use crate::backend::Backend;
54 use crate::backend::BackendError;
55 use crate::backend::BackendInitError;
56 use crate::backend::BackendLoadError;
57 use crate::backend::BackendResult;
58 use crate::backend::ChangeId;
59 use crate::backend::Commit;
60 use crate::backend::CommitId;
61 use crate::backend::CopyHistory;
62 use crate::backend::CopyId;
63 use crate::backend::CopyRecord;
64 use crate::backend::FileId;
65 use crate::backend::MillisSinceEpoch;
66 use crate::backend::RelatedCopy;
67 use crate::backend::SecureSig;
68 use crate::backend::Signature;
69 use crate::backend::SigningFn;
70 use crate::backend::SymlinkId;
71 use crate::backend::Timestamp;
72 use crate::backend::Tree;
73 use crate::backend::TreeId;
74 use crate::backend::TreeValue;
75 use crate::backend::make_root_commit;
76 use crate::config::ConfigGetError;
77 use crate::file_util;
78 use crate::file_util::BadPathEncoding;
79 use crate::file_util::IoResultExt as _;
80 use crate::file_util::PathError;
81 use crate::git::GitSettings;
82 use crate::index::Index;
83 use crate::lock::FileLock;
84 use crate::merge::Merge;
85 use crate::merge::MergeBuilder;
86 use crate::object_id::ObjectId;
87 use crate::repo_path::RepoPath;
88 use crate::repo_path::RepoPathBuf;
89 use crate::repo_path::RepoPathComponentBuf;
90 use crate::settings::UserSettings;
91 use crate::stacked_table::MutableTable;
92 use crate::stacked_table::ReadonlyTable;
93 use crate::stacked_table::TableSegment as _;
94 use crate::stacked_table::TableStore;
95 use crate::stacked_table::TableStoreError;
96
97 const CHANGE_ID_LENGTH: usize = 16;
98 /// Ref namespace used only for preventing GC.
99 const NO_GC_REF_NAMESPACE: &str = "refs/jj/keep/";
100
101 pub const JJ_CONFLICT_README_FILE_NAME: &str = "JJ-CONFLICT-README";
102
103 pub const JJ_TREES_COMMIT_HEADER: &str = "jj:trees";
104 pub const JJ_CONFLICT_LABELS_COMMIT_HEADER: &str = "jj:conflict-labels";
105 pub const CHANGE_ID_COMMIT_HEADER: &str = "change-id";
106
107 #[derive(Debug, Error)]
108 pub enum GitBackendInitError {
109 #[error("Failed to initialize git repository")]
110 InitRepository(#[source] gix::init::Error),
111 #[error("Failed to open git repository")]
112 OpenRepository(#[source] gix::open::Error),
113 #[error("Failed to encode git repository path")]
114 EncodeRepositoryPath(#[source] BadPathEncoding),
115 #[error(transparent)]
116 Config(ConfigGetError),
117 #[error(transparent)]
118 Path(PathError),
119 }
120
121 impl From<Box<GitBackendInitError>> for BackendInitError {
122 fn from(err: Box<GitBackendInitError>) -> Self {
123 Self(err)
124 }
125 }
126
127 #[derive(Debug, Error)]
128 pub enum GitBackendLoadError {
129 #[error("Failed to open git repository")]
130 OpenRepository(#[source] gix::open::Error),
131 #[error("Failed to decode git repository path")]
132 DecodeRepositoryPath(#[source] BadPathEncoding),
133 #[error(transparent)]
134 Config(ConfigGetError),
135 #[error(transparent)]
136 Path(PathError),
137 }
138
139 impl From<Box<GitBackendLoadError>> for BackendLoadError {
140 fn from(err: Box<GitBackendLoadError>) -> Self {
141 Self(err)
142 }
143 }
144
145 /// `GitBackend`-specific error that may occur after the backend is loaded.
146 #[derive(Debug, Error)]
147 pub enum GitBackendError {
148 #[error("Failed to read non-git metadata")]
149 ReadMetadata(#[source] TableStoreError),
150 #[error("Failed to write non-git metadata")]
151 WriteMetadata(#[source] TableStoreError),
152 }
153
154 impl From<GitBackendError> for BackendError {
155 fn from(err: GitBackendError) -> Self {
156 Self::Other(err.into())
157 }
158 }
159
160 #[derive(Debug, Error)]
161 pub enum GitRepoAtWorkdirError {
162 #[error("No Git repository found at {path}")]
163 NotFound {
164 path: PathBuf,
165 source: gix::discover::is_git::Error,
166 },
167 #[error("Unrelated Git repository found at {path}")]
168 Unrelated { path: PathBuf },
169 #[error("Failed to open Git repository")]
170 Other(#[source] Box<dyn std::error::Error + Send + Sync>),
171 }
172
173 #[derive(Debug, Error)]
174 pub enum GitGcError {
175 #[error("Failed to run git gc command")]
176 GcCommand(#[source] std::io::Error),
177 #[error("git gc command exited with an error: {0}")]
178 GcCommandErrorStatus(ExitStatus),
179 }
180
181 pub struct GitBackend {
182 // While gix::Repository can be created from gix::ThreadSafeRepository, it's
183 // cheaper to cache the thread-local instance behind a mutex than creating
184 // one for each backend method call. Our GitBackend is most likely to be
185 // used in a single-threaded context.
186 base_repo: gix::ThreadSafeRepository,
187 repo: Mutex<gix::Repository>,
188 root_commit_id: CommitId,
189 root_change_id: ChangeId,
190 empty_tree_id: TreeId,
191 shallow_root_ids: OnceLock<Vec<CommitId>>,
192 extra_metadata_store: TableStore,
193 cached_extra_metadata: Mutex<Option<Arc<ReadonlyTable>>>,
194 git_executable: PathBuf,
195 write_change_id_header: bool,
196 }
197
198 impl GitBackend {
199 pub fn name() -> &'static str {
200 "git"
201 }
202
203 fn new(
204 base_repo: gix::ThreadSafeRepository,
205 extra_metadata_store: TableStore,
206 git_settings: GitSettings,
207 ) -> Self {
208 let repo = base_repo.to_thread_local();
209 let root_commit_id = CommitId::from_bytes(repo.object_hash().null_ref().as_bytes());
210 let root_change_id = ChangeId::from_bytes(&[0; CHANGE_ID_LENGTH]);
211 let empty_tree_id =
212 TreeId::from_bytes(gix::ObjectId::empty_tree(repo.object_hash()).as_bytes());
213 Self {
214 base_repo,
215 repo: Mutex::new(repo),
216 root_commit_id,
217 root_change_id,
218 empty_tree_id,
219 shallow_root_ids: OnceLock::new(),
220 extra_metadata_store,
221 cached_extra_metadata: Mutex::new(None),
222 git_executable: git_settings.executable_path,
223 write_change_id_header: git_settings.write_change_id_header,
224 }
225 }
226
227 pub fn init_internal(
228 settings: &UserSettings,
229 store_path: &Path,
230 object_hash: gix::hash::Kind,
231 ) -> Result<Self, Box<GitBackendInitError>> {
232 let git_repo_path = Path::new("git");
233 let git_repo = gix::ThreadSafeRepository::init_opts(
234 store_path.join(git_repo_path),
235 gix::create::Kind::Bare,
236 gix::create::Options {
237 object_hash: Some(object_hash),
238 ..Default::default()
239 },
240 gix_open_opts_from_settings(settings),
241 )
242 .map_err(GitBackendInitError::InitRepository)?;
243 let git_settings =
244 GitSettings::from_settings(settings).map_err(GitBackendInitError::Config)?;
245 Self::init_with_repo(store_path, git_repo_path, git_repo, git_settings)
246 }
247
248 /// Initializes backend by creating a new Git repo at the specified
249 /// workspace path. The workspace directory must exist.
250 pub fn init_colocated(
251 settings: &UserSettings,
252 store_path: &Path,
253 workspace_root: &Path,
254 object_hash: gix::hash::Kind,
255 ) -> Result<Self, Box<GitBackendInitError>> {
256 let canonical_workspace_root = {
257 let path = store_path.join(workspace_root);
258 dunce::canonicalize(&path)
259 .context(&path)
260 .map_err(GitBackendInitError::Path)?
261 };
262 let git_repo = gix::ThreadSafeRepository::init_opts(
263 canonical_workspace_root,
264 gix::create::Kind::WithWorktree,
265 gix::create::Options {
266 object_hash: Some(object_hash),
267 ..Default::default()
268 },
269 gix_open_opts_from_settings(settings),
270 )
271 .map_err(GitBackendInitError::InitRepository)?;
272 let git_repo_path = workspace_root.join(".git");
273 let git_settings =
274 GitSettings::from_settings(settings).map_err(GitBackendInitError::Config)?;
275 Self::init_with_repo(store_path, &git_repo_path, git_repo, git_settings)
276 }
277
278 /// Initializes backend with an existing Git repo at the specified path.
279 pub fn init_external(
280 settings: &UserSettings,
281 store_path: &Path,
282 git_repo_path: &Path,
283 ) -> Result<Self, Box<GitBackendInitError>> {
284 let canonical_git_repo_path = {
285 let path = store_path.join(git_repo_path);
286 canonicalize_git_repo_path(&path)
287 .context(&path)
288 .map_err(GitBackendInitError::Path)?
289 };
290 let git_repo = gix::ThreadSafeRepository::open_opts(
291 canonical_git_repo_path,
292 gix_open_opts_from_settings(settings),
293 )
294 .map_err(GitBackendInitError::OpenRepository)?;
295 let git_settings =
296 GitSettings::from_settings(settings).map_err(GitBackendInitError::Config)?;
297 Self::init_with_repo(store_path, git_repo_path, git_repo, git_settings)
298 }
299
300 fn init_with_repo(
301 store_path: &Path,
302 git_repo_path: &Path,
303 repo: gix::ThreadSafeRepository,
304 git_settings: GitSettings,
305 ) -> Result<Self, Box<GitBackendInitError>> {
306 let extra_path = store_path.join("extra");
307 fs::create_dir(&extra_path)
308 .context(&extra_path)
309 .map_err(GitBackendInitError::Path)?;
310 let target_path = store_path.join("git_target");
311 let git_repo_path = if cfg!(windows) && git_repo_path.is_relative() {
312 // When a repository is created in Windows, format the path with *forward
313 // slashes* and not backwards slashes. This makes it possible to use the same
314 // repository under Windows Subsystem for Linux.
315 //
316 // This only works for relative paths. If the path is absolute, there's not much
317 // we can do, and it simply won't work inside and outside WSL at the same time.
318 file_util::slash_path(git_repo_path)
319 } else {
320 git_repo_path.into()
321 };
322 let git_repo_path_bytes = file_util::path_to_bytes(&git_repo_path)
323 .map_err(GitBackendInitError::EncodeRepositoryPath)?;
324 fs::write(&target_path, git_repo_path_bytes)
325 .context(&target_path)
326 .map_err(GitBackendInitError::Path)?;
327 let extra_metadata_store = TableStore::init(
328 extra_path,
329 repo.to_thread_local().object_hash().len_in_bytes(),
330 );
331 Ok(Self::new(repo, extra_metadata_store, git_settings))
332 }
333
334 pub fn load(
335 settings: &UserSettings,
336 store_path: &Path,
337 ) -> Result<Self, Box<GitBackendLoadError>> {
338 let git_repo_path = {
339 let target_path = store_path.join("git_target");
340 let git_repo_path_bytes = fs::read(&target_path)
341 .context(&target_path)
342 .map_err(GitBackendLoadError::Path)?;
343 let git_repo_path = file_util::path_from_bytes(&git_repo_path_bytes)
344 .map_err(GitBackendLoadError::DecodeRepositoryPath)?;
345 let git_repo_path = store_path.join(git_repo_path);
346 canonicalize_git_repo_path(&git_repo_path)
347 .context(&git_repo_path)
348 .map_err(GitBackendLoadError::Path)?
349 };
350 let repo = gix::ThreadSafeRepository::open_opts(
351 git_repo_path,
352 gix_open_opts_from_settings(settings),
353 )
354 .map_err(GitBackendLoadError::OpenRepository)?;
355 let extra_metadata_store = TableStore::load(
356 store_path.join("extra"),
357 repo.to_thread_local().object_hash().len_in_bytes(),
358 );
359 let git_settings =
360 GitSettings::from_settings(settings).map_err(GitBackendLoadError::Config)?;
361 Ok(Self::new(repo, extra_metadata_store, git_settings))
362 }
363
364 fn lock_git_repo(&self) -> MutexGuard<'_, gix::Repository> {
365 self.repo.lock().unwrap()
366 }
367
368 /// Returns a new thread-local handle for the underlying Git repository.
369 ///
370 /// Use [`Self::open_git_repo_at_workdir()`] for worktree operations.
371 pub fn git_repo(&self) -> gix::Repository {
372 self.base_repo.to_thread_local()
373 }
374
375 /// Reopens the repository at the given workspace path. Returns a new
376 /// thread-local handle.
377 pub fn open_git_repo_at_workdir(
378 &self,
379 path: &Path,
380 ) -> Result<gix::Repository, GitRepoAtWorkdirError> {
381 // Try the open repository first.
382 let open_repo = self.git_repo();
383 if let Some(workdir) = open_repo.workdir()
384 && (workdir == path || dunce::canonicalize(path).is_ok_and(|path| workdir == path))
385 {
386 return Ok(open_repo);
387 }
388
389 // The input path doesn't include ".git".
390 let opts = open_repo.open_options().clone().open_path_as_is(false);
391 let work_repo = gix::ThreadSafeRepository::open_opts(path, opts)
392 .map_err(|err| match err {
393 gix::open::Error::NotARepository { path, source } => {
394 GitRepoAtWorkdirError::NotFound { path, source }
395 }
396 err => GitRepoAtWorkdirError::Other(err.into()),
397 })?
398 .to_thread_local();
399 let canonicalize = |path: &Path| {
400 dunce::canonicalize(path).map_err(|err| GitRepoAtWorkdirError::Other(err.into()))
401 };
402 if open_repo.common_dir() == work_repo.common_dir()
403 || canonicalize(open_repo.common_dir())? == canonicalize(work_repo.common_dir())?
404 {
405 // The last (path, work_repo) can be cached if needed.
406 Ok(work_repo)
407 } else {
408 let path = path.to_owned();
409 Err(GitRepoAtWorkdirError::Unrelated { path })
410 }
411 }
412
413 /// Path to the `.git` directory or the repository itself if it's bare.
414 pub fn git_repo_path(&self) -> &Path {
415 self.base_repo.path()
416 }
417
418 fn shallow_root_ids(&self, git_repo: &gix::Repository) -> BackendResult<&[CommitId]> {
419 // The list of shallow roots is cached by gix, but it's still expensive
420 // to stat file on every read_object() call. Refreshing shallow roots is
421 // also bad for consistency reasons.
422 self.shallow_root_ids
423 .get_or_try_init(|| {
424 let maybe_oids = git_repo
425 .shallow_commits()
426 .map_err(|err| BackendError::Other(err.into()))?;
427 let commit_ids = maybe_oids.map_or(vec![], |oids| {
428 oids.iter()
429 .map(|oid| CommitId::from_bytes(oid.as_bytes()))
430 .collect()
431 });
432 Ok(commit_ids)
433 })
434 .map(AsRef::as_ref)
435 }
436
437 fn cached_extra_metadata_table(&self) -> BackendResult<Arc<ReadonlyTable>> {
438 let mut locked_head = self.cached_extra_metadata.lock().unwrap();
439 match locked_head.as_ref() {
440 Some(head) => Ok(head.clone()),
441 None => {
442 let table = self
443 .extra_metadata_store
444 .get_head()
445 .map_err(GitBackendError::ReadMetadata)?;
446 *locked_head = Some(table.clone());
447 Ok(table)
448 }
449 }
450 }
451
452 fn read_extra_metadata_table_locked(&self) -> BackendResult<(Arc<ReadonlyTable>, FileLock)> {
453 let table = self
454 .extra_metadata_store
455 .get_head_locked()
456 .map_err(GitBackendError::ReadMetadata)?;
457 Ok(table)
458 }
459
460 fn save_extra_metadata_table(
461 &self,
462 mut_table: MutableTable,
463 _table_lock: &FileLock,
464 ) -> BackendResult<()> {
465 let table = self
466 .extra_metadata_store
467 .save_table(mut_table)
468 .map_err(GitBackendError::WriteMetadata)?;
469 // Since the parent table was the head, saved table are likely to be new head.
470 // If it's not, cache will be reloaded when entry can't be found.
471 *self.cached_extra_metadata.lock().unwrap() = Some(table);
472 Ok(())
473 }
474
475 /// Imports the given commits and ancestors from the backing Git repo.
476 ///
477 /// The `head_ids` may contain commits that have already been imported, but
478 /// the caller should filter them out to eliminate redundant I/O processing.
479 #[tracing::instrument(skip(self, head_ids))]
480 pub fn import_head_commits<'a>(
481 &self,
482 head_ids: impl IntoIterator<Item = &'a CommitId>,
483 ) -> BackendResult<()> {
484 let head_ids: HashSet<&CommitId> = head_ids
485 .into_iter()
486 .filter(|&id| *id != self.root_commit_id)
487 .collect();
488 if head_ids.is_empty() {
489 return Ok(());
490 }
491
492 // Create no-gc ref even if known to the extras table. Concurrent GC
493 // process might have deleted the no-gc ref.
494 let locked_repo = self.lock_git_repo();
495 locked_repo
496 .edit_references(head_ids.iter().copied().map(to_no_gc_ref_update))
497 .map_err(|err| BackendError::Other(Box::new(err)))?;
498
499 // These commits are imported from Git. Make our change ids persist (otherwise
500 // future write_commit() could reassign new change id.)
501 tracing::debug!(
502 heads_count = head_ids.len(),
503 "import extra metadata entries"
504 );
505 let (table, table_lock) = self.read_extra_metadata_table_locked()?;
506 let mut mut_table = table.start_mutation();
507 import_extra_metadata_entries_from_heads(
508 &locked_repo,
509 &mut mut_table,
510 &table_lock,
511 &head_ids,
512 self.shallow_root_ids(&locked_repo)?,
513 )?;
514 self.save_extra_metadata_table(mut_table, &table_lock)
515 }
516
517 fn read_file_sync(&self, id: &FileId) -> BackendResult<Vec<u8>> {
518 let locked_repo = self.lock_git_repo();
519 let git_blob_id = validate_git_object_id(&locked_repo, id)?;
520 let mut blob = locked_repo
521 .find_object(git_blob_id)
522 .map_err(|err| map_not_found_err(err, id))?
523 .try_into_blob()
524 .map_err(|err| to_read_object_err(err, id))?;
525 Ok(blob.take_data())
526 }
527
528 fn new_diff_platform(&self) -> BackendResult<gix::diff::blob::Platform> {
529 let attributes = gix::worktree::Stack::new(
530 Path::new(""),
531 gix::worktree::stack::State::AttributesStack(Default::default()),
532 gix::worktree::glob::pattern::Case::Sensitive,
533 Vec::new(),
534 Vec::new(),
535 );
536 let filter = gix::diff::blob::Pipeline::new(
537 Default::default(),
538 gix::filter::plumbing::Pipeline::new(
539 self.git_repo()
540 .command_context()
541 .map_err(|err| BackendError::Other(Box::new(err)))?,
542 Default::default(),
543 ),
544 Vec::new(),
545 Default::default(),
546 );
547 Ok(gix::diff::blob::Platform::new(
548 Default::default(),
549 filter,
550 gix::diff::blob::pipeline::Mode::ToGit,
551 attributes,
552 ))
553 }
554
555 fn read_tree_for_commit<'repo>(
556 &self,
557 repo: &'repo gix::Repository,
558 id: &CommitId,
559 ) -> BackendResult<gix::Tree<'repo>> {
560 let tree = self.read_commit(id).block_on()?.root_tree;
561 // TODO(kfm): probably want to do something here if it is a merge
562 let tree_id = tree.first().clone();
563 let gix_id = validate_git_object_id(repo, &tree_id)?;
564 repo.find_object(gix_id)
565 .map_err(|err| map_not_found_err(err, &tree_id))?
566 .try_into_tree()
567 .map_err(|err| to_read_object_err(err, &tree_id))
568 }
569
570 // Similar to gix's write_blob, but compute the hash outside our lock to
571 // reduce contention.
572 fn write_blob(
573 &self,
574 bytes: &[u8],
575 object_type: &'static str,
576 ) -> BackendResult<gix::hash::ObjectId> {
577 let oid = gix::objs::compute_hash(
578 self.base_repo.objects.object_hash(),
579 gix::objs::Kind::Blob,
580 bytes,
581 )
582 .map_err(|err| BackendError::WriteObject {
583 object_type,
584 source: Box::new(err),
585 })?;
586
587 let locked_repo = self.lock_git_repo();
588 if !locked_repo.objects.exists(&oid) {
589 // reuse the precomputed hash, since Gitoxide provides an API for it (otherwise
590 // Gitoxide recomputes it).
591 let write_oid = locked_repo
592 .objects
593 .write_buf_with_known_id(gix::objs::Kind::Blob, bytes, oid)
594 .map_err(|err| BackendError::WriteObject {
595 object_type,
596 source: err,
597 })?;
598 assert!(oid == write_oid);
599 }
600 Ok(oid)
601 }
602 }
603
604 /// Canonicalizes the given `path` except for the last `".git"` component.
605 ///
606 /// The last path component matters when opening a Git repo without `core.bare`
607 /// config. This config is usually set, but the "repo" tool will set up such
608 /// repositories and symlinks. Opening such repo with fully-canonicalized path
609 /// would turn a colocated Git repo into a bare repo.
610 pub fn canonicalize_git_repo_path(path: &Path) -> io::Result<PathBuf> {
611 if path.ends_with(".git") {
612 let workdir = path.parent().unwrap();
613 dunce::canonicalize(workdir).map(|dir| dir.join(".git"))
614 } else {
615 dunce::canonicalize(path)
616 }
617 }
618
619 fn gix_open_opts_from_settings(settings: &UserSettings) -> gix::open::Options {
620 let user_name = settings.user_name();
621 let user_email = settings.user_email();
622 gix::open::Options::default()
623 .config_overrides([
624 // Committer has to be configured to record reflog. Author isn't
625 // needed, but let's copy the same values.
626 format!("author.name={user_name}"),
627 format!("author.email={user_email}"),
628 format!("committer.name={user_name}"),
629 format!("committer.email={user_email}"),
630 ])
631 // The git_target path should point the repository, not the working directory.
632 .open_path_as_is(true)
633 // Gitoxide recommends this when correctness is preferred
634 .strict_config(true)
635 }
636
637 /// Parses the `jj:conflict-labels` header value if present.
638 fn extract_conflict_labels_from_commit(commit: &gix::objs::CommitRef) -> Merge<String> {
639 let Some(value) = commit
640 .extra_headers()
641 .find(JJ_CONFLICT_LABELS_COMMIT_HEADER)
642 else {
643 return Merge::resolved(String::new());
644 };
645
646 str::from_utf8(value)
647 .expect("labels should be valid utf8")
648 .split_terminator('\n')
649 .map(str::to_owned)
650 .collect::<MergeBuilder<_>>()
651 .build()
652 }
653
654 /// Parses the `jj:trees` header value if present, otherwise returns the
655 /// resolved tree ID from Git.
656 fn extract_root_tree_from_commit(commit: &gix::objs::CommitRef) -> Result<Merge<TreeId>, ()> {
657 let Some(value) = commit.extra_headers().find(JJ_TREES_COMMIT_HEADER) else {
658 let tree_id = TreeId::from_bytes(commit.tree().as_bytes());
659 return Ok(Merge::resolved(tree_id));
660 };
661
662 let hash_len = commit.tree().kind().len_in_bytes();
663 let mut tree_ids = SmallVec::new();
664 for hex in value.split(|b| *b == b' ') {
665 let tree_id = TreeId::try_from_hex(hex).ok_or(())?;
666 if tree_id.as_bytes().len() != hash_len {
667 return Err(());
668 }
669 tree_ids.push(tree_id);
670 }
671 // It is invalid to use `jj:trees` with a non-conflicted tree. If this were
672 // allowed, it would be possible to construct a commit which appears to have
673 // different contents depending on whether it is viewed using `jj` or `git`.
674 if tree_ids.len() == 1 || tree_ids.len() % 2 == 0 {
675 return Err(());
676 }
677 Ok(Merge::from_vec(tree_ids))
678 }
679
680 fn commit_from_git_without_root_parent(
681 id: &CommitId,
682 git_object: &gix::Object,
683 is_shallow: bool,
684 ) -> BackendResult<Commit> {
685 let decode_err = |err: gix::objs::decode::Error| to_read_object_err(err, id);
686 let commit = git_object
687 .try_to_commit_ref()
688 .map_err(|err| to_read_object_err(err, id))?;
689
690 // If the git header has a change-id field, we attempt to convert that to a
691 // valid JJ Change Id
692 let change_id = extract_change_id_from_commit(&commit)
693 .unwrap_or_else(|| synthetic_change_id_from_git_commit_id(id));
694
695 // shallow commits don't have parents their parents actually fetched, so we
696 // discard them here
697 // TODO: This causes issues when a shallow repository is deepened/unshallowed
698 let parents = if is_shallow {
699 vec![]
700 } else {
701 commit
702 .parents()
703 .map(|oid| CommitId::from_bytes(oid.as_bytes()))
704 .collect_vec()
705 };
706 // If the commit is a conflict, the conflict labels are stored in a commit
707 // header separately from the trees.
708 let conflict_labels = extract_conflict_labels_from_commit(&commit);
709 // Conflicted commits written before we started using the `jj:trees` header
710 // (~March 2024) may have the root trees stored in the extra metadata table
711 // instead. For such commits, we'll update the root tree later when we read the
712 // extra metadata.
713 let root_tree = extract_root_tree_from_commit(&commit)
714 .map_err(|()| to_read_object_err("Invalid jj:trees header", id))?;
715 // Use lossy conversion as commit message with "mojibake" is still better than
716 // nothing.
717 // TODO: what should we do with commit.encoding?
718 let description = String::from_utf8_lossy(commit.message).into_owned();
719 let author = signature_from_git(commit.author().map_err(decode_err)?);
720 let committer = signature_from_git(commit.committer().map_err(decode_err)?);
721
722 // If the commit is signed, extract both the signature and the signed data
723 // (which is the commit buffer with the gpgsig header omitted).
724 // We have to re-parse the raw commit data because gix CommitRef does not give
725 // us the sogned data, only the signature.
726 // Ideally, we could use try_to_commit_ref_iter at the beginning of this
727 // function and extract everything from that. For now, this works
728 let secure_sig = commit
729 .extra_headers
730 .iter()
•731 // gix does not recognize gpgsig-sha256, but prevent future footguns by checking for it too
732 .any(|(k, _)| *k == "gpgsig" || *k == "gpgsig-sha256")
733 .then(|| CommitRefIter::signature(&git_object.data, git_object.id.kind()))
734 .transpose()
735 .map_err(decode_err)?
736 .flatten()
737 .map(|(sig, data)| SecureSig {
738 data: data.to_bstring().into(),
739 sig: sig.into_owned().into(),
740 });
741
742 Ok(Commit {
743 parents,
744 predecessors: vec![],
745 // If this commit has associated extra metadata, we may reset this later.
746 root_tree,
747 conflict_labels,
748 change_id,
749 description,
750 author,
751 committer,
752 secure_sig,
753 })
754 }
755
756 /// Extracts change id from commit headers.
757 pub fn extract_change_id_from_commit(commit: &gix::objs::CommitRef) -> Option<ChangeId> {
758 commit
759 .extra_headers()
760 .find(CHANGE_ID_COMMIT_HEADER)
761 .and_then(ChangeId::try_from_reverse_hex)
762 .filter(|val| val.as_bytes().len() == CHANGE_ID_LENGTH)
763 }
764
765 /// Deterministically creates a change id based on the commit id
766 ///
767 /// Used when we get a commit without a change id. The exact algorithm for the
768 /// computation should not be relied upon.
769 pub fn synthetic_change_id_from_git_commit_id(id: &CommitId) -> ChangeId {
770 // We reverse the bits of the commit id to create the change id. We don't
771 // want to use the first bytes unmodified because then it would be ambiguous
772 // if a given hash prefix refers to the commit id or the change id. It would
773 // have been enough to pick the last 16 bytes instead of the leading 16
774 // bytes to address that. We also reverse the bits to make it less likely
775 // that users depend on any relationship between the two ids.
776 let bytes = id.as_bytes()[id.as_bytes().len() - CHANGE_ID_LENGTH..]
777 .iter()
778 .rev()
779 .map(|b| b.reverse_bits())
780 .collect();
781 ChangeId::new(bytes)
782 }
783
784 const EMPTY_STRING_PLACEHOLDER: &str = "JJ_EMPTY_STRING";
785
786 fn signature_from_git(signature: gix::actor::SignatureRef) -> Signature {
787 let name = signature.name;
788 let name = if name != EMPTY_STRING_PLACEHOLDER {
789 String::from_utf8_lossy(name).into_owned()
790 } else {
791 "".to_string()
792 };
793 let email = signature.email;
794 let email = if email != EMPTY_STRING_PLACEHOLDER {
795 String::from_utf8_lossy(email).into_owned()
796 } else {
797 "".to_string()
798 };
799 let time = signature.time().unwrap_or_default();
800 let timestamp = MillisSinceEpoch(time.seconds * 1000);
801 let tz_offset = time.offset.div_euclid(60); // in minutes
802 Signature {
803 name,
804 email,
805 timestamp: Timestamp {
806 timestamp,
807 tz_offset,
808 },
809 }
810 }
811
812 fn signature_to_git(signature: &Signature) -> gix::actor::Signature {
813 // git does not support empty names or emails
814 let name = if !signature.name.is_empty() {
815 &signature.name
816 } else {
817 EMPTY_STRING_PLACEHOLDER
818 };
819 let email = if !signature.email.is_empty() {
820 &signature.email
821 } else {
822 EMPTY_STRING_PLACEHOLDER
823 };
824 let time = gix::date::Time::new(
825 signature.timestamp.timestamp.0.div_euclid(1000),
826 signature.timestamp.tz_offset * 60, // in seconds
827 );
828 gix::actor::Signature {
829 name: name.into(),
830 email: email.into(),
831 time,
832 }
833 }
834
835 fn serialize_extras(commit: &Commit) -> Vec<u8> {
836 let mut proto = crate::protos::git_store::Commit {
837 change_id: commit.change_id.to_bytes(),
838 ..Default::default()
839 };
840 proto.uses_tree_conflict_format = true;
841 for predecessor in &commit.predecessors {
842 proto.predecessors.push(predecessor.to_bytes());
843 }
844 proto.encode_to_vec()
845 }
846
847 fn deserialize_extras(commit: &mut Commit, bytes: &[u8]) {
848 let proto = crate::protos::git_store::Commit::decode(bytes).unwrap();
849 if !proto.change_id.is_empty() {
850 commit.change_id = ChangeId::new(proto.change_id);
851 }
852 if commit.root_tree.is_resolved()
853 && proto.uses_tree_conflict_format
854 && !proto.root_tree.is_empty()
855 {
856 let merge_builder: MergeBuilder<_> = proto
857 .root_tree
858 .iter()
859 .map(|id_bytes| TreeId::from_bytes(id_bytes))
860 .collect();
861 commit.root_tree = merge_builder.build();
862 }
863 for predecessor in &proto.predecessors {
864 commit.predecessors.push(CommitId::from_bytes(predecessor));
865 }
866 }
867
868 /// Returns `RefEdit` that will create a ref in `refs/jj/keep` if not exist.
869 /// Used for preventing GC of commits we create.
870 fn to_no_gc_ref_update(id: &CommitId) -> gix::refs::transaction::RefEdit {
871 let name = format!("{NO_GC_REF_NAMESPACE}{id}");
872 let new = gix::refs::Target::Object(gix::ObjectId::from_bytes_or_panic(id.as_bytes()));
873 let expected = gix::refs::transaction::PreviousValue::ExistingMustMatch(new.clone());
874 gix::refs::transaction::RefEdit {
875 change: gix::refs::transaction::Change::Update {
876 log: gix::refs::transaction::LogChange {
877 message: "used by jj".into(),
878 ..Default::default()
879 },
880 expected,
881 new,
882 },
883 name: name.try_into().unwrap(),
884 deref: false,
885 }
886 }
887
888 fn to_ref_deletion(git_ref: gix::refs::Reference) -> gix::refs::transaction::RefEdit {
889 let expected = gix::refs::transaction::PreviousValue::ExistingMustMatch(git_ref.target);
890 gix::refs::transaction::RefEdit {
891 change: gix::refs::transaction::Change::Delete {
892 expected,
893 log: gix::refs::transaction::RefLog::AndReference,
894 },
895 name: git_ref.name,
896 deref: false,
897 }
898 }
899
900 /// Recreates `refs/jj/keep` refs for the `new_heads`, and removes the other
901 /// unreachable and non-head refs.
902 fn recreate_no_gc_refs(
903 git_repo: &gix::Repository,
904 new_heads: impl IntoIterator<Item = CommitId>,
905 keep_newer: SystemTime,
906 ) -> BackendResult<()> {
907 // Calculate diff between existing no-gc refs and new heads.
908 let new_heads: HashSet<CommitId> = new_heads.into_iter().collect();
909 let mut no_gc_refs_to_keep_count: usize = 0;
910 let mut no_gc_refs_to_delete: Vec<gix::refs::Reference> = Vec::new();
911 let git_references = git_repo
912 .references()
913 .map_err(|err| BackendError::Other(err.into()))?;
914 let no_gc_refs_iter = git_references
915 .prefixed(NO_GC_REF_NAMESPACE)
916 .map_err(|err| BackendError::Other(err.into()))?;
917 for git_ref in no_gc_refs_iter {
918 let git_ref = git_ref.map_err(BackendError::Other)?.detach();
919 let oid = git_ref.target.try_id().ok_or_else(|| {
920 let name = git_ref.name.as_bstr();
921 BackendError::Other(format!("Symbolic no-gc ref found: {name}").into())
922 })?;
923 let id = CommitId::from_bytes(oid.as_bytes());
924 let name_good = git_ref.name.as_bstr()[NO_GC_REF_NAMESPACE.len()..] == id.hex();
925 if new_heads.contains(&id) && name_good {
926 no_gc_refs_to_keep_count += 1;
927 continue;
928 }
929 // Check timestamp of loose ref, but this is still racy on re-import
930 // because:
931 // - existing packed ref won't be demoted to loose ref
932 // - existing loose ref won't be touched
933 //
934 // TODO: might be better to switch to a dummy merge, where new no-gc ref
935 // will always have a unique name. Doing that with the current
936 // ref-per-head strategy would increase the number of the no-gc refs.
937 // https://github.com/jj-vcs/jj/pull/2659#issuecomment-1837057782
938 let loose_ref_path = git_repo.path().join(git_ref.name.to_path());
939 if let Ok(metadata) = loose_ref_path.metadata() {
940 let mtime = metadata.modified().expect("unsupported platform?");
941 if mtime > keep_newer {
942 tracing::trace!(?git_ref, "not deleting new");
943 no_gc_refs_to_keep_count += 1;
944 continue;
945 }
946 }
947 // Also deletes no-gc ref of random name created by old jj.
948 tracing::trace!(?git_ref, ?name_good, "will delete");
949 no_gc_refs_to_delete.push(git_ref);
950 }
951 tracing::info!(
952 new_heads_count = new_heads.len(),
953 no_gc_refs_to_keep_count,
954 no_gc_refs_to_delete_count = no_gc_refs_to_delete.len(),
955 "collected reachable refs"
956 );
957
958 // It's slow to delete packed refs one by one, so update refs all at once.
959 let ref_edits = itertools::chain(
960 no_gc_refs_to_delete.into_iter().map(to_ref_deletion),
961 new_heads.iter().map(to_no_gc_ref_update),
962 );
963 git_repo
964 .edit_references(ref_edits)
965 .map_err(|err| BackendError::Other(err.into()))?;
966
967 Ok(())
968 }
969
970 fn run_git_gc(program: &OsStr, git_dir: &Path, keep_newer: SystemTime) -> Result<(), GitGcError> {
971 let keep_newer = keep_newer
972 .duration_since(SystemTime::UNIX_EPOCH)
973 .unwrap_or_default(); // underflow
974 let mut git = Command::new(program);
975 git.arg("--git-dir=.") // turn off discovery
976 .arg("gc")
977 .arg(format!("--prune=@{} +0000", keep_newer.as_secs()));
978 // Don't specify it by GIT_DIR/--git-dir. On Windows, the path could be
979 // canonicalized as UNC path, which wouldn't be supported by git.
980 git.current_dir(git_dir);
981 // TODO: pass output to UI layer instead of printing directly here
982 tracing::info!(?git, "running git gc");
983 let status = git.status().map_err(GitGcError::GcCommand)?;
984 tracing::info!(?status, "git gc exited");
985 if !status.success() {
986 return Err(GitGcError::GcCommandErrorStatus(status));
987 }
988 Ok(())
989 }
990
991 fn validate_git_object_id(
992 repo: &gix::Repository,
993 id: &impl ObjectId,
994 ) -> BackendResult<gix::ObjectId> {
995 let expected_kind = repo.object_hash();
996 match gix::ObjectId::try_from(id.as_bytes()) {
997 Ok(id) if id.kind() == expected_kind => Ok(id),
998 _ => Err(BackendError::InvalidHashLength {
999 expected: expected_kind.len_in_bytes(),
1000 actual: id.as_bytes().len(),
1001 object_type: id.object_type(),
1002 hash: id.hex(),
1003 }),
1004 }
1005 }
1006
1007 fn map_not_found_err(err: gix::object::find::existing::Error, id: &impl ObjectId) -> BackendError {
1008 if matches!(err, gix::object::find::existing::Error::NotFound { .. }) {
1009 BackendError::ObjectNotFound {
1010 object_type: id.object_type(),
1011 hash: id.hex(),
1012 source: Box::new(err),
1013 }
1014 } else {
1015 to_read_object_err(err, id)
1016 }
1017 }
1018
1019 fn to_read_object_err(
1020 err: impl Into<Box<dyn std::error::Error + Send + Sync>>,
1021 id: &impl ObjectId,
1022 ) -> BackendError {
1023 BackendError::ReadObject {
1024 object_type: id.object_type(),
1025 hash: id.hex(),
1026 source: err.into(),
1027 }
1028 }
1029
1030 fn to_invalid_utf8_err(source: Utf8Error, id: &impl ObjectId) -> BackendError {
1031 BackendError::InvalidUtf8 {
1032 object_type: id.object_type(),
1033 hash: id.hex(),
1034 source,
1035 }
1036 }
1037
1038 fn import_extra_metadata_entries_from_heads(
1039 git_repo: &gix::Repository,
1040 mut_table: &mut MutableTable,
1041 _table_lock: &FileLock,
1042 head_ids: &HashSet<&CommitId>,
1043 shallow_roots: &[CommitId],
1044 ) -> BackendResult<()> {
1045 let mut work_ids = head_ids
1046 .iter()
1047 .filter(|&id| mut_table.get_value(id.as_bytes()).is_none())
1048 .map(|&id| id.clone())
1049 .collect_vec();
1050 while let Some(id) = work_ids.pop() {
1051 let git_object = git_repo
1052 .find_object(validate_git_object_id(git_repo, &id)?)
1053 .map_err(|err| map_not_found_err(err, &id))?;
1054 let is_shallow = shallow_roots.contains(&id);
1055 // TODO(#1624): Should we read the root tree here and check if it has a
1056 // `.jjconflict-...` entries? That could happen if the user used `git` to e.g.
1057 // change the description of a commit with tree-level conflicts.
1058 let commit = commit_from_git_without_root_parent(&id, &git_object, is_shallow)?;
1059 mut_table.add_entry(id.to_bytes(), serialize_extras(&commit));
1060 work_ids.extend(
1061 commit
1062 .parents
1063 .into_iter()
1064 .filter(|id| mut_table.get_value(id.as_bytes()).is_none()),
1065 );
1066 }
1067 Ok(())
1068 }
1069
1070 impl Debug for GitBackend {
1071 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1072 f.debug_struct("GitBackend")
1073 .field("path", &self.git_repo_path())
1074 .finish()
1075 }
1076 }
1077
1078 #[async_trait]
1079 impl Backend for GitBackend {
1080 fn name(&self) -> &str {
1081 Self::name()
1082 }
1083
1084 fn commit_id_length(&self) -> usize {
1085 self.base_repo.objects.object_hash().len_in_bytes()
1086 }
1087
1088 fn change_id_length(&self) -> usize {
1089 CHANGE_ID_LENGTH
1090 }
1091
1092 fn root_commit_id(&self) -> &CommitId {
1093 &self.root_commit_id
1094 }
1095
1096 fn root_change_id(&self) -> &ChangeId {
1097 &self.root_change_id
1098 }
1099
1100 fn empty_tree_id(&self) -> &TreeId {
1101 &self.empty_tree_id
1102 }
1103
1104 fn concurrency(&self) -> usize {
1105 1
1106 }
1107
1108 async fn read_file(
1109 &self,
1110 _path: &RepoPath,
1111 id: &FileId,
1112 ) -> BackendResult<Pin<Box<dyn AsyncRead + Send>>> {
1113 let data = self.read_file_sync(id)?;
1114 Ok(Box::pin(Cursor::new(data)))
1115 }
1116
1117 async fn write_file(
1118 &self,
1119 _path: &RepoPath,
1120 contents: &mut (dyn AsyncRead + Send + Unpin),
1121 ) -> BackendResult<FileId> {
1122 let mut bytes = Vec::new();
1123 contents.read_to_end(&mut bytes).await.unwrap();
1124
1125 let oid = self.write_blob(&bytes, "file")?;
1126 Ok(FileId::new(oid.as_bytes().to_vec()))
1127 }
1128
1129 async fn read_symlink(&self, _path: &RepoPath, id: &SymlinkId) -> BackendResult<String> {
1130 let locked_repo = self.lock_git_repo();
1131 let git_blob_id = validate_git_object_id(&locked_repo, id)?;
1132 let mut blob = locked_repo
1133 .find_object(git_blob_id)
1134 .map_err(|err| map_not_found_err(err, id))?
1135 .try_into_blob()
1136 .map_err(|err| to_read_object_err(err, id))?;
1137 let target = String::from_utf8(blob.take_data())
1138 .map_err(|err| to_invalid_utf8_err(err.utf8_error(), id))?;
1139 Ok(target)
1140 }
1141
1142 async fn write_symlink(&self, _path: &RepoPath, target: &str) -> BackendResult<SymlinkId> {
1143 let oid = self.write_blob(target.as_bytes(), "symlink")?;
1144 Ok(SymlinkId::new(oid.as_bytes().to_vec()))
1145 }
1146
1147 async fn read_copy(&self, _id: &CopyId) -> BackendResult<CopyHistory> {
1148 Err(BackendError::Unsupported(
1149 "The Git backend doesn't support tracked copies yet".to_string(),
1150 ))
1151 }
1152
1153 async fn write_copy(&self, _contents: &CopyHistory) -> BackendResult<CopyId> {
1154 Err(BackendError::Unsupported(
1155 "The Git backend doesn't support tracked copies yet".to_string(),
1156 ))
1157 }
1158
1159 async fn get_related_copies(&self, _copy_id: &CopyId) -> BackendResult<Vec<RelatedCopy>> {
1160 Err(BackendError::Unsupported(
1161 "The Git backend doesn't support tracked copies yet".to_string(),
1162 ))
1163 }
1164
1165 async fn read_tree(&self, _path: &RepoPath, id: &TreeId) -> BackendResult<Tree> {
1166 if id == &self.empty_tree_id {
1167 return Ok(Tree::default());
1168 }
1169
1170 let locked_repo = self.lock_git_repo();
1171 let git_tree_id = validate_git_object_id(&locked_repo, id)?;
1172 let git_tree = locked_repo
1173 .find_object(git_tree_id)
1174 .map_err(|err| map_not_found_err(err, id))?
1175 .try_into_tree()
1176 .map_err(|err| to_read_object_err(err, id))?;
1177 let mut entries: Vec<_> = git_tree
1178 .iter()
1179 .map(|entry| -> BackendResult<_> {
1180 let entry = entry.map_err(|err| to_read_object_err(err, id))?;
1181 let name = RepoPathComponentBuf::new(
1182 str::from_utf8(entry.filename()).map_err(|err| to_invalid_utf8_err(err, id))?,
1183 )
1184 .unwrap();
1185 let value = match entry.mode().kind() {
1186 gix::object::tree::EntryKind::Tree => {
1187 let id = TreeId::from_bytes(entry.oid().as_bytes());
1188 TreeValue::Tree(id)
1189 }
1190 gix::object::tree::EntryKind::Blob => {
1191 let id = FileId::from_bytes(entry.oid().as_bytes());
1192 TreeValue::File {
1193 id,
1194 executable: false,
1195 copy_id: CopyId::placeholder(),
1196 }
1197 }
1198 gix::object::tree::EntryKind::BlobExecutable => {
1199 let id = FileId::from_bytes(entry.oid().as_bytes());
1200 TreeValue::File {
1201 id,
1202 executable: true,
1203 copy_id: CopyId::placeholder(),
1204 }
1205 }
1206 gix::object::tree::EntryKind::Link => {
1207 let id = SymlinkId::from_bytes(entry.oid().as_bytes());
1208 TreeValue::Symlink(id)
1209 }
1210 gix::object::tree::EntryKind::Commit => {
1211 let id = CommitId::from_bytes(entry.oid().as_bytes());
1212 TreeValue::GitSubmodule(id)
1213 }
1214 };
1215 Ok((name, value))
1216 })
1217 .try_collect()?;
1218 // While Git tree entries are sorted, the rule is slightly different.
1219 // Directory names are sorted as if they had trailing "/".
1220 if !entries.is_sorted_by_key(|(name, _)| name) {
1221 entries.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
1222 }
1223 Ok(Tree::from_sorted_entries(entries))
1224 }
1225
1226 async fn write_tree(&self, _path: &RepoPath, contents: &Tree) -> BackendResult<TreeId> {
1227 // Tree entries to be written must be sorted by Entry::filename(), which
1228 // is slightly different from the order of our backend::Tree.
1229 let entries = contents
1230 .entries()
1231 .map(|entry| {
1232 let filename = BString::from(entry.name().as_internal_str());
1233 match entry.value() {
1234 TreeValue::File {
1235 id,
1236 executable: false,
1237 copy_id: _, // TODO: Use the value
1238 } => gix::objs::tree::Entry {
1239 mode: gix::object::tree::EntryKind::Blob.into(),
1240 filename,
1241 oid: gix::ObjectId::from_bytes_or_panic(id.as_bytes()),
1242 },
1243 TreeValue::File {
1244 id,
1245 executable: true,
1246 copy_id: _, // TODO: Use the value
1247 } => gix::objs::tree::Entry {
1248 mode: gix::object::tree::EntryKind::BlobExecutable.into(),
1249 filename,
1250 oid: gix::ObjectId::from_bytes_or_panic(id.as_bytes()),
1251 },
1252 TreeValue::Symlink(id) => gix::objs::tree::Entry {
1253 mode: gix::object::tree::EntryKind::Link.into(),
1254 filename,
1255 oid: gix::ObjectId::from_bytes_or_panic(id.as_bytes()),
1256 },
1257 TreeValue::Tree(id) => gix::objs::tree::Entry {
1258 mode: gix::object::tree::EntryKind::Tree.into(),
1259 filename,
1260 oid: gix::ObjectId::from_bytes_or_panic(id.as_bytes()),
1261 },
1262 TreeValue::GitSubmodule(id) => gix::objs::tree::Entry {
1263 mode: gix::object::tree::EntryKind::Commit.into(),
1264 filename,
1265 oid: gix::ObjectId::from_bytes_or_panic(id.as_bytes()),
1266 },
1267 }
1268 })
1269 .sorted_unstable()
1270 .collect();
1271 let locked_repo = self.lock_git_repo();
1272 let oid = locked_repo
1273 .write_object(gix::objs::Tree { entries })
1274 .map_err(|err| BackendError::WriteObject {
1275 object_type: "tree",
1276 source: Box::new(err),
1277 })?;
1278 Ok(TreeId::from_bytes(oid.as_bytes()))
1279 }
1280
1281 #[tracing::instrument(skip(self))]
1282 async fn read_commit(&self, id: &CommitId) -> BackendResult<Commit> {
1283 if *id == self.root_commit_id {
1284 return Ok(make_root_commit(
1285 self.root_change_id().clone(),
1286 self.empty_tree_id.clone(),
1287 ));
1288 }
1289
1290 let mut commit = {
1291 let locked_repo = self.lock_git_repo();
1292 let git_commit_id = validate_git_object_id(&locked_repo, id)?;
1293 let git_object = locked_repo
1294 .find_object(git_commit_id)
1295 .map_err(|err| map_not_found_err(err, id))?;
1296 let is_shallow = self.shallow_root_ids(&locked_repo)?.contains(id);
1297 commit_from_git_without_root_parent(id, &git_object, is_shallow)?
1298 };
1299 if commit.parents.is_empty() {
1300 commit.parents.push(self.root_commit_id.clone());
1301 }
1302
1303 let table = self.cached_extra_metadata_table()?;
1304 if let Some(extras) = table.get_value(id.as_bytes()) {
1305 deserialize_extras(&mut commit, extras);
1306 } else {
1307 // TODO: Remove this hack and map to ObjectNotFound error if we're sure that
1308 // there are no reachable ancestor commits without extras metadata. Git commits
1309 // imported by jj < 0.8.0 might not have extras (#924).
1310 // https://github.com/jj-vcs/jj/issues/2343
1311 tracing::info!("unimported Git commit found");
1312 self.import_head_commits([id])?;
1313 let table = self.cached_extra_metadata_table()?;
1314 let extras = table.get_value(id.as_bytes()).unwrap();
1315 deserialize_extras(&mut commit, extras);
1316 }
1317 Ok(commit)
1318 }
1319
1320 async fn write_commit(
1321 &self,
1322 mut contents: Commit,
1323 mut sign_with: Option<&mut SigningFn>,
1324 ) -> BackendResult<(CommitId, Commit)> {
1325 assert!(contents.secure_sig.is_none(), "commit.secure_sig was set");
1326
1327 let locked_repo = self.lock_git_repo();
1328 let tree_ids = &contents.root_tree;
1329 let git_tree_id = match tree_ids.as_resolved() {
1330 Some(tree_id) => validate_git_object_id(&locked_repo, tree_id)?,
1331 None => write_tree_conflict(&locked_repo, tree_ids)?,
1332 };
1333 let author = signature_to_git(&contents.author);
1334 let mut committer = signature_to_git(&contents.committer);
1335 let message = &contents.description;
1336 if contents.parents.is_empty() {
1337 return Err(BackendError::Other(
1338 "Cannot write a commit with no parents".into(),
1339 ));
1340 }
1341 let mut parents = SmallVec::new();
1342 for parent_id in &contents.parents {
1343 if *parent_id == self.root_commit_id {
1344 // Git doesn't have a root commit, so if the parent is the root commit, we don't
1345 // add it to the list of parents to write in the Git commit. We also check that
1346 // there are no other parents since Git cannot represent a merge between a root
1347 // commit and another commit.
1348 if contents.parents.len() > 1 {
1349 return Err(BackendError::Unsupported(
1350 "The Git backend does not support creating merge commits with the root \
1351 commit as one of the parents."
1352 .to_owned(),
1353 ));
1354 }
1355 } else {
1356 parents.push(validate_git_object_id(&locked_repo, parent_id)?);
1357 }
1358 }
1359 let mut extra_headers: Vec<(BString, BString)> = vec![];
1360 if !contents.conflict_labels.is_resolved() {
1361 // Labels cannot contain '\n' since we use it as a separator in the header.
1362 assert!(
1363 contents
1364 .conflict_labels
1365 .iter()
1366 .all(|label| !label.contains('\n'))
1367 );
1368 let mut joined_with_newlines = contents.conflict_labels.iter().join("\n");
1369 joined_with_newlines.push('\n');
1370 extra_headers.push((
1371 JJ_CONFLICT_LABELS_COMMIT_HEADER.into(),
1372 joined_with_newlines.into(),
1373 ));
1374 }
1375 if !tree_ids.is_resolved() {
1376 let value = tree_ids.iter().map(|id| id.hex()).join(" ");
1377 extra_headers.push((JJ_TREES_COMMIT_HEADER.into(), value.into()));
1378 }
1379 if self.write_change_id_header {
1380 extra_headers.push((
1381 CHANGE_ID_COMMIT_HEADER.into(),
1382 contents.change_id.reverse_hex().into(),
1383 ));
1384 }
1385
1386 if tree_ids.iter().any(|id| id == &self.empty_tree_id) {
1387 let tree = gix::objs::Tree::empty();
1388 let tree_id =
1389 locked_repo
1390 .write_object(&tree)
1391 .map_err(|err| BackendError::WriteObject {
1392 object_type: "tree",
1393 source: Box::new(err),
1394 })?;
1395 assert!(tree_id.is_empty_tree());
1396 }
1397
1398 let extras = serialize_extras(&contents);
1399
1400 // If two writers write commits of the same id with different metadata, they
1401 // will both succeed and the metadata entries will be "merged" later. Since
1402 // metadata entry is keyed by the commit id, one of the entries would be lost.
1403 // To prevent such race condition locally, we extend the scope covered by the
1404 // table lock. This is still racy if multiple machines are involved and the
1405 // repository is rsync-ed.
1406 let (table, table_lock) = self.read_extra_metadata_table_locked()?;
1407 let id = loop {
1408 let mut commit = gix::objs::Commit {
1409 message: message.to_owned().into(),
1410 tree: git_tree_id,
1411 author: author.clone(),
1412 committer: committer.clone(),
1413 encoding: None,
1414 parents: parents.clone(),
1415 extra_headers: extra_headers.clone(),
1416 };
1417
1418 if let Some(sign) = &mut sign_with {
1419 // we don't use gix pool, but at least use their heuristic
1420 let mut data = Vec::with_capacity(512);
1421 commit.write_to(&mut data).unwrap();
1422
1423 let sig = sign(&data).map_err(|err| BackendError::WriteObject {
1424 object_type: "commit",
1425 source: Box::new(err),
1426 })?;
1427 commit
1428 .extra_headers
•1429 .push(("gpgsig".into(), sig.clone().into()));
1430 contents.secure_sig = Some(SecureSig { data, sig });
1431 }
1432
1433 let git_id =
1434 locked_repo
1435 .write_object(&commit)
1436 .map_err(|err| BackendError::WriteObject {
1437 object_type: "commit",
1438 source: Box::new(err),
1439 })?;
1440
1441 match table.get_value(git_id.as_bytes()) {
1442 Some(existing_extras) if existing_extras != extras => {
1443 // It's possible a commit already exists with the same
1444 // commit id but different change id. Adjust the timestamp
1445 // until this is no longer the case.
1446 //
1447 // For example, this can happen when rebasing duplicate
1448 // commits, https://github.com/jj-vcs/jj/issues/694.
1449 //
1450 // `jj` resets the committer timestamp to the current
1451 // timestamp whenever it rewrites a commit. So, it's
1452 // unlikely for the timestamp to be 0 even if the original
1453 // commit had its timestamp set to 0. Moreover, we test that
1454 // a commit with a negative timestamp can still be written
1455 // and read back by `jj`.
1456 committer.time.seconds -= 1;
1457 }
1458 _ => break CommitId::from_bytes(git_id.as_bytes()),
1459 }
1460 };
1461
1462 // Everything up to this point had no permanent effect on the repo except
1463 // GC-able objects
1464 locked_repo
1465 .edit_reference(to_no_gc_ref_update(&id))
1466 .map_err(|err| BackendError::Other(Box::new(err)))?;
1467
1468 // Update the signature to match the one that was actually written to the object
1469 // store
1470 contents.committer.timestamp.timestamp = MillisSinceEpoch(committer.time.seconds * 1000);
1471 let mut mut_table = table.start_mutation();
1472 mut_table.add_entry(id.to_bytes(), extras);
1473 self.save_extra_metadata_table(mut_table, &table_lock)?;
1474 Ok((id, contents))
1475 }
1476
1477 fn get_copy_records(
1478 &self,
1479 paths: Option<&[RepoPathBuf]>,
1480 root_id: &CommitId,
1481 head_id: &CommitId,
1482 ) -> BackendResult<BoxStream<'_, BackendResult<CopyRecord>>> {
1483 let repo = self.git_repo();
1484 let root_tree = self.read_tree_for_commit(&repo, root_id)?;
1485 let head_tree = self.read_tree_for_commit(&repo, head_id)?;
1486
1487 let change_to_copy_record =
1488 |change: gix::object::tree::diff::Change| -> BackendResult<Option<CopyRecord>> {
1489 let gix::object::tree::diff::Change::Rewrite {
1490 source_location,
1491 source_entry_mode,
1492 source_id,
1493 entry_mode: dest_entry_mode,
1494 location: dest_location,
1495 ..
1496 } = change
1497 else {
1498 return Ok(None);
1499 };
1500 // TODO: Renamed symlinks cannot be returned because CopyRecord
1501 // expects `source_file: FileId`.
1502 if !source_entry_mode.is_blob() || !dest_entry_mode.is_blob() {
1503 return Ok(None);
1504 }
1505
1506 let source = str::from_utf8(source_location)
1507 .map_err(|err| to_invalid_utf8_err(err, root_id))?;
1508 let dest = str::from_utf8(dest_location)
1509 .map_err(|err| to_invalid_utf8_err(err, head_id))?;
1510
1511 let target = RepoPathBuf::from_internal_string(dest).unwrap();
1512 if !paths.is_none_or(|paths| paths.contains(&target)) {
1513 return Ok(None);
1514 }
1515
1516 Ok(Some(CopyRecord {
1517 target,
1518 target_commit: head_id.clone(),
1519 source: RepoPathBuf::from_internal_string(source).unwrap(),
1520 source_file: FileId::from_bytes(source_id.as_bytes()),
1521 source_commit: root_id.clone(),
1522 }))
1523 };
1524
1525 let mut records: Vec<BackendResult<CopyRecord>> = Vec::new();
1526 root_tree
1527 .changes()
1528 .map_err(|err| BackendError::Other(err.into()))?
1529 .options(|opts| {
1530 opts.track_path().track_rewrites(Some(gix::diff::Rewrites {
1531 copies: Some(gix::diff::rewrites::Copies {
1532 source: gix::diff::rewrites::CopySource::FromSetOfModifiedFiles,
1533 percentage: Some(0.5),
1534 }),
1535 percentage: Some(0.5),
1536 limit: 1000,
1537 track_empty: false,
1538 }));
1539 })
1540 .for_each_to_obtain_tree_with_cache(
1541 &head_tree,
1542 &mut self.new_diff_platform()?,
1543 |change| -> BackendResult<_> {
1544 match change_to_copy_record(change) {
1545 Ok(None) => {}
1546 Ok(Some(change)) => records.push(Ok(change)),
1547 Err(err) => records.push(Err(err)),
1548 }
1549 Ok(gix::object::tree::diff::Action::Continue(()))
1550 },
1551 )
1552 .map_err(|err| BackendError::Other(err.into()))?;
1553 Ok(futures::stream::iter(records).boxed())
1554 }
1555
1556 #[tracing::instrument(skip(self, index))]
1557 fn gc(&self, index: &dyn Index, keep_newer: SystemTime) -> BackendResult<()> {
1558 let git_repo = self.lock_git_repo();
1559 let new_heads = index
1560 .all_heads_for_gc()
1561 .map_err(|err| BackendError::Other(err.into()))?
1562 .filter(|id| *id != self.root_commit_id);
1563 recreate_no_gc_refs(&git_repo, new_heads, keep_newer)?;
1564
1565 // No locking is needed since we aren't going to add new "commits".
1566 let table = self.cached_extra_metadata_table()?;
1567 // TODO: remove unreachable entries from extras table if segment file
1568 // mtime <= keep_newer? (it won't be consistent with no-gc refs
1569 // preserved by the keep_newer timestamp though)
1570 self.extra_metadata_store
1571 .gc(&table, keep_newer)
1572 .map_err(|err| BackendError::Other(err.into()))?;
1573
1574 run_git_gc(
1575 self.git_executable.as_ref(),
1576 self.git_repo_path(),
1577 keep_newer,
1578 )
1579 .map_err(|err| BackendError::Other(err.into()))?;
1580 // Since "git gc" will move loose refs into packed refs, in-memory
1581 // packed-refs cache should be invalidated without relying on mtime.
1582 git_repo.refs.force_refresh_packed_buffer().ok();
1583 Ok(())
1584 }
1585 }
1586
1587 /// Write a tree conflict as a special tree with `.jjconflict-base-N` and
1588 /// `.jjconflict-side-N` subtrees. This ensure that the parts are not GC'd.
1589 /// Also includes a `JJ-CONFLICT-README` file explaining why these trees are
1590 /// present. The rest of the tree is copied from the first term of the conflict,
1591 /// which prevents editors with Git support from highlighting all files as new.
1592 fn write_tree_conflict(
1593 repo: &gix::Repository,
1594 conflict: &Merge<TreeId>,
1595 ) -> BackendResult<gix::ObjectId> {
1596 // Tree entries to be written must be sorted by Entry::filename().
1597 let mut entries = itertools::chain(
1598 conflict
1599 .removes()
1600 .enumerate()
1601 .map(|(i, tree_id)| (format!(".jjconflict-base-{i}"), tree_id)),
1602 conflict
1603 .adds()
1604 .enumerate()
1605 .map(|(i, tree_id)| (format!(".jjconflict-side-{i}"), tree_id)),
1606 )
1607 .map(|(name, tree_id)| gix::objs::tree::Entry {
1608 mode: gix::object::tree::EntryKind::Tree.into(),
1609 filename: name.into(),
1610 oid: gix::ObjectId::from_bytes_or_panic(tree_id.as_bytes()),
1611 })
1612 .collect_vec();
1613 let readme_id = repo
1614 .write_blob(
1615 r#"This commit was made by jj, https://jj-vcs.dev/.
1616 The commit contains file conflicts, and therefore looks wrong when used with
1617 plain Git or other tools that are unfamiliar with jj.
1618
1619 The .jjconflict-* directories represent the different inputs to the conflict.
1620 For details, see
1621 https://docs.jj-vcs.dev/latest/git-compatibility/#format-mapping-details
1622
1623 If you see this file in your working copy, it probably means that you used a
1624 regular `git` command to check out a conflicted commit. Use `jj abandon` to
1625 recover.
1626 "#,
1627 )
1628 .map_err(|err| {
1629 BackendError::Other(format!("Failed to write README for conflict tree: {err}").into())
1630 })?
1631 .detach();
1632 entries.push(gix::objs::tree::Entry {
1633 mode: gix::object::tree::EntryKind::Blob.into(),
1634 filename: JJ_CONFLICT_README_FILE_NAME.into(),
1635 oid: readme_id,
1636 });
1637 let first_tree_id = conflict.first();
1638 let first_tree = repo
1639 .find_tree(gix::ObjectId::from_bytes_or_panic(first_tree_id.as_bytes()))
1640 .map_err(|err| to_read_object_err(err, first_tree_id))?;
1641 for entry in first_tree.iter() {
1642 let entry = entry.map_err(|err| to_read_object_err(err, first_tree_id))?;
1643 if !entry.filename().starts_with(b".jjconflict")
1644 && entry.filename() != JJ_CONFLICT_README_FILE_NAME
1645 {
1646 entries.push(entry.detach().into());
1647 }
1648 }
1649 entries.sort_unstable();
1650 let id = repo
1651 .write_object(gix::objs::Tree { entries })
1652 .map_err(|err| BackendError::WriteObject {
1653 object_type: "tree",
1654 source: Box::new(err),
1655 })?;
1656 Ok(id.detach())
1657 }
1658
1659 #[cfg(test)]
1660 mod tests {
1661 use assert_matches::assert_matches;
1662 use gix::date::parse::TimeBuf;
1663 use gix::objs::CommitRef;
1664 use indoc::indoc;
1665 use test_case::test_case;
1666
1667 use super::*;
1668 use crate::config::StackedConfig;
1669 use crate::content_hash::blake2b_hash;
1670 use crate::hex_util;
1671 use crate::tests::TestResult;
1672 use crate::tests::new_temp_dir;
1673
1674 const GIT_USER: &str = "Someone";
1675 const GIT_EMAIL: &str = "[email protected]";
1676
1677 fn git_config() -> Vec<bstr::BString> {
1678 vec![
1679 format!("user.name = {GIT_USER}").into(),
1680 format!("user.email = {GIT_EMAIL}").into(),
1681 "init.defaultBranch = master".into(),
1682 ]
1683 }
1684
1685 fn open_options() -> gix::open::Options {
1686 gix::open::Options::isolated()
1687 .config_overrides(git_config())
1688 .strict_config(true)
1689 }
1690
1691 fn git_init(directory: impl AsRef<Path>, object_hash: gix::hash::Kind) -> gix::Repository {
1692 gix::ThreadSafeRepository::init_opts(
1693 directory,
1694 gix::create::Kind::WithWorktree,
1695 gix::create::Options {
1696 object_hash: Some(object_hash),
1697 ..Default::default()
1698 },
1699 open_options(),
1700 )
1701 .unwrap()
1702 .to_thread_local()
1703 }
1704
1705 #[test]
1706 fn open_git_repo_at_workdir() -> TestResult {
1707 let settings = user_settings();
1708 let temp_dir = new_temp_dir();
1709 let store_path = temp_dir.path().join("store");
1710 fs::create_dir(&store_path)?;
1711
1712 let git_repo_path = temp_dir.path().join("git1");
1713 let git_repo = git_init(&git_repo_path, gix::hash::Kind::default());
1714 let other_git_repo_path = temp_dir.path().join("git2");
1715 let _other_git_repo = git_init(&other_git_repo_path, gix::hash::Kind::default());
1716
1717 let worktree_dir = temp_dir.path().join("git1-wt");
1718 let output = Command::new("git")
1719 .args(["worktree", "add", "--orphan"])
1720 .arg(&worktree_dir)
1721 .current_dir(&git_repo_path)
1722 .output()?;
1723 assert!(output.status.success(), "{output:?}");
1724
1725 let backend = GitBackend::init_external(&settings, &store_path, git_repo.path())?;
1726
1727 assert_matches!(
1728 backend.open_git_repo_at_workdir(&git_repo_path),
1729 Ok(repo) if repo.workdir() == Some(backend.git_repo().workdir().unwrap())
1730 );
1731 assert_matches!(
1732 backend.open_git_repo_at_workdir(&worktree_dir),
1733 Ok(repo) if repo.workdir() == Some(worktree_dir.as_ref())
1734 );
1735 assert_matches!(
1736 backend.open_git_repo_at_workdir(&temp_dir.path().join("unknown")),
1737 Err(GitRepoAtWorkdirError::NotFound { .. })
1738 );
1739 assert_matches!(
1740 backend.open_git_repo_at_workdir(&other_git_repo_path),
1741 Err(GitRepoAtWorkdirError::Unrelated { .. })
1742 );
1743
1744 Ok(())
1745 }
1746
1747 #[test_case(gix::hash::Kind::Sha1 ; "sha1")]
1748 #[test_case(gix::hash::Kind::Sha256; "sha256")]
1749 fn read_plain_git_commit(object_hash: gix::hash::Kind) -> TestResult {
1750 let settings = user_settings();
1751 let temp_dir = new_temp_dir();
1752 let store_path = temp_dir.path();
1753 let git_repo_path = temp_dir.path().join("git");
1754 let git_repo = git_init(git_repo_path, object_hash);
1755
1756 // Add a commit with some files in
1757 let blob1 = git_repo.write_blob(b"content1")?.detach();
1758 let blob2 = git_repo.write_blob(b"normal")?.detach();
1759 let mut dir_tree_editor = git_repo.empty_tree().edit()?;
1760 dir_tree_editor.upsert("normal", gix::object::tree::EntryKind::Blob, blob1)?;
1761 dir_tree_editor.upsert("symlink", gix::object::tree::EntryKind::Link, blob2)?;
1762 let dir_tree_id = dir_tree_editor.write()?.detach();
1763 let mut root_tree_builder = git_repo.empty_tree().edit()?;
1764 root_tree_builder.upsert("dir", gix::object::tree::EntryKind::Tree, dir_tree_id)?;
1765 let root_tree_id = root_tree_builder.write()?.detach();
1766 let git_author = gix::actor::Signature {
1767 name: "git author".into(),
1768 email: "[email protected]".into(),
1769 time: gix::date::Time::new(1000, 60 * 60),
1770 };
1771 let git_committer = gix::actor::Signature {
1772 name: "git committer".into(),
1773 email: "[email protected]".into(),
1774 time: gix::date::Time::new(2000, -480 * 60),
1775 };
1776 let git_commit_id = git_repo
1777 .commit_as(
1778 git_committer.to_ref(&mut TimeBuf::default()),
1779 git_author.to_ref(&mut TimeBuf::default()),
1780 "refs/heads/dummy",
1781 "git commit message",
1782 root_tree_id,
1783 [] as [gix::ObjectId; 0],
1784 )?
1785 .detach();
1786 git_repo.find_reference("refs/heads/dummy")?.delete()?;
1787 // The change id is the leading reverse bits of the commit id
1788 let (commit_id, change_id) = match object_hash {
1789 gix::hash::Kind::Sha1 => (
1790 CommitId::from_hex("efdcea5ca4b3658149f899ca7feee6876d077263"),
1791 ChangeId::from_hex("c64ee0b6e16777fe53991f9281a6cd25"),
1792 ),
1793 gix::hash::Kind::Sha256 => (
1794 CommitId::from_hex(
1795 "64366022e4938d697015b775945be93aea6d3fc221feeaf7c516420262e3fa54",
1796 ),
1797 ChangeId::from_hex("2a5fc746404268a3ef577f8443fcb657"),
1798 ),
1799 _ => unreachable!(),
1800 };
1801 // Check that the git commit above got the hash we expect
1802 assert_eq!(
1803 git_commit_id.as_bytes(),
1804 commit_id.as_bytes(),
1805 "{git_commit_id:?} vs {commit_id:?}"
1806 );
1807
1808 // Add an empty commit on top
1809 let git_commit_id2 = git_repo
1810 .commit_as(
1811 git_committer.to_ref(&mut TimeBuf::default()),
1812 git_author.to_ref(&mut TimeBuf::default()),
1813 "refs/heads/dummy2",
1814 "git commit message 2",
1815 root_tree_id,
1816 [git_commit_id],
1817 )?
1818 .detach();
1819 git_repo.find_reference("refs/heads/dummy2")?.delete()?;
1820 let commit_id2 = CommitId::from_bytes(git_commit_id2.as_bytes());
1821
1822 let backend = GitBackend::init_external(&settings, store_path, git_repo.path())?;
1823
1824 // Import the head commit and its ancestors
1825 backend.import_head_commits([&commit_id2])?;
1826 // Ref should be created only for the head commit
1827 let git_refs = backend
1828 .git_repo()
1829 .references()?
1830 .prefixed("refs/jj/keep/")?
1831 .map(|git_ref| git_ref.unwrap().id().detach())
1832 .collect_vec();
1833 assert_eq!(git_refs, vec![git_commit_id2]);
1834
1835 let commit = backend.read_commit(&commit_id).block_on()?;
1836 assert_eq!(&commit.change_id, &change_id);
1837 assert_eq!(
1838 commit.parents,
1839 vec![CommitId::from_bytes(object_hash.null_ref().as_bytes())]
1840 );
1841 assert_eq!(commit.predecessors, vec![]);
1842 assert_eq!(
1843 commit.root_tree,
1844 Merge::resolved(TreeId::from_bytes(root_tree_id.as_bytes()))
1845 );
1846 assert_eq!(commit.description, "git commit message");
1847 assert_eq!(commit.author.name, "git author");
1848 assert_eq!(commit.author.email, "[email protected]");
1849 assert_eq!(
1850 commit.author.timestamp.timestamp,
1851 MillisSinceEpoch(1000 * 1000)
1852 );
1853 assert_eq!(commit.author.timestamp.tz_offset, 60);
1854 assert_eq!(commit.committer.name, "git committer");
1855 assert_eq!(commit.committer.email, "[email protected]");
1856 assert_eq!(
1857 commit.committer.timestamp.timestamp,
1858 MillisSinceEpoch(2000 * 1000)
1859 );
1860 assert_eq!(commit.committer.timestamp.tz_offset, -480);
1861
1862 let root_tree = backend
1863 .read_tree(
1864 RepoPath::root(),
1865 &TreeId::from_bytes(root_tree_id.as_bytes()),
1866 )
1867 .block_on()?;
1868 let mut root_entries = root_tree.entries();
1869 let dir = root_entries.next().unwrap();
1870 assert_eq!(root_entries.next(), None);
1871 assert_eq!(dir.name().as_internal_str(), "dir");
1872 assert_eq!(
1873 dir.value(),
1874 &TreeValue::Tree(TreeId::from_bytes(dir_tree_id.as_bytes()))
1875 );
1876
1877 let dir_tree = backend
1878 .read_tree(
1879 RepoPath::from_internal_string("dir")?,
1880 &TreeId::from_bytes(dir_tree_id.as_bytes()),
1881 )
1882 .block_on()?;
1883 let mut entries = dir_tree.entries();
1884 let file = entries.next().unwrap();
1885 let symlink = entries.next().unwrap();
1886 assert_eq!(entries.next(), None);
1887 assert_eq!(file.name().as_internal_str(), "normal");
1888 assert_eq!(
1889 file.value(),
1890 &TreeValue::File {
1891 id: FileId::from_bytes(blob1.as_bytes()),
1892 executable: false,
1893 copy_id: CopyId::placeholder(),
1894 }
1895 );
1896 assert_eq!(symlink.name().as_internal_str(), "symlink");
1897 assert_eq!(
1898 symlink.value(),
1899 &TreeValue::Symlink(SymlinkId::from_bytes(blob2.as_bytes()))
1900 );
1901
1902 let commit2 = backend.read_commit(&commit_id2).block_on()?;
1903 assert_eq!(commit2.parents, vec![commit_id.clone()]);
1904 assert_eq!(commit.predecessors, vec![]);
1905 assert_eq!(
1906 commit.root_tree,
1907 Merge::resolved(TreeId::from_bytes(root_tree_id.as_bytes()))
1908 );
1909 Ok(())
1910 }
1911
1912 #[test_case(gix::hash::Kind::Sha1 ; "sha1")]
1913 #[test_case(gix::hash::Kind::Sha256; "sha256")]
1914 fn read_git_commit_without_importing(object_hash: gix::hash::Kind) -> TestResult {
1915 let settings = user_settings();
1916 let temp_dir = new_temp_dir();
1917 let store_path = temp_dir.path();
1918 let git_repo_path = temp_dir.path().join("git");
1919 let git_repo = git_init(&git_repo_path, object_hash);
1920
1921 let signature = gix::actor::Signature {
1922 name: GIT_USER.into(),
1923 email: GIT_EMAIL.into(),
1924 time: gix::date::Time::now_utc(),
1925 };
1926 let empty_tree_id = gix::ObjectId::empty_tree(git_repo.object_hash());
1927 let git_commit_id = git_repo.commit_as(
1928 signature.to_ref(&mut TimeBuf::default()),
1929 signature.to_ref(&mut TimeBuf::default()),
1930 "refs/heads/main",
1931 "git commit message",
1932 empty_tree_id,
1933 [] as [gix::ObjectId; 0],
1934 )?;
1935
1936 let backend = GitBackend::init_external(&settings, store_path, git_repo.path())?;
1937
1938 // read_commit() without import_head_commits() works as of now. This might be
1939 // changed later.
1940 assert!(
1941 backend
1942 .read_commit(&CommitId::from_bytes(git_commit_id.as_bytes()))
1943 .block_on()
1944 .is_ok()
1945 );
1946 assert!(
1947 backend
1948 .cached_extra_metadata_table()?
1949 .get_value(git_commit_id.as_bytes())
1950 .is_some(),
1951 "extra metadata should have been be created"
1952 );
1953 Ok(())
1954 }
1955
1956 #[test_case(gix::hash::Kind::Sha1 ; "sha1")]
1957 #[test_case(gix::hash::Kind::Sha256; "sha256")]
1958 fn read_signed_git_commit(object_hash: gix::hash::Kind) -> TestResult {
1959 let settings = user_settings();
1960 let temp_dir = new_temp_dir();
1961 let store_path = temp_dir.path();
1962 let git_repo_path = temp_dir.path().join("git");
1963 let git_repo = git_init(git_repo_path, object_hash);
1964
1965 let signature = gix::actor::Signature {
1966 name: GIT_USER.into(),
1967 email: GIT_EMAIL.into(),
1968 time: gix::date::Time::now_utc(),
1969 };
1970 let empty_tree_id = gix::ObjectId::empty_tree(git_repo.object_hash());
1971
1972 let secure_sig =
1973 "here are some ASCII bytes to be used as a test signature\n\ndefinitely not PGP\n";
1974
1975 let mut commit = gix::objs::Commit {
1976 tree: empty_tree_id,
1977 parents: smallvec::SmallVec::new(),
1978 author: signature.clone(),
1979 committer: signature.clone(),
1980 encoding: None,
1981 message: "git commit message".into(),
1982 extra_headers: Vec::new(),
1983 };
1984
1985 let mut commit_buf = Vec::new();
1986 commit.write_to(&mut commit_buf)?;
1987 let commit_str = str::from_utf8(&commit_buf)?;
1988
•1989 commit
1990 .extra_headers
1991 // TODO: should this conditionally become gpgsig-sha256 once gix supports it?
1992 .push(("gpgsig".into(), secure_sig.into()));
1993
1994 let git_commit_id = git_repo.write_object(&commit)?;
1995
1996 let backend = GitBackend::init_external(&settings, store_path, git_repo.path())?;
1997
1998 let commit = backend
1999 .read_commit(&CommitId::from_bytes(git_commit_id.as_bytes()))
2000 .block_on()?;
2001
2002 let sig = commit.secure_sig.expect("failed to read the signature");
2003
2004 // converting to string for nicer assert diff
2005 assert_eq!(str::from_utf8(&sig.sig)?, secure_sig);
2006 assert_eq!(str::from_utf8(&sig.data)?, commit_str);
2007 Ok(())
2008 }
2009
2010 #[test]
2011 fn change_id_parsing() {
2012 let id = |commit_object_bytes: &[u8]| {
2013 extract_change_id_from_commit(
2014 &CommitRef::from_bytes(commit_object_bytes, gix::hash::Kind::Sha1).unwrap(),
2015 )
2016 };
2017
2018 let commit_with_id = indoc! {b"
2019 tree 126799bf8058d1b5c531e93079f4fe79733920dd
2020 parent bd50783bdf38406dd6143475cd1a3c27938db2ee
2021 author JJ Fan <[email protected]> 1757112665 -0700
2022 committer JJ Fan <[email protected]> 1757359886 -0700
2023 extra-header blah
2024 change-id lkonztmnvsxytrwkxpvuutrmompwylqq
2025
2026 test-commit
2027 "};
2028 insta::assert_compact_debug_snapshot!(
2029 id(commit_with_id),
2030 @r#"Some(ChangeId("efbc06dc4721683f2a45568dbda31e99"))"#
2031 );
2032
2033 let commit_without_id = indoc! {b"
2034 tree 126799bf8058d1b5c531e93079f4fe79733920dd
2035 parent bd50783bdf38406dd6143475cd1a3c27938db2ee
2036 author JJ Fan <[email protected]> 1757112665 -0700
2037 committer JJ Fan <[email protected]> 1757359886 -0700
2038 extra-header blah
2039
2040 no id in header
2041 "};
2042 insta::assert_compact_debug_snapshot!(
2043 id(commit_without_id),
2044 @"None"
2045 );
2046
2047 let commit = indoc! {b"
2048 tree 126799bf8058d1b5c531e93079f4fe79733920dd
2049 parent bd50783bdf38406dd6143475cd1a3c27938db2ee
2050 author JJ Fan <[email protected]> 1757112665 -0700
2051 committer JJ Fan <[email protected]> 1757359886 -0700
2052 change-id lkonztmnvsxytrwkxpvuutrmompwylqq
2053 extra-header blah
2054 change-id abcabcabcabcabcabcabcabcabcabcab
2055
2056 valid change id first
2057 "};
2058 insta::assert_compact_debug_snapshot!(
2059 id(commit),
2060 @r#"Some(ChangeId("efbc06dc4721683f2a45568dbda31e99"))"#
2061 );
2062
2063 // We only look at the first change id if multiple are present, so this should
2064 // error
2065 let commit = indoc! {b"
2066 tree 126799bf8058d1b5c531e93079f4fe79733920dd
2067 parent bd50783bdf38406dd6143475cd1a3c27938db2ee
2068 author JJ Fan <[email protected]> 1757112665 -0700
2069 committer JJ Fan <[email protected]> 1757359886 -0700
2070 change-id abcabcabcabcabcabcabcabcabcabcab
2071 extra-header blah
2072 change-id lkonztmnvsxytrwkxpvuutrmompwylqq
2073
2074 valid change id first
2075 "};
2076 insta::assert_compact_debug_snapshot!(
2077 id(commit),
2078 @"None"
2079 );
2080 }
2081
2082 #[test_case(gix::hash::Kind::Sha1 ; "sha1")]
2083 #[test_case(gix::hash::Kind::Sha256; "sha256")]
2084 fn round_trip_change_id_via_git_header(object_hash: gix::hash::Kind) -> TestResult {
2085 let settings = user_settings();
2086 let temp_dir = new_temp_dir();
2087
2088 let store_path = temp_dir.path().join("store");
2089 fs::create_dir(&store_path)?;
2090 let empty_store_path = temp_dir.path().join("empty_store");
2091 fs::create_dir(&empty_store_path)?;
2092 let git_repo_path = temp_dir.path().join("git");
2093 let git_repo = git_init(git_repo_path, object_hash);
2094
2095 let backend = GitBackend::init_external(&settings, &store_path, git_repo.path())?;
2096 let original_change_id = ChangeId::from_hex("1111eeee1111eeee1111eeee1111eeee");
2097 let commit = Commit {
2098 parents: vec![backend.root_commit_id().clone()],
2099 predecessors: vec![],
2100 root_tree: Merge::resolved(backend.empty_tree_id().clone()),
2101 conflict_labels: Merge::resolved(String::new()),
2102 change_id: original_change_id.clone(),
2103 description: "initial".to_string(),
2104 author: create_signature(),
2105 committer: create_signature(),
2106 secure_sig: None,
2107 };
2108
2109 let (initial_commit_id, _init_commit) = backend.write_commit(commit, None).block_on()?;
2110 let commit = backend.read_commit(&initial_commit_id).block_on()?;
2111 assert_eq!(
2112 commit.change_id, original_change_id,
2113 "The change-id header did not roundtrip"
2114 );
2115
2116 // Because of how change ids are also persisted in extra proto files,
2117 // initialize a new store without those files, but reuse the same git
2118 // storage. This change-id must be derived from the git commit header.
2119 let no_extra_backend =
2120 GitBackend::init_external(&settings, &empty_store_path, git_repo.path())?;
2121 let no_extra_commit = no_extra_backend
2122 .read_commit(&initial_commit_id)
2123 .block_on()?;
2124
2125 assert_eq!(
2126 no_extra_commit.change_id, original_change_id,
2127 "The change-id header did not roundtrip"
2128 );
2129 Ok(())
2130 }
2131
2132 #[test]
2133 fn read_empty_string_placeholder() {
2134 let git_signature1 = gix::actor::Signature {
2135 name: EMPTY_STRING_PLACEHOLDER.into(),
2136 email: "[email protected]".into(),
2137 time: gix::date::Time::new(1000, 60 * 60),
2138 };
2139 let signature1 = signature_from_git(git_signature1.to_ref(&mut TimeBuf::default()));
2140 assert!(signature1.name.is_empty());
2141 assert_eq!(signature1.email, "[email protected]");
2142 let git_signature2 = gix::actor::Signature {
2143 name: "git committer".into(),
2144 email: EMPTY_STRING_PLACEHOLDER.into(),
2145 time: gix::date::Time::new(2000, -480 * 60),
2146 };
2147 let signature2 = signature_from_git(git_signature2.to_ref(&mut TimeBuf::default()));
2148 assert_eq!(signature2.name, "git committer");
2149 assert!(signature2.email.is_empty());
2150 }
2151
2152 #[test]
2153 fn write_empty_string_placeholder() {
2154 let signature1 = Signature {
2155 name: "".to_string(),
2156 email: "[email protected]".to_string(),
2157 timestamp: Timestamp {
2158 timestamp: MillisSinceEpoch(0),
2159 tz_offset: 0,
2160 },
2161 };
2162 let git_signature1 = signature_to_git(&signature1);
2163 assert_eq!(git_signature1.name, EMPTY_STRING_PLACEHOLDER);
2164 assert_eq!(git_signature1.email, "[email protected]");
2165 let signature2 = Signature {
2166 name: "Someone".to_string(),
2167 email: "".to_string(),
2168 timestamp: Timestamp {
2169 timestamp: MillisSinceEpoch(0),
2170 tz_offset: 0,
2171 },
2172 };
2173 let git_signature2 = signature_to_git(&signature2);
2174 assert_eq!(git_signature2.name, "Someone");
2175 assert_eq!(git_signature2.email, EMPTY_STRING_PLACEHOLDER);
2176 }
2177
2178 /// Test that parents get written correctly
2179 #[test_case(gix::hash::Kind::Sha1 ; "sha1")]
2180 #[test_case(gix::hash::Kind::Sha256; "sha256")]
2181 fn git_commit_parents(object_hash: gix::hash::Kind) -> TestResult {
2182 let settings = user_settings();
2183 let temp_dir = new_temp_dir();
2184 let store_path = temp_dir.path();
2185 let git_repo_path = temp_dir.path().join("git");
2186 let git_repo = git_init(&git_repo_path, object_hash);
2187
2188 let backend = GitBackend::init_external(&settings, store_path, git_repo.path())?;
2189 let mut commit = Commit {
2190 parents: vec![],
2191 predecessors: vec![],
2192 root_tree: Merge::resolved(backend.empty_tree_id().clone()),
2193 conflict_labels: Merge::resolved(String::new()),
2194 change_id: ChangeId::from_hex("abc123"),
2195 description: "".to_string(),
2196 author: create_signature(),
2197 committer: create_signature(),
2198 secure_sig: None,
2199 };
2200
2201 let write_commit = |commit: Commit| -> BackendResult<(CommitId, Commit)> {
2202 backend.write_commit(commit, None).block_on()
2203 };
2204
2205 // No parents
2206 commit.parents = vec![];
2207 assert_matches!(
2208 write_commit(commit.clone()),
2209 Err(BackendError::Other(err)) if err.to_string().contains("no parents")
2210 );
2211
2212 // Only root commit as parent
2213 commit.parents = vec![backend.root_commit_id().clone()];
2214 let first_id = write_commit(commit.clone())?.0;
2215 let first_commit = backend.read_commit(&first_id).block_on()?;
2216 assert_eq!(first_commit, commit);
2217 let first_git_commit = git_repo.find_commit(git_id(&first_id))?;
2218 assert!(first_git_commit.parent_ids().collect_vec().is_empty());
2219
2220 // Only non-root commit as parent
2221 commit.parents = vec![first_id.clone()];
2222 let second_id = write_commit(commit.clone())?.0;
2223 let second_commit = backend.read_commit(&second_id).block_on()?;
2224 assert_eq!(second_commit, commit);
2225 let second_git_commit = git_repo.find_commit(git_id(&second_id))?;
2226 assert_eq!(
2227 second_git_commit.parent_ids().collect_vec(),
2228 vec![git_id(&first_id)]
2229 );
2230
2231 // Merge commit
2232 commit.parents = vec![first_id.clone(), second_id.clone()];
2233 let merge_id = write_commit(commit.clone())?.0;
2234 let merge_commit = backend.read_commit(&merge_id).block_on()?;
2235 assert_eq!(merge_commit, commit);
2236 let merge_git_commit = git_repo.find_commit(git_id(&merge_id))?;
2237 assert_eq!(
2238 merge_git_commit.parent_ids().collect_vec(),
2239 vec![git_id(&first_id), git_id(&second_id)]
2240 );
2241
2242 // Merge commit with root as one parent
2243 commit.parents = vec![first_id, backend.root_commit_id().clone()];
2244 assert_matches!(
2245 write_commit(commit),
2246 Err(BackendError::Unsupported(message)) if message.contains("root commit")
2247 );
2248 Ok(())
2249 }
2250
2251 #[test_case(gix::hash::Kind::Sha1 ; "sha1")]
2252 #[test_case(gix::hash::Kind::Sha256; "sha256")]
2253 fn write_tree_conflicts(object_hash: gix::hash::Kind) -> TestResult {
2254 let settings = user_settings();
2255 let temp_dir = new_temp_dir();
2256 let store_path = temp_dir.path();
2257 let git_repo_path = temp_dir.path().join("git");
2258 let git_repo = git_init(&git_repo_path, object_hash);
2259
2260 let backend = GitBackend::init_external(&settings, store_path, git_repo.path())?;
2261 let create_tree = |i| {
2262 let blob_id = git_repo.write_blob(format!("content {i}")).unwrap();
2263 let mut tree_builder = git_repo.empty_tree().edit().unwrap();
2264 tree_builder
2265 .upsert(
2266 format!("file{i}"),
2267 gix::object::tree::EntryKind::Blob,
2268 blob_id,
2269 )
2270 .unwrap();
2271 TreeId::from_bytes(tree_builder.write().unwrap().as_bytes())
2272 };
2273
2274 let root_tree = Merge::from_removes_adds(
2275 vec![create_tree(0), create_tree(1)],
2276 vec![create_tree(2), create_tree(3), create_tree(4)],
2277 );
2278 let mut commit = Commit {
2279 parents: vec![backend.root_commit_id().clone()],
2280 predecessors: vec![],
2281 root_tree: root_tree.clone(),
2282 conflict_labels: Merge::resolved(String::new()),
2283 change_id: ChangeId::from_hex("abc123"),
2284 description: "".to_string(),
2285 author: create_signature(),
2286 committer: create_signature(),
2287 secure_sig: None,
2288 };
2289
2290 let write_commit = |commit: Commit| -> BackendResult<(CommitId, Commit)> {
2291 backend.write_commit(commit, None).block_on()
2292 };
2293
2294 // When writing a tree-level conflict, the root tree on the git side has the
2295 // individual trees as subtrees.
2296 let read_commit_id = write_commit(commit.clone())?.0;
2297 let read_commit = backend.read_commit(&read_commit_id).block_on()?;
2298 assert_eq!(read_commit, commit);
2299 let git_commit = git_repo.find_commit(gix::ObjectId::from_bytes_or_panic(
2300 read_commit_id.as_bytes(),
2301 ))?;
2302 let git_tree = git_repo.find_tree(git_commit.tree_id()?)?;
2303 let jj_conflict_entries = git_tree
2304 .iter()
2305 .map(Result::unwrap)
2306 .filter(|entry| {
2307 entry.filename().starts_with(b".jjconflict")
2308 || entry.filename() == JJ_CONFLICT_README_FILE_NAME
2309 })
2310 .collect_vec();
2311 assert!(
2312 jj_conflict_entries
2313 .iter()
2314 .filter(|entry| entry.filename() != JJ_CONFLICT_README_FILE_NAME)
2315 .all(|entry| entry.mode().value() == 0o040000)
2316 );
2317 let mut iter = jj_conflict_entries.iter();
2318 let entry = iter.next().unwrap();
2319 assert_eq!(entry.filename(), b".jjconflict-base-0");
2320 assert_eq!(
2321 entry.id().as_bytes(),
2322 root_tree.get_remove(0).unwrap().as_bytes()
2323 );
2324 let entry = iter.next().unwrap();
2325 assert_eq!(entry.filename(), b".jjconflict-base-1");
2326 assert_eq!(
2327 entry.id().as_bytes(),
2328 root_tree.get_remove(1).unwrap().as_bytes()
2329 );
2330 let entry = iter.next().unwrap();
2331 assert_eq!(entry.filename(), b".jjconflict-side-0");
2332 assert_eq!(
2333 entry.id().as_bytes(),
2334 root_tree.get_add(0).unwrap().as_bytes()
2335 );
2336 let entry = iter.next().unwrap();
2337 assert_eq!(entry.filename(), b".jjconflict-side-1");
2338 assert_eq!(
2339 entry.id().as_bytes(),
2340 root_tree.get_add(1).unwrap().as_bytes()
2341 );
2342 let entry = iter.next().unwrap();
2343 assert_eq!(entry.filename(), b".jjconflict-side-2");
2344 assert_eq!(
2345 entry.id().as_bytes(),
2346 root_tree.get_add(2).unwrap().as_bytes()
2347 );
2348 let entry = iter.next().unwrap();
2349 assert_eq!(entry.filename(), b"JJ-CONFLICT-README");
2350 assert_eq!(entry.mode().value(), 0o100644);
2351 assert!(iter.next().is_none());
2352
2353 // When writing a single tree using the new format, it's represented by a
2354 // regular git tree.
2355 commit.root_tree = Merge::resolved(create_tree(5));
2356 let read_commit_id = write_commit(commit.clone())?.0;
2357 let read_commit = backend.read_commit(&read_commit_id).block_on()?;
2358 assert_eq!(read_commit, commit);
2359 let git_commit = git_repo.find_commit(gix::ObjectId::from_bytes_or_panic(
2360 read_commit_id.as_bytes(),
2361 ))?;
2362 assert_eq!(
2363 Merge::resolved(TreeId::from_bytes(git_commit.tree_id()?.as_bytes())),
2364 commit.root_tree
2365 );
2366 Ok(())
2367 }
2368
2369 #[test_case(gix::hash::Kind::Sha1 ; "sha1")]
2370 #[test_case(gix::hash::Kind::Sha256; "sha256")]
2371 fn commit_has_ref(object_hash: gix::hash::Kind) -> TestResult {
2372 let settings = user_settings();
2373 let temp_dir = new_temp_dir();
2374 let backend = GitBackend::init_internal(&settings, temp_dir.path(), object_hash)?;
2375 let git_repo = backend.git_repo();
2376 let signature = Signature {
2377 name: "Someone".to_string(),
2378 email: "[email protected]".to_string(),
2379 timestamp: Timestamp {
2380 timestamp: MillisSinceEpoch(0),
2381 tz_offset: 0,
2382 },
2383 };
2384 let commit = Commit {
2385 parents: vec![backend.root_commit_id().clone()],
2386 predecessors: vec![],
2387 root_tree: Merge::resolved(backend.empty_tree_id().clone()),
2388 conflict_labels: Merge::resolved(String::new()),
2389 change_id: ChangeId::new(vec![42; 16]),
2390 description: "initial".to_string(),
2391 author: signature.clone(),
2392 committer: signature,
2393 secure_sig: None,
2394 };
2395 let commit_id = backend.write_commit(commit, None).block_on()?.0;
2396 let git_refs = git_repo.references()?;
2397 let git_ref_ids: Vec<_> = git_refs
2398 .prefixed("refs/jj/keep/")?
2399 .map(|x| x.unwrap().id().detach())
2400 .collect();
2401 assert!(git_ref_ids.iter().any(|id| *id == git_id(&commit_id)));
2402
2403 // Concurrently-running GC deletes the ref, leaving the extra metadata.
2404 for git_ref in git_refs.prefixed("refs/jj/keep/")? {
2405 git_ref.unwrap().delete().unwrap();
2406 }
2407 // Re-imported commit should have new ref.
2408 backend.import_head_commits([&commit_id])?;
2409 let git_refs = git_repo.references()?;
2410 let git_ref_ids: Vec<_> = git_refs
2411 .prefixed("refs/jj/keep/")?
2412 .map(|x| x.unwrap().id().detach())
2413 .collect();
2414 assert!(git_ref_ids.iter().any(|id| *id == git_id(&commit_id)));
2415 Ok(())
2416 }
2417
2418 #[test_case(gix::hash::Kind::Sha1 ; "sha1")]
2419 #[test_case(gix::hash::Kind::Sha256; "sha256")]
2420 fn import_head_commits_duplicates(object_hash: gix::hash::Kind) -> TestResult {
2421 let settings = user_settings();
2422 let temp_dir = new_temp_dir();
2423 let backend = GitBackend::init_internal(&settings, temp_dir.path(), object_hash)?;
2424 let git_repo = backend.git_repo();
2425
2426 let signature = gix::actor::Signature {
2427 name: GIT_USER.into(),
2428 email: GIT_EMAIL.into(),
2429 time: gix::date::Time::now_utc(),
2430 };
2431 let empty_tree_id = gix::ObjectId::empty_tree(git_repo.object_hash());
2432 let git_commit_id = git_repo
2433 .commit_as(
2434 signature.to_ref(&mut TimeBuf::default()),
2435 signature.to_ref(&mut TimeBuf::default()),
2436 "refs/heads/main",
2437 "git commit message",
2438 empty_tree_id,
2439 [] as [gix::ObjectId; 0],
2440 )?
2441 .detach();
2442 let commit_id = CommitId::from_bytes(git_commit_id.as_bytes());
2443
2444 // Ref creation shouldn't fail because of duplicated head ids.
2445 backend.import_head_commits([&commit_id, &commit_id])?;
2446 assert!(
2447 git_repo
2448 .references()?
2449 .prefixed("refs/jj/keep/")?
2450 .any(|git_ref| git_ref.unwrap().id().detach() == git_commit_id)
2451 );
2452 Ok(())
2453 }
2454
2455 #[test_case(gix::hash::Kind::Sha1 ; "sha1")]
2456 #[test_case(gix::hash::Kind::Sha256; "sha256")]
2457 fn overlapping_git_commit_id(object_hash: gix::hash::Kind) -> TestResult {
2458 let settings = user_settings();
2459 let temp_dir = new_temp_dir();
2460 let backend = GitBackend::init_internal(&settings, temp_dir.path(), object_hash)?;
2461 let commit1 = Commit {
2462 parents: vec![backend.root_commit_id().clone()],
2463 predecessors: vec![],
2464 root_tree: Merge::resolved(backend.empty_tree_id().clone()),
2465 conflict_labels: Merge::resolved(String::new()),
2466 change_id: ChangeId::from_hex("7f0a7ce70354b22efcccf7bf144017c4"),
2467 description: "initial".to_string(),
2468 author: create_signature(),
2469 committer: create_signature(),
2470 secure_sig: None,
2471 };
2472
2473 let write_commit = |commit: Commit| -> BackendResult<(CommitId, Commit)> {
2474 backend.write_commit(commit, None).block_on()
2475 };
2476
2477 let (commit_id1, mut commit2) = write_commit(commit1)?;
2478 commit2.predecessors.push(commit_id1.clone());
2479 // `write_commit` should prevent the ids from being the same by changing the
2480 // committer timestamp of the commit it actually writes.
2481 let (commit_id2, mut actual_commit2) = write_commit(commit2.clone())?;
2482 // The returned matches the ID
2483 assert_eq!(backend.read_commit(&commit_id2).block_on()?, actual_commit2);
2484 assert_ne!(commit_id2, commit_id1);
2485 // The committer timestamp should differ
2486 assert_ne!(
2487 actual_commit2.committer.timestamp.timestamp,
2488 commit2.committer.timestamp.timestamp
2489 );
2490 // The rest of the commit should be the same
2491 actual_commit2.committer.timestamp.timestamp = commit2.committer.timestamp.timestamp;
2492 assert_eq!(actual_commit2, commit2);
2493 Ok(())
2494 }
2495
2496 #[test]
2497 fn write_signed_commit_sha1() -> TestResult {
2498 let (obj, sig) = write_signed_commit(gix::hash::Kind::Sha1)?;
2499 insta::assert_snapshot!(&obj, @"
2500 tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
2501 author Someone <[email protected]> 0 +0000
2502 committer Someone <[email protected]> 0 +0000
2503 change-id xpxpxpxpxpxpxpxpxpxpxpxpxpxpxpxp
2504 gpgsig test sig
2505 hash=03feb0caccbacce2e7b7bca67f4c82292dd487e669ed8a813120c9f82d3fd0801420a1f5d05e1393abfe4e9fc662399ec4a9a1898c5f1e547e0044a52bd4bd29
2506
2507 initial
2508 ");
2509 insta::assert_snapshot!(str::from_utf8(&sig.sig)?, @"
2510 test sig
2511 hash=03feb0caccbacce2e7b7bca67f4c82292dd487e669ed8a813120c9f82d3fd0801420a1f5d05e1393abfe4e9fc662399ec4a9a1898c5f1e547e0044a52bd4bd29
2512 ");
2513 insta::assert_snapshot!(str::from_utf8(&sig.data)?, @"
2514 tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
2515 author Someone <[email protected]> 0 +0000
2516 committer Someone <[email protected]> 0 +0000
2517 change-id xpxpxpxpxpxpxpxpxpxpxpxpxpxpxpxp
2518
2519 initial
2520 ");
2521 Ok(())
2522 }
2523
2524 #[test]
2525 fn write_signed_commit_sha256() -> TestResult {
2526 let (obj, sig) = write_signed_commit(gix::hash::Kind::Sha256)?;
2527 insta::assert_snapshot!(&obj, @"
2528 tree 6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321
2529 author Someone <[email protected]> 0 +0000
2530 committer Someone <[email protected]> 0 +0000
2531 change-id xpxpxpxpxpxpxpxpxpxpxpxpxpxpxpxp
•2532 gpgsig test sig
2533 hash=d6219e8e5169d409d115848dea4556b3accc76f3cd8dc9b128cc3fe9f71adae275f0e6ce9f98c581a89b960863b61c61b6479cdc20806009d63aecaaa82f4590
2534
2535 initial
2536 ");
2537 insta::assert_snapshot!(str::from_utf8(&sig.sig)?, @"
2538 test sig
2539 hash=d6219e8e5169d409d115848dea4556b3accc76f3cd8dc9b128cc3fe9f71adae275f0e6ce9f98c581a89b960863b61c61b6479cdc20806009d63aecaaa82f4590
2540 ");
2541 insta::assert_snapshot!(str::from_utf8(&sig.data)?, @"
2542 tree 6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321
2543 author Someone <[email protected]> 0 +0000
2544 committer Someone <[email protected]> 0 +0000
2545 change-id xpxpxpxpxpxpxpxpxpxpxpxpxpxpxpxp
2546
2547 initial
2548 ");
2549 Ok(())
2550 }
2551
2552 fn write_signed_commit(object_hash: gix::hash::Kind) -> TestResult<(String, SecureSig)> {
2553 let settings = user_settings();
2554 let temp_dir = new_temp_dir();
2555 let backend = GitBackend::init_internal(&settings, temp_dir.path(), object_hash)?;
2556
2557 let commit = Commit {
2558 parents: vec![backend.root_commit_id().clone()],
2559 predecessors: vec![],
2560 root_tree: Merge::resolved(backend.empty_tree_id().clone()),
2561 conflict_labels: Merge::resolved(String::new()),
2562 change_id: ChangeId::new(vec![42; 16]),
2563 description: "initial".to_string(),
2564 author: create_signature(),
2565 committer: create_signature(),
2566 secure_sig: None,
2567 };
2568
2569 let mut signer = |data: &_| {
2570 let hash: String = hex_util::encode_hex(&blake2b_hash(data));
2571 Ok(format!("test sig\nhash={hash}\n").into_bytes())
2572 };
2573
2574 let (id, commit) = backend
2575 .write_commit(commit, Some(&mut signer as &mut SigningFn))
2576 .block_on()?;
2577 let returned_sig = commit.secure_sig.expect("failed to return the signature");
2578
2579 let commit = backend.read_commit(&id).block_on()?;
2580 let sig = commit.secure_sig.expect("failed to read the signature");
2581 assert_eq!(&sig, &returned_sig);
2582
2583 let git_repo = backend.git_repo();
2584 let obj = git_repo.find_object(gix::ObjectId::from_bytes_or_panic(id.as_bytes()))?;
2585 Ok((String::from_utf8(obj.data.clone())?, sig))
2586 }
2587
2588 fn git_id(commit_id: &CommitId) -> gix::ObjectId {
2589 gix::ObjectId::from_bytes_or_panic(commit_id.as_bytes())
2590 }
2591
2592 fn create_signature() -> Signature {
2593 Signature {
2594 name: GIT_USER.to_string(),
2595 email: GIT_EMAIL.to_string(),
2596 timestamp: Timestamp {
2597 timestamp: MillisSinceEpoch(0),
2598 tz_offset: 0,
2599 },
2600 }
2601 }
2602
2603 // Not using testutils::user_settings() because there is a dependency cycle
2604 // 'jj_lib (1) -> testutils -> jj_lib (2)' which creates another distinct
2605 // UserSettings type. testutils returns jj_lib (2)'s UserSettings, whereas
2606 // our UserSettings type comes from jj_lib (1).
2607 fn user_settings() -> UserSettings {
2608 let config = StackedConfig::with_defaults();
2609 UserSettings::from_config(config).unwrap()
2610 }
2611 }