| 1 |
// Copyright 2025 The Jujutsu Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
use std::path::Path; |
| 16 |
use std::path::PathBuf; |
| 17 |
|
| 18 |
use gix::date::parse::TimeBuf; |
| 19 |
|
| 20 |
pub const GIT_USER: &str = "Someone"; |
| 21 |
pub const GIT_EMAIL: &str = "[email protected]"; |
| 22 |
|
| 23 |
fn git_config() -> Vec<bstr::BString> { |
| 24 |
vec![ |
| 25 |
format!("user.name = {GIT_USER}").into(), |
| 26 |
format!("user.email = {GIT_EMAIL}").into(), |
| 27 |
"init.defaultBranch = master".into(), |
| 28 |
] |
| 29 |
} |
| 30 |
|
| 31 |
fn open_options() -> gix::open::Options { |
| 32 |
gix::open::Options::isolated() |
| 33 |
.config_overrides(git_config()) |
| 34 |
.strict_config(true) |
| 35 |
} |
| 36 |
|
| 37 |
pub fn open(directory: impl Into<PathBuf>) -> gix::Repository { |
| 38 |
gix::open_opts(directory, open_options()).unwrap() |
| 39 |
} |
| 40 |
|
| 41 |
pub fn init(directory: impl AsRef<Path>) -> gix::Repository { |
| 42 |
gix::ThreadSafeRepository::init_opts( |
| 43 |
directory, |
| 44 |
gix::create::Kind::WithWorktree, |
| 45 |
gix::create::Options::default(), |
| 46 |
open_options(), |
| 47 |
) |
| 48 |
.unwrap() |
| 49 |
.to_thread_local() |
| 50 |
} |
| 51 |
|
| 52 |
pub fn init_bare(directory: impl AsRef<Path>) -> gix::Repository { |
| 53 |
gix::ThreadSafeRepository::init_opts( |
| 54 |
directory, |
| 55 |
gix::create::Kind::Bare, |
| 56 |
gix::create::Options::default(), |
| 57 |
open_options(), |
| 58 |
) |
| 59 |
.unwrap() |
| 60 |
.to_thread_local() |
| 61 |
} |
| 62 |
|
| 63 |
pub fn clone(dest_path: &Path, repo_url: &str, remote_name: Option<&str>) -> gix::Repository { |
| 64 |
let remote_name = remote_name.unwrap_or("origin"); |
| 65 |
// gitoxide doesn't write the remote HEAD as a symbolic link, which prevents |
| 66 |
// `jj` from getting it. |
| 67 |
// |
| 68 |
// This, plus the fact that the code to clone a repo in gitoxide is non-trivial, |
| 69 |
// makes it appealing to just spawn a git subprocess |
| 70 |
let output = std::process::Command::new("git") |
| 71 |
.args(["clone", repo_url, "--origin", remote_name]) |
| 72 |
.arg(dest_path) |
| 73 |
.output() |
| 74 |
.unwrap(); |
| 75 |
assert!( |
| 76 |
output.status.success(), |
| 77 |
"git cloning failed with {}:\n{}\n----- stderr -----\n{}", |
| 78 |
output.status, |
| 79 |
bstr::BString::from(output.stdout), |
| 80 |
bstr::BString::from(output.stderr), |
| 81 |
); |
| 82 |
|
| 83 |
open(dest_path) |
| 84 |
} |
| 85 |
|
| 86 |
/// Writes out gitlink entry pointing to the `target_repo`. |
| 87 |
pub fn create_gitlink(src_repo: impl AsRef<Path>, target_repo: impl AsRef<Path>) { |
| 88 |
let git_link_path = src_repo.as_ref().join(".git"); |
| 89 |
std::fs::write( |
| 90 |
git_link_path, |
| 91 |
format!("gitdir: {}\n", target_repo.as_ref().display()), |
| 92 |
) |
| 93 |
.unwrap(); |
| 94 |
} |
| 95 |
|
| 96 |
pub fn remove_config_value(mut repo: gix::Repository, section: &str, key: &str) { |
| 97 |
let mut config = repo.config_snapshot_mut(); |
| 98 |
let Ok(mut section) = config.section_mut(section, None) else { |
| 99 |
return; |
| 100 |
}; |
| 101 |
section.remove(key); |
| 102 |
|
| 103 |
let mut file = std::fs::File::create(config.meta().path.as_ref().unwrap()).unwrap(); |
| 104 |
config |
| 105 |
.write_to_filter(&mut file, |section| section.meta() == config.meta()) |
| 106 |
.unwrap(); |
| 107 |
} |
| 108 |
|
| 109 |
pub struct CommitResult { |
| 110 |
pub tree_id: gix::ObjectId, |
| 111 |
pub commit_id: gix::ObjectId, |
| 112 |
} |
| 113 |
|
| 114 |
pub fn add_commit( |
| 115 |
repo: &gix::Repository, |
| 116 |
reference: &str, |
| 117 |
filename: &str, |
| 118 |
content: &[u8], |
| 119 |
message: &str, |
| 120 |
parents: &[gix::ObjectId], |
| 121 |
) -> CommitResult { |
| 122 |
let blob_oid = repo.write_blob(content).unwrap(); |
| 123 |
|
| 124 |
let parent_tree_editor = parents.first().map(|commit_id| { |
| 125 |
repo.find_commit(*commit_id) |
| 126 |
.unwrap() |
| 127 |
.tree() |
| 128 |
.unwrap() |
| 129 |
.edit() |
| 130 |
.unwrap() |
| 131 |
}); |
| 132 |
let empty_tree_editor_fn = || { |
| 133 |
repo.edit_tree(gix::ObjectId::empty_tree(repo.object_hash())) |
| 134 |
.unwrap() |
| 135 |
}; |
| 136 |
|
| 137 |
let mut tree_editor = parent_tree_editor.unwrap_or_else(empty_tree_editor_fn); |
| 138 |
tree_editor |
| 139 |
.upsert(filename, gix::object::tree::EntryKind::Blob, blob_oid) |
| 140 |
.unwrap(); |
| 141 |
let tree_id = tree_editor.write().unwrap().detach(); |
| 142 |
let commit_id = write_commit(repo, reference, tree_id, message, parents); |
| 143 |
CommitResult { tree_id, commit_id } |
| 144 |
} |
| 145 |
|
| 146 |
pub fn write_commit( |
| 147 |
repo: &gix::Repository, |
| 148 |
reference: &str, |
| 149 |
tree_id: gix::ObjectId, |
| 150 |
message: &str, |
| 151 |
parents: &[gix::ObjectId], |
| 152 |
) -> gix::ObjectId { |
| 153 |
let signature = signature(); |
| 154 |
repo.commit_as( |
| 155 |
signature.to_ref(&mut TimeBuf::default()), |
| 156 |
signature.to_ref(&mut TimeBuf::default()), |
| 157 |
reference, |
| 158 |
message, |
| 159 |
tree_id, |
| 160 |
parents.iter().copied(), |
| 161 |
) |
| 162 |
.unwrap() |
| 163 |
.detach() |
| 164 |
} |
| 165 |
|
| 166 |
pub fn set_head_to_id(repo: &gix::Repository, target: gix::ObjectId) { |
| 167 |
repo.edit_reference(gix::refs::transaction::RefEdit { |
| 168 |
change: gix::refs::transaction::Change::Update { |
| 169 |
log: gix::refs::transaction::LogChange::default(), |
| 170 |
expected: gix::refs::transaction::PreviousValue::Any, |
| 171 |
new: gix::refs::Target::Object(target), |
| 172 |
}, |
| 173 |
name: "HEAD".try_into().unwrap(), |
| 174 |
deref: false, |
| 175 |
}) |
| 176 |
.unwrap(); |
| 177 |
} |
| 178 |
|
| 179 |
pub fn set_symbolic_reference(repo: &gix::Repository, reference: &str, target: &str) { |
| 180 |
use gix::refs::transaction; |
| 181 |
let change = transaction::Change::Update { |
| 182 |
log: transaction::LogChange { |
| 183 |
mode: transaction::RefLog::AndReference, |
| 184 |
force_create_reflog: true, |
| 185 |
message: "create symbolic reference".into(), |
| 186 |
}, |
| 187 |
expected: transaction::PreviousValue::Any, |
| 188 |
new: gix::refs::Target::Symbolic(target.try_into().unwrap()), |
| 189 |
}; |
| 190 |
|
| 191 |
let ref_edit = transaction::RefEdit { |
| 192 |
change, |
| 193 |
name: reference.try_into().unwrap(), |
| 194 |
deref: false, |
| 195 |
}; |
| 196 |
repo.edit_reference(ref_edit).unwrap(); |
| 197 |
} |
| 198 |
|
| 199 |
pub fn checkout_tree_index(repo: &gix::Repository, tree_id: gix::ObjectId) { |
| 200 |
let objects = repo.objects.clone(); |
| 201 |
let mut index = repo.index_from_tree(&tree_id).unwrap(); |
| 202 |
gix::worktree::state::checkout( |
| 203 |
&mut index, |
| 204 |
repo.workdir().unwrap(), |
| 205 |
objects, |
| 206 |
&gix::progress::Discard, |
| 207 |
&gix::progress::Discard, |
| 208 |
&gix::interrupt::IS_INTERRUPTED, |
| 209 |
gix::worktree::state::checkout::Options::default(), |
| 210 |
) |
| 211 |
.unwrap(); |
| 212 |
} |
| 213 |
|
| 214 |
fn signature() -> gix::actor::Signature { |
| 215 |
gix::actor::Signature { |
| 216 |
name: bstr::BString::from(GIT_USER), |
| 217 |
email: bstr::BString::from(GIT_EMAIL), |
| 218 |
time: gix::date::Time::new(0, 0), |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
#[derive(Debug, PartialEq, Eq)] |
| 223 |
pub enum GitStatusInfo { |
| 224 |
Index(IndexStatus), |
| 225 |
Worktree(WorktreeStatus), |
| 226 |
} |
| 227 |
|
| 228 |
#[derive(Debug, PartialEq, Eq)] |
| 229 |
pub enum IndexStatus { |
| 230 |
Addition, |
| 231 |
Deletion, |
| 232 |
Rename, |
| 233 |
Modification, |
| 234 |
} |
| 235 |
|
| 236 |
#[derive(Debug, PartialEq, Eq)] |
| 237 |
pub enum WorktreeStatus { |
| 238 |
Removed, |
| 239 |
Added, |
| 240 |
Modified, |
| 241 |
TypeChange, |
| 242 |
Renamed, |
| 243 |
Copied, |
| 244 |
IntentToAdd, |
| 245 |
Conflict, |
| 246 |
Ignored, |
| 247 |
} |
| 248 |
|
| 249 |
impl<'lhs, 'rhs> From<gix::diff::index::ChangeRef<'lhs, 'rhs>> for IndexStatus { |
| 250 |
fn from(value: gix::diff::index::ChangeRef<'lhs, 'rhs>) -> Self { |
| 251 |
match value { |
| 252 |
gix::diff::index::ChangeRef::Addition { .. } => Self::Addition, |
| 253 |
gix::diff::index::ChangeRef::Deletion { .. } => Self::Deletion, |
| 254 |
gix::diff::index::ChangeRef::Rewrite { .. } => Self::Rename, |
| 255 |
gix::diff::index::ChangeRef::Modification { .. } => Self::Modification, |
| 256 |
} |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
impl From<Option<gix::status::index_worktree::iter::Summary>> for WorktreeStatus { |
| 261 |
fn from(value: Option<gix::status::index_worktree::iter::Summary>) -> Self { |
| 262 |
match value { |
| 263 |
Some(gix::status::index_worktree::iter::Summary::Removed) => Self::Removed, |
| 264 |
Some(gix::status::index_worktree::iter::Summary::Added) => Self::Added, |
| 265 |
Some(gix::status::index_worktree::iter::Summary::Modified) => Self::Modified, |
| 266 |
Some(gix::status::index_worktree::iter::Summary::TypeChange) => Self::TypeChange, |
| 267 |
Some(gix::status::index_worktree::iter::Summary::Renamed) => Self::Renamed, |
| 268 |
Some(gix::status::index_worktree::iter::Summary::Copied) => Self::Copied, |
| 269 |
Some(gix::status::index_worktree::iter::Summary::IntentToAdd) => Self::IntentToAdd, |
| 270 |
Some(gix::status::index_worktree::iter::Summary::Conflict) => Self::Conflict, |
| 271 |
None => Self::Ignored, |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
impl From<gix::status::Item> for GitStatusInfo { |
| 277 |
fn from(value: gix::status::Item) -> Self { |
| 278 |
match value { |
| 279 |
gix::status::Item::TreeIndex(change) => Self::Index(change.into()), |
| 280 |
gix::status::Item::IndexWorktree(item) => Self::Worktree(item.summary().into()), |
| 281 |
} |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
#[derive(Debug, PartialEq, Eq)] |
| 286 |
pub struct GitStatus { |
| 287 |
path: String, |
| 288 |
status: GitStatusInfo, |
| 289 |
} |
| 290 |
|
| 291 |
impl From<gix::status::Item> for GitStatus { |
| 292 |
fn from(value: gix::status::Item) -> Self { |
| 293 |
let path = value.location().to_string(); |
| 294 |
let status = value.into(); |
| 295 |
Self { path, status } |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
pub fn status(repo: &gix::Repository) -> Vec<GitStatus> { |
| 300 |
let mut status: Vec<GitStatus> = repo |
| 301 |
.status(gix::progress::Discard) |
| 302 |
.unwrap() |
| 303 |
.untracked_files(gix::status::UntrackedFiles::Files) |
| 304 |
.dirwalk_options(|options| { |
| 305 |
options.emit_ignored(Some(gix::dir::walk::EmissionMode::Matching)) |
| 306 |
}) |
| 307 |
.into_iter(None) |
| 308 |
.unwrap() |
| 309 |
.map(Result::unwrap) |
| 310 |
.map(|x| x.into()) |
| 311 |
.collect(); |
| 312 |
|
| 313 |
status.sort_by(|a, b| a.path.cmp(&b.path)); |
| 314 |
status |
| 315 |
} |
| 316 |
|
| 317 |
pub struct IndexManager<'a> { |
| 318 |
index: gix::index::File, |
| 319 |
repo: &'a gix::Repository, |
| 320 |
} |
| 321 |
|
| 322 |
impl<'a> IndexManager<'a> { |
| 323 |
pub fn new(repo: &'a gix::Repository) -> Self { |
| 324 |
// This would be equivalent to repo.open_index_or_empty() if such |
| 325 |
// function existed. |
| 326 |
let index = repo.index_or_empty().unwrap(); |
| 327 |
let index = gix::index::File::clone(&index); // unshare |
| 328 |
Self { index, repo } |
| 329 |
} |
| 330 |
|
| 331 |
pub fn add_file(&mut self, name: &str, data: &[u8]) { |
| 332 |
std::fs::write(self.repo.workdir().unwrap().join(name), data).unwrap(); |
| 333 |
let blob_oid = self.repo.write_blob(data).unwrap().detach(); |
| 334 |
|
| 335 |
self.index.dangerously_push_entry( |
| 336 |
gix::index::entry::Stat::default(), |
| 337 |
blob_oid, |
| 338 |
gix::index::entry::Flags::from_stage(gix::index::entry::Stage::Unconflicted), |
| 339 |
gix::index::entry::Mode::FILE, |
| 340 |
name.as_bytes().into(), |
| 341 |
); |
| 342 |
} |
| 343 |
|
| 344 |
pub fn sync_index(&mut self) { |
| 345 |
self.index.sort_entries(); |
| 346 |
self.index.verify_entries().unwrap(); |
| 347 |
// Same contract as `update_intent_to_add_impl` in lib/src/git.rs: the |
| 348 |
// entry mutations above leave any loaded cache-tree stale, and |
| 349 |
// `write()` would re-emit it as-is. |
| 350 |
self.index.remove_tree(); |
| 351 |
self.index |
| 352 |
.write(gix::index::write::Options::default()) |
| 353 |
.unwrap(); |
| 354 |
} |
| 355 |
} |
| 356 |
|
| 357 |
pub fn add_remote(repo_dir: impl AsRef<Path>, remote_name: &str, url: &str) { |
| 358 |
let output = std::process::Command::new("git") |
| 359 |
.current_dir(repo_dir) |
| 360 |
.args(["remote", "add", remote_name, url]) |
| 361 |
.output() |
| 362 |
.unwrap(); |
| 363 |
assert!( |
| 364 |
output.status.success(), |
| 365 |
"git remote add {remote_name} {url} failed with {}:\n{}\n----- stderr -----\n{}", |
| 366 |
output.status, |
| 367 |
bstr::BString::from(output.stdout), |
| 368 |
bstr::BString::from(output.stderr), |
| 369 |
); |
| 370 |
} |
| 371 |
|
| 372 |
pub fn rename_remote(repo_dir: impl AsRef<Path>, original: &str, new: &str) { |
| 373 |
let output = std::process::Command::new("git") |
| 374 |
.current_dir(repo_dir) |
| 375 |
.args(["remote", "rename", original, new]) |
| 376 |
.output() |
| 377 |
.unwrap(); |
| 378 |
assert!( |
| 379 |
output.status.success(), |
| 380 |
"git remote rename failed with {}:\n{}\n----- stderr -----\n{}", |
| 381 |
output.status, |
| 382 |
bstr::BString::from(output.stdout), |
| 383 |
bstr::BString::from(output.stderr), |
| 384 |
); |
| 385 |
} |
| 386 |
|
| 387 |
pub fn fetch(repo_dir: impl AsRef<Path>, remote: &str) { |
| 388 |
let output = std::process::Command::new("git") |
| 389 |
.current_dir(repo_dir) |
| 390 |
.args(["fetch", remote]) |
| 391 |
.output() |
| 392 |
.unwrap(); |
| 393 |
assert!( |
| 394 |
output.status.success(), |
| 395 |
"git fetch {remote} failed with {}:\n{}\n----- stderr -----\n{}", |
| 396 |
output.status, |
| 397 |
bstr::BString::from(output.stdout), |
| 398 |
bstr::BString::from(output.stderr), |
| 399 |
); |
| 400 |
} |